text
stringlengths 2
6.14k
|
|---|
///////////////////////////////////////////////////////////////////////////////
// $Id: tut_gdal.h,v 1.4 2006/12/06 15:39:14 mloskot Exp $
//
// Project: C++ Test Suite for GDAL/OGR
// Purpose: TUT: C++ Unit Test Framework extensions for GDAL Test Suite
// Author: Mateusz Loskot <[email protected]>
//
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2006, Mateusz Loskot <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
//
// $Log: tut_gdal.h,v $
// Revision 1.4 2006/12/06 15:39:14 mloskot
// Added file header comment and copyright note.
//
//
///////////////////////////////////////////////////////////////////////////////
#ifndef TUT_GDAL_H_INCLUDED
#define TUT_GDAL_H_INCLUDED
#include <ogr_api.h> // GDAL
#include <cassert>
#include <sstream>
#include <string>
namespace tut
{
#if defined(WIN32) || defined(_WIN32_WCE)
#define SEP '\\'
#else
#define SEP '/'
#endif
//
// Template of attribute reading function and its specializations
//
template <typename T>
inline void read_feature_attribute(OGRFeatureH feature, int index, T& val)
{
assert(!"Can't find read_feature_attribute specialization for given type");
}
template <>
inline void read_feature_attribute(OGRFeatureH feature, int index, int& val)
{
val = OGR_F_GetFieldAsInteger(feature, index);
}
template <>
inline void read_feature_attribute(OGRFeatureH feature, int index, double& val)
{
val = OGR_F_GetFieldAsDouble(feature, index);
}
template <>
inline void read_feature_attribute(OGRFeatureH feature, int index, std::string& val)
{
val = OGR_F_GetFieldAsString(feature, index);
}
//
// Test equality of two OGR geometries according to passed tolerance.
//
void ensure_equal_geometries(OGRGeometryH lhs, OGRGeometryH rhs, double tolerance);
//
// Test layer attributes from given field against expected list of values
//
template <typename T>
void ensure_equal_attributes(OGRLayerH layer, std::string const& field, T const& list)
{
ensure("Layer is NULL", NULL != layer);
OGRFeatureDefnH featDefn = OGR_L_GetLayerDefn(layer);
ensure("Layer schema is NULL", NULL != featDefn);
int fldIndex = OGR_FD_GetFieldIndex(featDefn, field.c_str());
std::ostringstream os;
os << "Can't find field '" << field << "'";
ensure(os.str(), fldIndex >= 0);
// Test value in tested field from subsequent features
OGRFeatureH feat = NULL;
OGRFieldDefnH fldDefn = NULL;
typename T::value_type attrVal;
for (typename T::const_iterator it = list.begin(); it != list.end(); ++it)
{
feat = OGR_L_GetNextFeature(layer);
fldDefn = OGR_F_GetFieldDefnRef(feat, fldIndex);
ensure("Field schema is NULL", NULL != fldDefn);
read_feature_attribute(feat, fldIndex, attrVal);
OGR_F_Destroy(feat);
// Test attribute against expected value
ensure_equals("Attributes not equal", (*it), attrVal);
}
// Check if not too many features filtered
feat = OGR_L_GetNextFeature(layer);
bool notTooMany = (NULL == feat);
OGR_F_Destroy(feat);
ensure("Got more features than expected", notTooMany);
}
template <typename T>
void ensure_approx_equals(T const& a, T const& b)
{
std::ostringstream os;
os << "Approx. equality failed: " << a << " != " << b;
ensure(os.str(), fabs(1.0 * b / a - 1.0) <= .00000000001);
}
} // namespace tut
#endif // TUT_GDAL_H_INCLUDED
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#ifdef __cplusplus
extern "C" { /* C-declarations for C++ */
#endif
extern void lv_draw_wifi_list();
extern void lv_clear_wifi_list();
extern void disp_wifi_list();
extern void cutWifiName(char *name, int len,char *outStr);
extern void wifi_scan_handle();
#define NUMBER_OF_PAGE 5
#define WIFI_TOTAL_NUMBER 20
#define WIFI_NAME_BUFFER_SIZE 33
typedef struct {
int8_t getNameNum;
int8_t nameIndex;
int8_t currentWifipage;
int8_t getPage;
int8_t RSSI[WIFI_TOTAL_NUMBER];
uint8_t wifiName[WIFI_TOTAL_NUMBER][WIFI_NAME_BUFFER_SIZE];
uint8_t wifiConnectedName[WIFI_NAME_BUFFER_SIZE];
} WIFI_LIST;
extern WIFI_LIST wifi_list;
typedef struct list_menu_disp {
const char *title;
const char *file_pages;
} list_menu_def;
extern list_menu_def list_menu;
typedef struct keyboard_menu_disp {
const char *title;
const char *apply;
const char *password;
const char *letter;
const char *digital;
const char *symbol;
const char *space;
} keyboard_menu_def;
extern keyboard_menu_def keyboard_menu;
typedef struct tips_menu_disp {
const char *joining;
const char *failedJoin;
const char *wifiConected;
} tips_menu_def;
extern tips_menu_def tips_menu;
#ifdef __cplusplus
} /* C-declarations for C++ */
#endif
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Tue Jul 07 13:45:10 BST 2015 -->
<title>interactor Class Hierarchy</title>
<meta name="date" content="2015-07-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="interactor Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../input/package-tree.html">Prev</a></li>
<li><a href="../output/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?interactor/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package interactor</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">interactor.<a href="../interactor/InteractorUDP.html" title="class in interactor"><span class="strong">InteractorUDP</span></a> (implements java.lang.Runnable)
<ul>
<li type="circle">interactor.<a href="../interactor/ConsoleInteractor.html" title="class in interactor"><span class="strong">ConsoleInteractor</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../input/package-tree.html">Prev</a></li>
<li><a href="../output/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?interactor/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
'''This code uses cubic splines from to interpolate a parametrized
funtion to an arbitrary point x inside the domain.
It follows the codes in the book 'Numerical recipes for C'
'''
import numpy as np
def spline(x, y, n, yp0, ypn_1):
'''Given arrays x[0,n-1] and y[0,n-1] containing a tabulated function, i.e., yi = f(xi), with
x0 <x1 < :: : < x(N-1), and given values yp0 and ypn_1 for the first derivative of the interpolating
function at points 0 and n-1, respectively, this routine returns an array y2[0, n-1] that contains
the second derivatives of the interpolating function at the tabulated points xi. If yp0 and/or
ypn_1 are equal to 1e+30 or larger, the routine is signaled to set the corresponding boundary
condition for a natural spline, with zero second derivative on that boundary.
'''
# Create vectors
u = np.zeros(n-1)
y2 = np.zeros(n)
# Set lower boundary condition
if(yp0 > 0.99e+30):
y2[0] = 0.
u[0] = 0.
else:
y2[0] = -0.5
u[0] = (3.0/(x[1]-x[0])) * ((y[1]-y[0])/(x[1]-x[0]) - yp0)
# Decomposition loop
for i in range(1,n-1):
sig = (x[i]-x[i-1]) / (x[i+1]-x[i-1])
p = sig * y2[i-1] + 2.0
y2[i] = (sig-1.0) / p
u[i] = (y[i+1]-y[i]) / (x[i+1]-x[i]) - (y[i]-y[i-1]) / (x[i]-x[i-1])
u[i] = ( 6.0*u[i]/(x[i+1]-x[i-1]) - sig*u[i-1] ) / p
#u[i] = (6.0 * ((y[i+1]-y[i])/(x[i+1]-x[i])-(y[i]-y[i-1]) / (x[i]-x[i-1]))/(x[i+1]-x[i-1])-sig*u[i-1]) / p
# Set upper boundary condition
if(ypn_1 > 0.99e+30):
qn_1 = 0.0
un_1 = 0.0
else:
qn_1 = 0.5
un_1 = (3.0/(x[n-1]-x[n-2])) * (ypn_1 - (y[n-1]-y[n-2])/(x[n-1]-x[n-2]))
# Backsustitution algorithm
y2[n-1] = (un_1 - qn_1*u[n-2]) / (qn_1*y2[n-2] + 1.0)
for i in range(n-2,-1,-1):
y2[i] = y2[i]*y2[i+1] + u[i]
return y2
def splint(xa, ya, y2a, n, x):
'''Given the arrays xa[0, n-1] and ya[0, n-1], which tabulate a function (with the xai's in order),
and given the array y2a[0, n-1], which is the output from spline above, and given a value of
x, this routine returns a cubic-spline interpolated value y.
'''
klo = 0
khi = n-1
# Find the right place in the table
while(khi-klo > 1):
k = (khi + klo) >> 1
if(xa[k] > x):
khi=k
else:
klo=k
h = xa[khi] - xa[klo]
if(h == 0):
print('Bad xa input to routine splint')
return 1e+999
a = (xa[khi]-x) / h
b = (x-xa[klo]) / h
y = a*ya[klo] + b*ya[khi] + ((a**3-a)*y2a[klo] + (b**3-b)*y2a[khi])*(h**2) / 6.0
return y
|
import React from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Rated } from '../collection';
import { RatingBrowserComponent } from '../components/RatingBrowserComponent.js';
const RatingBrowserContainer = createContainer((data) => {
console.log(data);
const { params, route } = data;
const tag = params.tag || 'general';
let ratingUrl = Meteor.absoluteUrl() + route.data.apiPath + '?tag=' + tag + '&uri=';
console.log('tag', tag, ratingUrl)
const query = {};
query['ratings.' + tag] = {$exists: 1};
const ratedHandle = Meteor.subscribe('rated', query);
const loading = !ratedHandle.ready();
const rated = Rated.find({}).fetch();
const ratedExists = !loading && !!rated;
return {
tag,
ratingUrl,
loading,
rated,
ratedExists
};
}, RatingBrowserComponent);
export { RatingBrowserContainer };
|
// footer to wrap "source-map" module
return this.sourceMap;
}();
})();
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>zLineArray(...)</title>
<link rel="stylesheet" href="../../stylesheets/pygeodoc.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO8859-1" />
<meta type="description" content="rest2web - build websites with Python and docutils." />
<meta type="keywords" content="PyGeo - a dynamic geometry toolkit,geometry, dynamic geoemtry,
python, vpython " />
</head>
<body>
<div id="header">
<a href="http://home.netcom.com/~ajs"></a>
<span id="pygeo1">PyGeo:</span>
<span id="pygeo2">a dynamic geometry toolkit</span>
</div>
<div id="nav">
<ul>
<li><a href="../../index.html">Docs</a></li> <li>></li> <li><a href="../index.html">Complex Numbers</a></li> <li>></li> <li><a href="index.html">Complex Plane</a></li> <li>></li> <li>zlinearrays</li>
</ul>
</div>
<table align="center" border="0" cellspacing="0" cellpadding="0" summary="Page layout" id="whole">
<tr>
<td class="sidie" valign="top" align="left">
<div <img src="../../images/pointconic.gif" width="200" height="150" border="1" alt="PyGeo website" />
<ul>
<div style="margin:10px">
<li id="sub"><strong><a id="sub" href="../../index.html">Docs</a></strong>
</li>
<li><a href="../../quickstart.html">QuickStart</a>
</li>
<li><a href="../../real/index.html">Real 3d Space</a>
</li>
<div style="margin:10px">
<li id="sub"><strong><a id="sub" href="../index.html">Complex Numbers</a></strong>
</li>
<div style="margin:10px">
<li id="sub"><strong><a id="sub" href="index.html">Complex Plane</a></strong>
</li>
<li><a href="complex_plane_abstracts.html">zPlane Abstracts</a>
</li>
<li><a href="zPoints.html">zpoints</a>
</li>
<li><a href="zfree_point.html">zfreepoint</a>
</li>
<li><a href="zsliders.html">zsliders</a>
</li>
<li><a href="z_anipoints.html">zanipoints</a>
</li>
<li><a href="z_lines.html">zlines</a>
</li>
<li><a href="z_circles.html">zcircles</a>
</li>
<li><a href="z_pointpencils.html">zpointarrays</a>
</li>
<li><a href="z_linearrays.html">zlinearrays</a>
</li>
<li><a href="z_circlepencils.html">zcirclepencils</a>
</li>
<li><a href="mobtransforms.html">ztransforms</a>
</li>
</div>
<li><a href="../unit sphere/index.html">Riemann sphere</a>
</li>
</div>
</div>
</ul>
</div>
</td>
<td class="docs" valign="top" align="left" width="100%">
<div id="main">
<a name="startcontent" id="startcontent"></a>
<div class="document" id="zlinearray">
<h1 class="title"><strong>zLineArray(...)</strong></h1>
<div class="contents topic">
<p class="topic-title first"><a id="contents" name="contents">Contents</a></p>
<ul class="simple">
<li><a class="reference" href="#def-zlinearray" id="id2" name="id2">def zLineArray</a><ul>
<li><a class="reference" href="#class-zlinepencil" id="id3" name="id3">class zLinePencil</a></li>
</ul>
</li>
</ul>
</div>
<p>Objects derived from the <a class="reference" href="complex_plane_abstracts.html#class-zlinearray">_zLineArray</a> abstract class,
representing an array of lines with determined positions
on the <a class="reference" href="http://mathworld.wolfram.com/ComplexPlane.html">complex plane</a></p>
<div class="section">
<h1><a class="toc-backref" href="#id2" id="def-zlinearray" name="def-zlinearray">def zLineArray</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">constructors:</th><td class="field-body"><ul class="first simple">
<li>zLineArray(zpoint); calls: <a class="reference" href="#class-zlinepencil">class zLinePencil</a></li>
</ul>
</td>
</tr>
<tr class="field"><th class="field-name">returns:</th><td class="field-body"><p class="first last">An instance of an object derived from the <a class="reference" href="complex_plane_abstracts.html#class-zlinearray">_zLineArray</a> abstract class,
representing an array of infinite lines of the <a class="reference" href="http://mathworld.wolfram.com/ComplexPlane.html">complex plane</a></p>
</td>
</tr>
</tbody>
</table>
<div class="section">
<h2><a class="toc-backref" href="#id3" id="class-zlinepencil" name="class-zlinepencil">class zLinePencil</a></h2>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">constructors:</th><td class="field-body"><ul class="first simple">
<li>zLineArray(zpoint)</li>
<li>zLinePencil(zpoint)</li>
</ul>
</td>
</tr>
<tr class="field"><th class="field-name">returns:</th><td class="field-body"><p class="first">array of equidistant lines on the <a class="reference" href="http://mathworld.wolfram.com/ComplexPlane.html">complex plane</a> and through the given point</p>
</td>
</tr>
<tr class="field"><th class="field-name">site ref:</th><td class="field-body"><p class="first last"><a class="reference" href="http://mathworld.wolfram.com/Pencil.html">http://mathworld.wolfram.com/Pencil.html</a></p>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div id="end">
<p><a href="#startcontent">Return to Top</a><br />
</p>
</div>
</div>
</td>
</tr>
</table>
</body></html>
|
/**
* Copyright (c) 2017. The WRENCH Team.
*
* 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.
*/
#include <wrench/services/compute/ComputeServiceProperty.h>
namespace wrench {
};
|
import * as express from 'express';
import * as routes from './routes';
import * as cors from 'cors';
export class Application {
public app: express.Application;
/**
* Bootstrap the application.
*
* @class Server
* @method bootstrap
* @static
* @return {ng.auto.IInjectorService} Returns the newly created injector for this this.app.
*/
public static bootstrap(): Application {
return new Application();
}
/**
* Constructor.
*
* @class Server
* @constructor
*/
constructor() {
// Application instantiation
this.app = express();
// configure this.application
this.config();
// configure routes
this.setupRoutes();
this.app.locals.sessions = [] as { nom: string, ip: string }[];
}
private config() {
// Middlewares configuration
this.app.use(cors());
}
/**
* The routes function.
*
* @class Server
* @method routes
*/
public setupRoutes() {
let router: express.Router;
router = express.Router();
// create routes
const ping = new routes.PingAPI();
// API routes
router.get('/ping', ping.get.bind(ping.get));
// use router middleware
this.app.use(router);
// Routes not matched by then return 404 error
this.app.use((_req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(404).json({
message: 'Not found',
error: '404'
});
});
// development error handler
// will print stacktrace
if (this.app.get('env') === 'development') {
this.app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(err.status || 500);
res.send({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user (in production env only)
this.app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(err.status || 500);
res.send({
message: err.message,
error: {}
});
});
}
}
|
using System;
using System.Xml.Serialization;
using PlanetbaseSaveGameEditor.Core.Models.SaveGameModels.Attributes;
namespace PlanetbaseSaveGameEditor.Core.Models.SaveGameModels
{
[XmlRoot(ElementName = "manufacture-limits")]
public class ManufactureLimitsCore
{
[XmlElement(ElementName = "bot-limit")]
public ValueAttribute<Int32> BotLimit { get; set; }
[XmlElement(ElementName = "MedicalSupplies-limit")]
public ValueAttribute<Int32> MedicalSuppliesLimit { get; set; }
[XmlElement(ElementName = "Spares-limit")]
public ValueAttribute<Int32> SparesLimit { get; set; }
[XmlElement(ElementName = "Semiconductors-limit")]
public ValueAttribute<Int32> SemiconductorsLimit { get; set; }
[XmlElement(ElementName = "Gun-limit")]
public ValueAttribute<Int32> GunLimit { get; set; }
}
}
|
/************************************************************************
AvalonDock
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the New BSD
License (BSD) as published at http://avalondock.codeplex.com/license
For more features, controls, and fast professional support,
pick up AvalonDock in Extended WPF Toolkit Plus at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like facebook.com/datagrids
**********************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Xceed.Wpf.AvalonDock.Themes
{
public abstract class Theme : DependencyObject
{
public Theme()
{
}
public abstract Uri GetResourceUri();
}
}
|
#!/usr/bin/env python
# coding=utf-8
from flask import g, request, url_for, redirect, make_response, abort, Blueprint, current_app
from flask.views import MethodView
from .template import render_template
from .ext import pager
# from flaskcms.modules.post.view import PostView
class CommonView(MethodView):
'''通用视图的基类
model:
模块对应的数据库model
category:
模块的名称
channels:
模块里面拥有的channel
'''
model = None
category = ""
channels = []
def get_template_name(self, channel):
if channel in self.channels:
template = self.category+'_'+channel+'.html'
else:
return abort(404)
return template
def get_contents(self, channel):
if channel == 'list':
return self.get_list()
elif channel == 'detail':
return self.get_detail()
else:
return {}
def get_detail(self,id=None):
if not id:
id = int(request.args.get('id', 1))
item = self.model.query.get(id)
return {self.category: item}
def get_list(self):
page = int(request.args.get('page', 1))
step = int(request.args.get('step', 5))
offset = (page-1)*step
list, count = self.get_list_preprocess(offset, step)
if not list.count():
self.get_list_or_404()
pagerObj = pager(step, step, page, count)
data = {self.category+'List': list, 'count': count,
'page': page, 'step': step, 'pagerObj': pagerObj}
return self.get_list_extra(data)
def get_list_preprocess(self, offset, step):
list = self.model.query.order_by(
self.model.time.desc()).offset(offset).limit(step)
count = self.model.query.count()
return [list, count]
def get_list_extra(self, data):
return data
def get(self, channel):
contents = self.get_contents(channel)
return render_template(self.get_template_name(channel), **contents)
def get_list_or_404(self):
return {}
# return abort(404)
|
import os
from atila import Atila
import skitai
app = Atila (__name__)
app.debug = True
app.use_reloader = True
app.jinja_overlay ()
@app.route ("/")
def index (was):
return was.render ("index.html")
@app.route ("/documentation")
def documentation (was):
req = was.get ("https://pypi.python.org/pypi/skitai")
pypi_content = "<h4><p>It seems some problem at <a href='https://pypi.python.org/pypi/skitai'>PyPi</a>.</p></h4><p>Please visit <a href='https://pypi.python.org/pypi/skitai'> https://pypi.python.org/pypi/skitai</a></p>"
rs = req.dispatch (timeout = 10)
if rs.data:
content = rs.data
s = content.find ('<div class="section">')
if s != -1:
e = content.find ('<a name="downloads">', s)
if e != -1:
pypi_content = "<h4>This contents retrieved right now using skitai was service from <a href='https://pypi.python.org/pypi/skitai'> https://pypi.python.org/pypi/skitai</a></h4>" + content [s:e]
return was.render ("documentation.html", content = pypi_content)
@app.route ("/documentation2")
def documentation2 (was):
def response (was, rss):
rs = rss [0]
pypi_content = "<h3>Error</h3>"
if rs.data:
content = rs.data
s = content.find ('<div class="project-description">')
if s != -1:
e = content.find ('<div id="history"', s)
if e != -1:
content = "<h4>This contents retrieved right now using skitai was service from <a href='https://pypi.org/project/skitai/'> https://pypi.org/project/skitai/</a></h4>" + content [s:e]
print (content)
print (type (content))
assert "Internet :: WWW/HTTP :: WSGI" in content
return was.render ("documentation2.html", skitai = content)
reqs = [was.get ("@pypi/project/skitai/", headers = [("Accept", "text/html")])]
return was.futures (reqs).then (response)
@app.route ("/hello")
def hello (was, num = 1):
was.response ["Content-Type"] = "text/plain"
return "\n".join (["hello" for i in range (int(num))])
@app.route ("/redirect1")
def redirect1 (was):
return was.response ("301 Object Moved", "", headers = [("Location", "/redirect2")])
@app.route ("/redirect2")
def redirect2 (was):
return was.response ("301 Object Moved", "", headers = [("Location", "/")])
@app.route ("/upload")
def upload (was, **karg):
return was.response ("200 OK", str (karg), headers = [("Content-Type", "text/plain")])
@app.route ("/post")
def post (was, username):
return 'USER: %s' % username
if __name__ == "__main__":
import skitai
skitai.alias ("@pypi", skitai.PROTO_HTTPS, "pypi.org")
skitai.mount ("/", 'statics')
skitai.mount ("/", app)
skitai.mount ("/websocket", 'websocket.py')
skitai.mount ("/rpc2", 'rpc2.py')
skitai.mount ("/routeguide.RouteGuide", 'grpc_route_guide.py')
skitai.mount ("/members", 'auth.py')
skitai.mount ("/lb", "@pypi")
skitai.enable_proxy ()
skitai.run (
workers = 3,
address = "0.0.0.0",
port = 30371
)
|
<?php
/**
* ShopEx licence
*
* @copyright Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
* @license http://ecos.shopex.cn/ ShopEx License
*/
/**
* PHPUnit
*
* Copyright (c) 2002-2007, Sebastian Bergmann <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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.
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2007 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id: Test.php 537 2007-02-24 06:58:18Z sb $
* @link http://www.phpunit.de/
* @since File available since Release 2.0.0
*/
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Util/Filter.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
if (!interface_exists('PHPUnit_Framework_Test', FALSE)) {
/**
* A Test can be run and collect its results.
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2007 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 3.1.3
* @link http://www.phpunit.de/
* @since Interface available since Release 2.0.0
*/
interface PHPUnit_Framework_Test extends Countable
{
/**
* Runs a test and collects its result in a TestResult instance.
*
* @param PHPUnit_Framework_TestResult $result
* @return PHPUnit_Framework_TestResult
* @access public
*/
public function run(PHPUnit_Framework_TestResult $result = NULL);
}
}
?>
|
//------------------------------------------------------------------------------
// <copyright company="LeanKit Inc.">
// Copyright (c) LeanKit Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IntegrationService.Targets.GitHub")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IntegrationService.Targets.GitHub")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b259063-8622-4b03-b289-2964ff0c14a1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
// Code from https://github.com/benelog/multiline.git
// Based on Adrian Walker's blog post: http://www.adrianwalker.org/2011/12/java-multiline-string.html
package org.adrianwalker.multilinestring;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import org.eclipse.jdt.internal.compiler.apt.model.VariableElementImpl;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import java.lang.reflect.Constructor;
@SupportedAnnotationTypes({"org.adrianwalker.multilinestring.Multiline"})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public final class EcjMultilineProcessor extends AbstractProcessor {
private Elements elementUtils;
@Override
public void init(final ProcessingEnvironment procEnv) {
super.init(procEnv);
this.elementUtils = procEnv.getElementUtils();
}
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
Set<? extends Element> fields = roundEnv.getElementsAnnotatedWith(Multiline.class);
for (Element field : fields) {
String docComment = elementUtils.getDocComment(field);
if (null != docComment) {
VariableElementImpl fieldElem = (VariableElementImpl) field;
FieldBinding biding = (FieldBinding) fieldElem._binding;
FieldDeclaration decl = biding.sourceField();
StringLiteral string = new StringLiteral(docComment.toCharArray(), decl.sourceStart, decl.sourceEnd, decl.sourceStart);
decl.initialization = string;
}
}
return true;
}
}
|
# -*- coding: utf-8 -*-
from collections import Sized
import numpy as np
from sklearn.base import clone
from sklearn.externals.joblib import Parallel, delayed
from sklearn.grid_search import GridSearchCV, ParameterGrid, _CVScoreTuple
from sklearn.metrics.scorer import check_scoring
from splearn.base import SparkBaseEstimator
from splearn.cross_validation import _check_cv, _fit_and_score
class SparkGridSearchCV(GridSearchCV, SparkBaseEstimator):
def _fit(self, Z, parameter_iterable):
"""Actual fitting, performing the search over parameters."""
self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)
cv = self.cv
cv = _check_cv(cv, Z)
if self.verbose > 0:
if isinstance(parameter_iterable, Sized):
n_candidates = len(parameter_iterable)
print("Fitting {0} folds for each of {1} candidates, totalling"
" {2} fits".format(len(cv), n_candidates,
n_candidates * len(cv)))
base_estimator = clone(self.estimator)
pre_dispatch = self.pre_dispatch
out = Parallel(
n_jobs=self.n_jobs, verbose=self.verbose,
pre_dispatch=pre_dispatch, backend="threading"
)(
delayed(_fit_and_score)(clone(base_estimator), Z, self.scorer_,
train, test, self.verbose, parameters,
self.fit_params, return_parameters=True,
error_score=self.error_score)
for parameters in parameter_iterable
for train, test in cv)
# Out is a list of triplet: score, estimator, n_test_samples
n_fits = len(out)
n_folds = len(cv)
scores = list()
grid_scores = list()
for grid_start in range(0, n_fits, n_folds):
n_test_samples = 0
score = 0
all_scores = []
for this_score, this_n_test_samples, _, parameters in \
out[grid_start:grid_start + n_folds]:
all_scores.append(this_score)
if self.iid:
this_score *= this_n_test_samples
n_test_samples += this_n_test_samples
score += this_score
if self.iid:
score /= float(n_test_samples)
else:
score /= float(n_folds)
scores.append((score, parameters))
# TODO: shall we also store the test_fold_sizes?
grid_scores.append(_CVScoreTuple(
parameters,
score,
np.array(all_scores)))
# Store the computed scores
self.grid_scores_ = grid_scores
# Find the best parameters by comparing on the mean validation score:
# note that `sorted` is deterministic in the way it breaks ties
best = sorted(grid_scores, key=lambda x: x.mean_validation_score,
reverse=True)[0]
self.best_params_ = best.parameters
self.best_score_ = best.mean_validation_score
if self.refit:
# fit the best estimator using the entire dataset
# clone first to work around broken estimators
best_estimator = clone(base_estimator).set_params(
**best.parameters)
best_estimator.fit(Z, **self.fit_params)
self.best_estimator_ = best_estimator
return self
def fit(self, Z):
return self._fit(Z, ParameterGrid(self.param_grid))
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack LLC.
# 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.
from nova.api.openstack import common
class ViewBuilder(object):
def build(self, flavor_obj, is_detail=False):
"""Generic method used to generate a flavor entity."""
if is_detail:
flavor = self._build_detail(flavor_obj)
else:
flavor = self._build_simple(flavor_obj)
self._build_extra(flavor)
return flavor
def _build_simple(self, flavor_obj):
"""Build a minimal representation of a flavor."""
return {
"id": flavor_obj["flavorid"],
"name": flavor_obj["name"],
}
def _build_detail(self, flavor_obj):
"""Build a more complete representation of a flavor."""
simple = self._build_simple(flavor_obj)
detail = {
"ram": flavor_obj["memory_mb"],
"disk": flavor_obj["local_gb"],
}
detail.update(simple)
return detail
def _build_extra(self, flavor_obj):
"""Hook for version-specific changes to newly created flavor object."""
pass
class ViewBuilderV11(ViewBuilder):
"""Openstack API v1.1 flavors view builder."""
def __init__(self, base_url):
"""
:param base_url: url of the root wsgi application
"""
self.base_url = base_url
def _build_extra(self, flavor_obj):
flavor_obj["links"] = self._build_links(flavor_obj)
def _build_links(self, flavor_obj):
"""Generate a container of links that refer to the provided flavor."""
href = self.generate_href(flavor_obj["id"])
links = [
{
"rel": "self",
"href": href,
},
{
"rel": "bookmark",
"type": "application/json",
"href": href,
},
{
"rel": "bookmark",
"type": "application/xml",
"href": href,
},
]
return links
def generate_href(self, flavor_id):
"""Create an url that refers to a specific flavor id."""
return "%s/flavors/%s" % (self.base_url, flavor_id)
|
package leaks.ContainsKeyNoRefute;
import edu.colorado.thresher.external.Annotations.*;
import java.util.HashMap;
import java.util.Map;
@noStaticRef public class Act {
int size;
public Act() {}
public static Map<String,Object> storyCache = new HashMap<String,Object>();
public static void main(String[] args) {
Map<String,Act> localMap = new HashMap<String,Act>();
if (localMap.containsKey("b")) {
int boogalo = 3;
}
localMap.put("a", new Act());
storyCache.put("b", new Act());
}
}
|
/* Copyright (C) 2013-2015 Computer Sciences Corporation
*
* 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 <ezbake/ezdiscovery/ServiceDiscoveryExceptions.h>
#include <boost/shared_ptr.hpp>
namespace ezbake { namespace ezdiscovery {
const std::string ServiceDiscoveryException::NAME = "ServiceDiscoveryException";
ServiceDiscoveryException::ServiceDiscoveryException(const ::std::string& message,
const ::std::string& component, const ::std::string& location, const Exception* reason)
: ::hadoop::Exception(message, component, location, reason)
{}
/*
* Create a clone of this exception
*
* @return - the clone
*/
ServiceDiscoveryException* ServiceDiscoveryException::clone() const {
boost::shared_ptr<ServiceDiscoveryException> p(new ServiceDiscoveryException(*this));
return p.get();
}
/*
* Get the name of this exception
*
* @return the name of this exception as char*
*/
const char* ServiceDiscoveryException::getTypename() const {
return NAME.c_str();
}
}} // namespace ::ezbake::ezdiscovery
|
import os
import matplotlib
import matplotlib.pylab as plt
import astropy.io.fits as fits
import numpy as np
def get_title_from_filename(filename):
"""
Generate title by parsing filename
Args:
filename: pull path to file
Return:
title: title to plot
"""
filepath_args = filename.split(os.path.sep)
objname = filepath_args[-4]
objname = objname.replace("_", " ")
dateband = filepath_args[-2].split("_")
date = dateband[0]
date = "{0}-{1}-{2}".format(date[0:4], date[4:6], date[6:8])
band = dateband[1]
mode = dateband[2]
title = "{obj} {date} {band}-{mode}".format(obj=objname, date=date, band=band, mode=mode)
return title
def save_klcube_image(filename, outputname, title=None):
"""
Open the PSF Subtraction saved as a KL Mode Cube and write the image as a PNG
in the path as specified by outputname
Args:
filename: path to KL Mode cube to display
outputname: output PNG filepath
title: title of saved PNG plot
Return:
None
"""
hdulist = fits.open(filename)
klcube = hdulist[1].data
frame50 = klcube[3]
band = hdulist[0].header['IFSFILT'].split("_")[1]
hdulist.close()
# rough throuhghput calibration
if 'methane' in filename:
throughput_corr = 1.1
else:
throughput_corr = 0.65
frame50 /= throughput_corr
# make strictly positive for log stretch
minval = np.nanmin(frame50) - 1
log_frame = np.log(frame50 - minval)
# use statistics only from the middle of the image
y,x = np.indices(frame50.shape)
r = np.sqrt((x-140)**2 + (y-140)**2)
if band =='J' or band =='Y':
innerradii = 100
else:
innerradii = 80
innerregion = np.where((r < innerradii))
limits = [-3.e-7, np.min([np.nanpercentile(frame50[innerregion], 99.9), 8.e-5])]
# set colormap to have nans as black
cmap = matplotlib.cm.viridis
cmap.set_bad('k',1.)
# plot
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(log_frame, cmap=cmap, vmin=np.log(limits[0]-minval), vmax=np.log(limits[1]-minval))
ax.invert_yaxis()
#add colorbar
cbar = plt.colorbar(im, orientation='vertical', shrink=0.9, pad=0.015, ticks=[np.log(limits[0]-minval),np.log(-minval), (np.log(limits[0]-minval)*2 + np.log(limits[1]-minval))/3., (np.log(limits[0]-minval) + np.log(limits[1]-minval)*2)/3. ,np.log(limits[1]-minval)])
cbar.ax.set_yticklabels(["{0:.1e}".format(limits[0]), "0", "{0:.1e}".format((np.exp((np.log(limits[0]-minval)*2 + np.log(limits[1]-minval))/3))+minval), "{0:.1e}".format((np.exp((np.log(limits[0]-minval) + np.log(limits[1]-minval)*2)/3))+minval), "{0:.1e}".format(limits[1])])
cbar.set_label("Contrast", fontsize=12)
cbar.ax.tick_params(labelsize=12)
ax.set_title(title)
plt.savefig(outputname)
# For testing purposes only
if __name__ == "__main__":
save_klcube_image('C:\\Users\\jwang\\OneDrive\\GPI\\data\\Reduced\\hd95086\\pyklip-S20160229-H-k150a9s4m1-KLmodes-all.fits', "tmp.png", "HD 95086 2016-02-29 H-Spec")
|
/*
* Copyright (c) 2016 by Alexander Schroeder
*/
#include "directx_vertex_buffer.hpp"
#include "directx_render_context_base.hpp"
#include "directx_error.hpp"
#include "directx_index_buffer.hpp"
#include "directx_render_step.hpp"
#include "directx_vertex_buffer.hpp"
namespace agge {
namespace directx {
render_context_base::render_context_base(
const agge::graphics::dimension& d)
: agge::graphics::render_context(d),
m_device(nullptr),
m_devicecontext(nullptr),
m_rendertargetview(nullptr),
m_no_depth_test_stencil_state(nullptr)
{
}
render_context_base::~render_context_base()
{
if (m_no_depth_test_stencil_state) {
m_no_depth_test_stencil_state->Release();
}
}
void render_context_base::on_make_current()
{
}
agge::graphics::vertex_buffer_ref render_context_base::create_vertex_buffer(
const agge::graphics::vertex_buffer_attributes& attributes,
size_t size)
{
auto result = std::make_shared<vertex_buffer>(self(), attributes,
size);
return result;
}
agge::graphics::index_buffer_ref render_context_base::create_index_buffer(
agge::graphics::index_type type, size_t size)
{
auto result = std::make_shared<index_buffer>(self(), type, size);
return result;
}
void render_context_base::on_clear(
const agge::graphics::rgba_color& color)
{
float rgba[4] = { color.r, color.g, color.b, 1.0f };
m_devicecontext->ClearRenderTargetView(m_rendertargetview, rgba);
}
ID3D11DepthStencilState * render_context_base::get_no_depth_test_stencil_state()
{
using agge::core::illegal_state;
if (m_no_depth_test_stencil_state == nullptr) {
if (!m_device) {
throw AGGE_EXCEPTION(illegal_state) << "No device";
}
D3D11_DEPTH_STENCIL_DESC desc;
desc.DepthEnable = FALSE;
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
desc.DepthFunc = D3D11_COMPARISON_LESS;
desc.StencilEnable = FALSE;
desc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
desc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
desc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
desc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
HRESULT rc = m_device->CreateDepthStencilState(
&desc, &m_no_depth_test_stencil_state);
CHECK_DIRECTX_ERROR(CreateDepthStencilState, rc);
}
return m_no_depth_test_stencil_state;
}
void render_context_base::on_set_depth_test(bool value)
{
if (value) {
m_devicecontext->OMSetDepthStencilState(NULL, 0);
} else {
m_devicecontext->OMSetDepthStencilState(
get_no_depth_test_stencil_state(), 0);
}
return;
}
agge::graphics::texture_ref render_context_base::create_texture()
{
AGGE_THROW_NOT_IMPLEMENTED;
}
agge::graphics::render_step_ref render_context_base::create_render_step()
{
return std::make_shared<render_step>(m_device, m_devicecontext,
self());
}
}
}
|
// Copyright Hugh Perkins 2006
//
// 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;
//
// 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 in the file licence.txt; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
// 1307 USA
// You can find the licence also on the web at:
// http://www.opensource.org/licenses/gpl-license.php
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Net;
namespace OSMP
{
public class XmlCommands
{
// use singleton so only create a single xmlserializer
static XmlCommands instance = new XmlCommands();
public static XmlCommands GetInstance() { return instance; }
XmlCommands()
{
xmlserializer = new XmlSerializer( typeof( Command ),
new Type[] {
typeof( ServerInfo ),
typeof( PingMe )
} );
}
public string Encode( Command cmd )
{
StringWriter stringwriter = new StringWriter();
xmlserializer.Serialize( stringwriter, cmd );
string message = stringwriter.ToString().Replace( "\n", "" ).Replace( "\r", "" );
stringwriter.Close();
return message;
}
public Command Decode( string message )
{
try
{
StringReader stringreader = new StringReader( message );
return xmlserializer.Deserialize( stringreader ) as Command;
}
catch
{
return null;
}
}
XmlSerializer xmlserializer;
public class Command
{
}
public class ServerInfo : Command
{
public byte[] IPAddress;
public int port;
public ServerInfo(){}
public ServerInfo( IPAddress ipaddress, int port )
{
this.IPAddress = ipaddress.GetAddressBytes();
this.port = port;
}
public override string ToString()
{
return "ServerInfo: " + new IPAddress( IPAddress ).ToString() + " " + port;
}
}
public class PingMe : Command
{
public byte[] MyIPAddress;
public int Myport;
public PingMe(){}
public PingMe( IPAddress MyIPAddress, int Myport )
{
this.MyIPAddress = MyIPAddress.GetAddressBytes();
this.Myport = Myport;
}
public override string ToString()
{
return "ClientInfo: " + new IPAddress( MyIPAddress ).ToString() + " " + Myport;
}
}
}
}
|
from .module import Module
from .. import functional as F
from ..._jit_internal import weak_module, weak_script_method
@weak_module
class PixelShuffle(Module):
r"""Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)`
to a tensor of shape :math:`(C, H \times r, W \times r)`.
This is useful for implementing efficient sub-pixel convolution
with a stride of :math:`1/r`.
Look at the paper:
`Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network`_
by Shi et. al (2016) for more details.
Args:
upscale_factor (int): factor to increase spatial resolution by
Shape:
- Input: :math:`(N, C \times \text{upscale_factor}^2, H, W)`
- Output: :math:`(N, C, H \times \text{upscale_factor}, W \times \text{upscale_factor})`
Examples::
>>> pixel_shuffle = nn.PixelShuffle(3)
>>> input = torch.randn(1, 9, 4, 4)
>>> output = pixel_shuffle(input)
>>> print(output.size())
torch.Size([1, 1, 12, 12])
.. _Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network:
https://arxiv.org/abs/1609.05158
"""
__constants__ = ['upscale_factor']
def __init__(self, upscale_factor):
super(PixelShuffle, self).__init__()
self.upscale_factor = upscale_factor
@weak_script_method
def forward(self, input):
return F.pixel_shuffle(input, self.upscale_factor)
def extra_repr(self):
return 'upscale_factor={}'.format(self.upscale_factor)
|
"""@package API
API documentation
"""
from django.contrib.auth import login, authenticate
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .forms import UserCreateForm
from MeancoApp.models import Profile
##Register user, and create a profile.
@csrf_exempt
def register(request):
if request.method == "POST":
form = UserCreateForm(request.POST)
if form.is_valid():
try:
form.save(True)
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
)
profile=Profile(user_id=new_user.id)
profile.save()
return HttpResponse(json.dumps({
"UserId": new_user.id}),
status=200,
content_type="application/json")
except:
return HttpResponse("User Creation Error",status=400)
return JsonResponse(form.errors)
return HttpResponse("Wrong Request!",status=400)
## login Request API function.
# Example Login Request:
# username= John
# password = secret
@csrf_exempt
def login(request):
if request.method == "POST":
username=request.POST.get("username")
password=request.POST.get("password")
user = authenticate(username=username, password=password)
print(user)
if user is not None:
return HttpResponse(json.dumps({
"UserId": user.id}),
status=200,
content_type="application/json")
else:
return HttpResponse("username or password error", status=400)
return HttpResponse("Wrong Request!",status=400)
|
<?php
/**
* Created by PhpStorm.
* User: es.sitnikov
* Date: 07.12.2016
* Time: 15:52
*/
/* @var $this yii\web\View */
use yii\helpers\Url;
$this->title = 'Магнитные панели на холодильник - ' . $theme['name'];
$this->params['breadcrumbs'][] = ['label' => 'Магнитные панели на холодильник', 'url' => ['site/catalog']];
$this->params['breadcrumbs'][] = $theme['name'];
?>
<div class="site-index">
<div class="row" style="text-align: center;">
<h1>Магнитные панели на холодильник <br> <?= $theme['name'] ?></h1>
</div>
<div class="body-content">
<div class="row">
<?php foreach($products as $product){ ?>
<div class="col-lg-4 col-md-6" style="text-align: center;">
<a href="<?= Url::to(['/product', 'id' => $product['id']]) ?>">
<img src="/img/product/<?= $product['id'] . '/id_' . $product['id'] ?>_350x350.jpg" style="height:350px; width:350px;" />
</a>
<div style="margin-top: -34px;">
<a href="/magnitnaya-panel-na-holodilnik-<?= $product['name_translit'] ?>.html"><button style="color: #FFF; border:0; height: 34px; width: 350px; background-color: rgba(0,0,0,0.5);"><?= strtoupper($type['name'] . ' - ' . $product['name']) ?></button></a>
</div><p></p>
</div>
<?php } ?>
</div>
</div>
</div>
|
from __future__ import unicode_literals, division, absolute_import
import logging
import base64
from flexget import plugin
from flexget.event import event
from flexget.utils import json
from flexget.utils.template import RenderError
from flexget.config_schema import one_or_more
log = logging.getLogger('pushbullet')
pushbullet_url = 'https://api.pushbullet.com/api/pushes'
class OutputPushbullet(object):
"""
Example::
pushbullet:
apikey: <API_KEY>
device: <DEVICE_IDEN> (can also be a list of device idens, or don't specify any idens to send to all devices)
[title: <MESSAGE_TITLE>] (default: "{{task}} - Download started" -- accepts Jinja2)
[body: <MESSAGE_BODY>] (default: "{{series_name}} {{series_id}}" -- accepts Jinja2)
Configuration parameters are also supported from entries (eg. through set).
"""
default_body = ('{% if series_name is defined %}{{tvdb_series_name|d(series_name)}} {{series_id}} '
'{{tvdb_ep_name|d('')}}{% elif imdb_name is defined %}{{imdb_name}} '
'{{imdb_year}}{% else %}{{title}}{% endif %}')
schema = {
'type': 'object',
'properties': {
'apikey': {'type': 'string'},
'device': one_or_more({'type': 'string'}),
'title': {'type': 'string', 'default': '{{task}} - Download started'},
'body': {'type': 'string', 'default': default_body},
'url': {'type': 'string'},
},
'required': ['apikey'],
'additionalProperties': False
}
# Run last to make sure other outputs are successful before sending notification
@plugin.priority(0)
def on_task_output(self, task, config):
# Support for multiple devices
devices = config.get('device')
if not isinstance(devices, list):
devices = [devices]
# Support for urls
push_type = 'link' if config.has_key('url') else 'note'
# Set a bunch of local variables from the config
apikey = config['apikey']
client_headers = {'Authorization': 'Basic %s' % base64.b64encode(apikey)}
if task.options.test:
log.info('Test mode. Pushbullet configuration:')
log.info(' API_KEY: %s' % apikey)
log.info(' Type: %s' % push_type)
log.info(' Device: %s' % devices)
# Loop through the provided entries
for entry in task.accepted:
title = config['title']
body = config['body']
url = config.get('url', '')
# Attempt to render the title field
try:
title = entry.render(title)
except RenderError as e:
log.warning('Problem rendering `title`: %s' % e)
title = 'Download started'
# Attempt to render the body field
try:
body = entry.render(body)
except RenderError as e:
log.warning('Problem rendering `body`: %s' % e)
body = entry['title']
# Attempt to render the url field
if push_type is 'link':
try:
url = entry.render(url)
except RenderError as e:
log.warning('Problem rendering `url`: %s' % e)
for device in devices:
# Build the request
data = {'type': push_type, 'title': title, 'body': body}
if push_type is 'link':
data['url'] = url
if device:
data['device_iden'] = device
# Check for test mode
if task.options.test:
log.info('Test mode. Pushbullet notification would be:')
log.info(' Type: %s' % push_type)
log.info(' Title: %s' % title)
log.info(' Body: %s' % body)
if push_type is 'link':
log.info(' URL: %s' % url)
# Test mode. Skip remainder.
continue
# Make the request
response = task.requests.post(pushbullet_url, headers=client_headers, data=data, raise_status=False)
# Check if it succeeded
request_status = response.status_code
# error codes and messages from Pushbullet API
if request_status == 200:
log.debug('Pushbullet notification sent')
elif request_status == 500:
log.warning('Pushbullet notification failed, Pushbullet API having issues')
#TODO: Implement retrying. API requests 5 seconds between retries.
elif request_status >= 400:
error = json.loads(response.content)['error']
log.error('Pushbullet API error: %s' % error['message'])
else:
log.error('Unknown error when sending Pushbullet notification')
@event('plugin.register')
def register_plugin():
plugin.register(OutputPushbullet, 'pushbullet', api_ver=2)
|
__author__ = 'hayden'
import random
import numpy as np
import pickle
import os
def main():
splits_id = '002'
labels_path = '/media/hayden/Storage/DATASETS/SPORT/TENNIS01/LABELS/RAW/'
split_path = '/media/hayden/Storage/DATASETS/SPORT/TENNIS01/SPLITS/'+splits_id+'/'
video_name = 'AUSO_2014_M_SF_Nadal_Federer'
markedup = [0, 50690]
sequence = [0, 50690]
percent = .9 # training percentage
split(video_name, split_path, labels_path, markedup, sequence, percent)
#######################################################################################################################
def split(video_name, split_path, labels_path, markedup, sequence, percent):
events = ['Nothing','Hit','Serve','Nadal','Federer','Forehand','Backhand']
# save annotations as class labels on framewise basis
with open(labels_path+video_name+'/labels_'+str(markedup[0])+'_'+str(markedup[1]), 'rb') as f:
labels = pickle.load(f)
labels = labels[:,markedup[0]:markedup[1]]
total_sums = np.sum(labels,1)
ratio = np.zeros((3))
for i in range(3):
ratio[i]=(total_sums[i]-min(total_sums[0:3]))/float(total_sums[i])
print ratio
training_indecies = random.sample(range(markedup[0],markedup[1]), int((markedup[1]-markedup[0])*percent))
training_indecies.sort()
# make sure same number of others
training_indecies_balanced = []
for ti in training_indecies:
tf = 0
for i in range(3):
if labels[i,ti] == 1:
tf = 1
if random.random()<((1-ratio[i])):
training_indecies_balanced.append(ti)
break
if tf == 0:
training_indecies_balanced.append(ti)
training_indecies = training_indecies_balanced
testing_indecies = range(markedup[0],markedup[1])
for sample in training_indecies:
testing_indecies.remove(sample)
#
testing_indecies_balanced = []
for ti in testing_indecies:
tf = 0
for i in range(3):
if labels[i,ti] == 1:
tf = 1
if random.random()<(1-ratio[i]):
testing_indecies_balanced.append(ti)
break
if tf == 0:
testing_indecies_balanced.append(ti)
testing_indecies = testing_indecies_balanced
if not os.path.exists(split_path+video_name+'/'):
os.makedirs(split_path+video_name+'/')
training_file = open(split_path+video_name+'/training_'+str(markedup[0])+'_'+str(markedup[1])+'.txt', "w")
for i in training_indecies:
training_file.write(str(i)+'\n')
testing_file = open(split_path+video_name+'/testing_'+str(markedup[0])+'_'+str(markedup[1])+'.txt', "w")
for i in testing_indecies:
testing_file.write(str(i)+'\n')
stats_file = open(split_path+video_name+'/stats_'+str(markedup[0])+'_'+str(markedup[1])+'.txt', "w")
stats_file.write('Total counts:'+'\n')
total_sums = np.sum(labels,1)
for i in range(len(events)):
stats_file.write(events[i] + ': ' + str(total_sums[i])+'\n')
stats_file.write('\n')
stats_file.write('Training counts:'+'\n')
sums = np.sum(labels[:,training_indecies],1)
for i in range(len(events)):
stats_file.write('%s: %d (%.2f%%)\n' % (events[i],sums[i],sums[i]/float(total_sums[i])))
stats_file.write('\n')
stats_file.write('Testing counts:'+'\n')
sums = np.sum(labels[:,testing_indecies],1)
for i in range(len(events)):
stats_file.write('%s: %d (%.2f%%)\n' % (events[i],sums[i],sums[i]/float(total_sums[i])))
stats_file.close()
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# Author: Zion Orent <[email protected]>
# Copyright (c) 2015 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_rfr359f as upmRfr359f
def main():
# Instantiate an RFR359F digital pin D2
# This was tested on the Grove IR Distance Interrupter
myDistInterrupter = upmRfr359f.RFR359F(2)
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit, including functions from myDistInterrupter
def exitHandler():
print("Exiting")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
if (myDistInterrupter.objectDetected()):
print("Object detected")
else:
print("Area is clear")
time.sleep(.1)
if __name__ == '__main__':
main()
|
using System;
using Server.Items;
using Server.Mobiles;
namespace Server.Engines.Quests
{
public class MougGuurMustDieQuest : BaseQuest
{
public MougGuurMustDieQuest()
{
AddObjective(new SlayObjective(typeof (MougGuur), "moug-guur", 1, "Sanctuary"));
AddReward(new BaseReward(typeof (TreasureBag), 1072583));
}
public override QuestChain ChainID
{
get { return QuestChain.MiniBoss; }
}
public override Type NextQuest
{
get { return typeof (LeaderOfThePackQuest); }
}
/* Moug-Guur Must Die */
public override object Title
{
get { return 1072368; }
}
/* You there! Yes, you. Kill Moug-Guur, the leader of the orcs in this depressing place, and I'll make
it worth your while. */
public override object Description
{
get { return 1072561; }
}
/* Fine. It's no skin off my teeth. */
public override object Refuse
{
get { return 1072571; }
}
/* Small words. Kill Moug-Guur. Go. Now! */
public override object Uncomplete
{
get { return 1072572; }
}
/* You're better than I thought you'd be. Not particularly bad, but not entirely inept. */
public override object Complete
{
get { return 1072573; }
}
public override bool CanOffer()
{
return MondainsLegacy.Sanctuary;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
}
public class LeaderOfThePackQuest : BaseQuest
{
public LeaderOfThePackQuest()
{
AddObjective(new SlayObjective(typeof (Chiikkaha), "chiikkaha", 1, "Sanctuary"));
AddReward(new BaseReward(typeof (TreasureBag), 1072583));
}
public override QuestChain ChainID
{
get { return QuestChain.MiniBoss; }
}
public override Type NextQuest
{
get { return typeof (SayonaraSzavetraQuest); }
}
/* Leader of the Pack */
public override object Title
{
get { return 1072560; }
}
/* Well now that Moug-Guur is no more -- and I can't say I'm weeping for his demise -- it's time for the
ratmen to experience a similar loss of leadership. Slay Chiikkaha. In return, I'll satisfy your greed
temporarily. */
public override object Description
{
get { return 1072574; }
}
/* Alright, if you'd rather not, then run along and do whatever worthless things you do when I'm not
giving you direction. */
public override object Refuse
{
get { return 1072575; }
}
/* How difficult is this? The rats live in the tunnels. Go into the tunnels and find the biggest, meanest
rat and execute him. Loitering around here won't get the task done. */
public override object Uncomplete
{
get { return 1072576; }
}
/* It's about time! Could you have taken longer? */
public override object Complete
{
get { return 1072577; }
}
public override bool CanOffer()
{
return MondainsLegacy.Sanctuary;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
}
public class SayonaraSzavetraQuest : BaseQuest
{
public SayonaraSzavetraQuest()
{
AddObjective(new SlayObjective(typeof (Szavetra), "szavetra", 1, "Sanctuary"));
AddReward(new BaseReward(typeof (RewardBox), 1072584));
}
public override QuestChain ChainID
{
get { return QuestChain.MiniBoss; }
}
/* Sayonara, Szavetra */
public override object Title
{
get { return 1072375; }
}
/* Hmm, maybe you aren't entirely worthless. I suspect a demoness of Szavetra's calibre will tear you
apart ... We might as well find out. Kill the succubus, yada yada, and you'll be richly rewarded. */
public override object Description
{
get { return 1072578; }
}
/* Hah! I knew you couldn't handle it. */
public override object Refuse
{
get { return 1072579; }
}
/* Hahahaha! I can see the fear in your eyes. Pathetic. Szavetra is waiting for you. */
public override object Uncomplete
{
get { return 1072581; }
}
/* Amazing! Simply astonishing ... you survived. Well, I supposed I should indulge your avarice
with a reward.*/
public override object Complete
{
get { return 1072582; }
}
public override bool CanOffer()
{
return MondainsLegacy.Sanctuary;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
}
}
}
|
# encoding: utf-8
from django.test import TestCase
from django_nose.tools import *
from wpkit.wp import content
from .. import Differ
BALANCE_TESTS = (
(
'<p> <p>Test 0</p>',
False,
'<p> </p><p>Test 0</p>'
),
(
'<p>Test 1 <i>abc <b>nested tags</b> and </p>\n<p>Unbalanced <a>tags</a>',
False,
'<p>Test 1 <i>abc <b>nested tags</b> and </i></p>\n<p>Unbalanced <a>tags</a></p>'
),
(
'<p>Test 2 <i>abc <b>nested </i>tags</b> and </p>\n<p>Unbalanced <a>tags</a>',
False,
'<p>Test 2 <i>abc <b>nested </b></i>tags and </p>\n<p>Unbalanced <a>tags</a></p>'
),
(
'<p>Test 2 <i>abc <b>nested </i>tags <br /></b> and </p>\n<p>Unbalanced <a>tags</a>',
False,
'<p>Test 2 <i>abc <b>nested </b></i>tags <br /> and </p>\n<p>Unbalanced <a>tags</a></p>'
),
(
'<p>Test 2 <i>abc <b>nested </i>tags <br></b> and </p>\n<p>Unbalanced <a>tags</a>',
False,
'<p>Test 2 <i>abc <b>nested </b></i>tags <br/> and </p>\n<p>Unbalanced <a>tags</a></p>'
),
(
'''<p>Test 1-2 <i>abc's <b>"nested tags"</b> -- and </p>\n<p>Unbalanced <a>tags</a>''',
True,
u'<p>Test 1-2 <i>abc’s <b>“nested tags”</b> — and </i></p>\n<p>Unbalanced <a>tags</a></p>'
),
(
'''<p>Test 1-2 <i>abc's <b>"nested tags"</b> -- and </p>\n<pre>Unbalanced <a>tags'</a>''',
True,
u'<p>Test 1-2 <i>abc’s <b>“nested tags”</b> — and </i></p>\n<pre>Unbalanced <a>tags\'</a></pre>'
),
(
u'''<img class="post" src="/wp-content/blogs.dir/1/eurostar.jpg" align="left" width="240" height="180" />Vi sarà capitato di salire su un Eurostar la mattina ancora insonnoliti, o a fine pomeriggio stanchi dopo una giornata di lavoro in trasferta, e conquistato l'agognato posto vicino al finestrino rannicchiarvi e cascare in un sonno profondo. E vi sarà anche capitato di svegliarvi di soprassalto per un rumore sferragliante qualche centimetro accanto alle vostre orecchie.''',
True,
u'''<img class="post" src="/wp-content/blogs.dir/1/eurostar.jpg" align="left" width="240" height="180" />Vi sarà capitato di salire su un Eurostar la mattina ancora insonnoliti, o a fine pomeriggio stanchi dopo una giornata di lavoro in trasferta, e conquistato l’agognato posto vicino al finestrino rannicchiarvi e cascare in un sonno profondo. E vi sarà anche capitato di svegliarvi di soprassalto per un rumore sferragliante qualche centimetro accanto alle vostre orecchie.'''
)
# ...
)
TXTR_BLOCK_TESTS = (
(
'''WP's a "great" app, PHP rocks, and code is poetry...''',
u'WP’s a “great” app, PHP rocks, and code is poetry…'
),
(
u'''Vi sarà capitato di salire su un Eurostar la mattina ancora insonnoliti, o a fine pomeriggio stanchi dopo una giornata di lavoro in trasferta, e conquistato l'agognato posto vicino al finestrino rannicchiarvi e cascare in un sonno profondo. E vi sarà anche capitato di svegliarvi di soprassalto per un rumore sferragliante qualche centimetro accanto alle vostre orecchie.''',
u'''Vi sarà capitato di salire su un Eurostar la mattina ancora insonnoliti, o a fine pomeriggio stanchi dopo una giornata di lavoro in trasferta, e conquistato l’agognato posto vicino al finestrino rannicchiarvi e cascare in un sonno profondo. E vi sarà anche capitato di svegliarvi di soprassalto per un rumore sferragliante qualche centimetro accanto alle vostre orecchie.'''
),
(
'This comment <!--abc--> should not be converted, nor should this one <!-- ab c -->',
'This comment <!--abc--> should not be converted, nor should this one <!-- ab c -->'
),
)
AUTOP_TESTS = (
(
'''Test 1.\nSecond line\n\n<br />Third line.''',
'''<p>Test 1.<br />\nSecond line</p>\n<p>Third line.</p>\n'''
),
(
'''Test 2.\n\n<pre>Second line</pre>\n\nThird line.''',
'''<p>Test 2.</p>\n<pre>Second line</pre>\n<p>Third line.</p>\n'''
),
)
class TestContent(TestCase):
def test_balance_tags(self):
for test, texturize, expected in BALANCE_TESTS:
result = content.balance_tags(test, texturize)
if result != expected:
raise ValueError(Differ(expected=expected, result=result))
def test_texturize_block(self):
for test, expected in TXTR_BLOCK_TESTS:
result = content.texturize_block(test)
if result != expected:
raise ValueError(Differ(expected=expected, result=result))
def test_autop(self):
for test, expected in AUTOP_TESTS:
result = content.autop(test)
if result != expected:
raise ValueError(Differ(expected=expected, result=result))
|
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sanatana.MongoDb;
using MongoDB.Driver;
using Sanatana.Notifications.Composing;
using Sanatana.Notifications.DAL.Entities;
using Sanatana.Notifications.DAL.Interfaces;
using Sanatana.Notifications.DAL.Results;
namespace Sanatana.Notifications.DAL.MongoDb
{
public class MongoDbEventSettingsQueries : IEventSettingsQueries<ObjectId>
{
//fields
protected MongoDbConnectionSettings _settings;
protected SenderMongoDbContext _context;
//init
public MongoDbEventSettingsQueries(MongoDbConnectionSettings connectionSettings)
{
_settings = connectionSettings;
_context = new SenderMongoDbContext(connectionSettings);
}
//methods
public virtual async Task Insert(List<EventSettings<ObjectId>> items)
{
foreach (EventSettings<ObjectId> item in items)
{
item.EventSettingsId = ObjectId.GenerateNewId();
}
var options = new InsertManyOptions()
{
IsOrdered = false
};
await _context.EventSettings.InsertManyAsync(items, options).ConfigureAwait(false);
}
public virtual async Task<TotalResult<List<EventSettings<ObjectId>>>> Select(int page, int pageSize)
{
int skip = MongoDbUtility.ToSkipNumber(page, pageSize);
var filter = Builders<EventSettings<ObjectId>>.Filter.Where(p => true);
Task<List<EventSettings<ObjectId>>> listTask = _context.EventSettings
.Find(filter)
.Skip(skip)
.Limit(pageSize)
.ToListAsync();
Task<long> countTask = _context.EventSettings.CountAsync(filter);
long count = await countTask.ConfigureAwait(false);
List<EventSettings<ObjectId>> list = await listTask.ConfigureAwait(false);
return new TotalResult<List<EventSettings<ObjectId>>>(list, count);
}
public virtual async Task<EventSettings<ObjectId>> Select(ObjectId eventSettingsId)
{
var filter = Builders<EventSettings<ObjectId>>.Filter.Where(
p => p.EventSettingsId == eventSettingsId);
EventSettings<ObjectId> item = await _context.EventSettings.Find(filter)
.FirstOrDefaultAsync().ConfigureAwait(false);
return item;
}
public virtual async Task<List<EventSettings<ObjectId>>> Select(int category)
{
var filter = Builders<EventSettings<ObjectId>>.Filter.Where(
p => p.CategoryId == category);
List<EventSettings<ObjectId>> list = await _context.EventSettings.Find(filter)
.ToListAsync().ConfigureAwait(false);
return list;
}
public virtual async Task Update(List<EventSettings<ObjectId>> items)
{
var requests = new List<WriteModel<EventSettings<ObjectId>>>();
foreach (EventSettings<ObjectId> item in items)
{
var filter = Builders<EventSettings<ObjectId>>.Filter.Where(
p => p.EventSettingsId == item.EventSettingsId);
var update = Builders<EventSettings<ObjectId>>.Update
.Set(p => p.Subscription, item.Subscription)
.Set(p => p.Updates, item.Updates)
.Set(p => p.Templates, item.Templates);
requests.Add(new UpdateOneModel<EventSettings<ObjectId>>(filter, update)
{
IsUpsert = false
});
}
var options = new BulkWriteOptions
{
IsOrdered = false
};
BulkWriteResult response = await _context.EventSettings
.BulkWriteAsync(requests, options).ConfigureAwait(false);
}
public virtual async Task Delete(List<EventSettings<ObjectId>> items)
{
List<ObjectId> Ids = items.Select(p => p.EventSettingsId).ToList();
var filter = Builders<EventSettings<ObjectId>>.Filter.Where(
p => Ids.Contains(p.EventSettingsId));
DeleteResult response = await _context.EventSettings.DeleteManyAsync(filter)
.ConfigureAwait(false);
}
}
}
|
# -*- coding: utf-8 -*-
import sys
from setuptools import setup
from setuptools.command.test import test
class Tox(test):
def initialize_options(self):
test.initialize_options(self)
self.tox_args = None
def finalize_options(self):
test.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
sys.exit(tox.cmdline())
if __name__ == '__main__':
setup(
name='match.py',
version='0.1',
description='Match is a library that works on a small subset of regular expressions for fast url matching.',
url='https://github.com/hackaugusto/match.py',
author='Augusto F. Hack',
author_email='[email protected]',
license='MIT',
py_modules=['timer'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
keywords=['timer'],
tests_require=['tox'],
cmdclass={'test': Tox},
)
|
import { parseXY } from 'xy-parser';
import { Chromatogram } from '../Chromatogram';
export function fromText(text, options = {}) {
const data = parseXY(text, options);
const time = data.x;
let series = {
intensity: data.y,
};
return new Chromatogram(time, series);
}
|
var _klingon___b_c_8cpp =
[
[ "g_pKlingonBCBitmap", "_klingon___b_c_8cpp.html#a2305dfd9cafced7768986381f87e7a43", null ]
];
|
#
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering 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.
#######################################################################################
# ___INFO__MARK_END__
#
from uge.exceptions.authorization_error import AuthorizationError
from uge.exceptions.command_failed import CommandFailed
from uge.exceptions.configuration_error import ConfigurationError
from uge.exceptions.invalid_argument import InvalidArgument
from uge.exceptions.invalid_request import InvalidRequest
from uge.exceptions.object_already_exists import ObjectAlreadyExists
from uge.exceptions.object_not_found import ObjectNotFound
from uge.exceptions.qconf_exception import QconfException
from uge.exceptions.qmaster_unreachable import QmasterUnreachable
from uge.exceptions.ar_exception import AdvanceReservationException
|
namespace HomeMadeFood.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class IgnoreChanges : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
|
#ifndef NT2_CORE_INCLUDE_FUNCTIONS_GREATESTNONINTEGER_HPP_INCLUDED
#define NT2_CORE_INCLUDE_FUNCTIONS_GREATESTNONINTEGER_HPP_INCLUDED
#include <nt2/core/functions/greatestnoninteger.hpp>
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.query.aggregate.timeseries;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class TimeSeriesPostFlatAggregateSort {
// private static final Logger logger =
// LoggerFactory.getLogger(PostFlatAggregateSort.class);
private static SortedSet<Map.Entry<List<String>, List<Double>>> sortByValue(
Map<List<String>, List<Double>> mapForSort,
List<SortOption> sortOptions) {
SortedSet<Map.Entry<List<String>, List<Double>>> sortedEntries = new TreeSet<Map.Entry<List<String>, List<Double>>>(
new MapEntryComparator(sortOptions));
sortedEntries.addAll(mapForSort.entrySet());
return sortedEntries;
}
/**
* sort aggregated results with sort options
*
* @param entity
*/
public static List<Map.Entry<List<String>, List<double[]>>> sort(
Map<List<String>, List<Double>> mapForSort,
Map<List<String>, List<double[]>> valueMap,
List<SortOption> sortOptions, int topN) {
processIndex(sortOptions);
List<Map.Entry<List<String>, List<double[]>>> result = new ArrayList<Map.Entry<List<String>, List<double[]>>>();
SortedSet<Map.Entry<List<String>, List<Double>>> sortedSet = sortByValue(
mapForSort, sortOptions);
for (Map.Entry<List<String>, List<Double>> entry : sortedSet) {
List<String> key = entry.getKey();
List<double[]> value = valueMap.get(key);
if (value != null) {
Map.Entry<List<String>, List<double[]>> newEntry = new ImmutableEntry<List<String>, List<double[]>>(key, value);
result.add(newEntry);
if (topN > 0 && result.size() >= topN) {
break;
}
}
}
return result;
}
private static void processIndex(List<SortOption> sortOptions) {
for (int i = 0; i < sortOptions.size(); ++i) {
SortOption so = sortOptions.get(i);
so.setIndex(i);
}
}
private static class MapEntryComparator implements
Comparator<Map.Entry<List<String>, List<Double>>> {
private List<SortOption> sortOptions;
public MapEntryComparator(List<SortOption> sortOptions) {
this.sortOptions = sortOptions;
}
/**
* default to sort by all groupby fields
*/
@Override
public int compare(Map.Entry<List<String>, List<Double>> e1,
Map.Entry<List<String>, List<Double>> e2) {
int r = 0;
List<String> keyList1 = e1.getKey();
List<Double> valueList1 = e1.getValue();
List<String> keyList2 = e2.getKey();
List<Double> valueList2 = e2.getValue();
for (SortOption so : sortOptions) {
int index = so.getIndex();
if (index == -1) {
continue;
}
if (!so.isInGroupby()) { // sort fields come from functions
Double value1 = valueList1.get(index);
Double value2 = valueList2.get(index);
r = value1.compareTo(value2);
} else { // sort fields come from groupby fields
String key1 = keyList1.get(index);
String key2 = keyList2.get(index);
r = key1.compareTo(key2);
}
if (r == 0)
continue;
if (!so.isAscendant()) {
r = -r;
}
return r;
}
// default to sort by groupby fields ascendently
if (r == 0) { // TODO is this check necessary
return new GroupbyFieldsComparator()
.compare(keyList1, keyList2);
}
return r;
}
}
static class ImmutableEntry<K, V> implements Map.Entry<K, V>, Serializable {
private final K key;
private final V value;
ImmutableEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
}
|
<?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Databases;
use Oro\Bundle\EntityExtendBundle\Databases\PostgresDatabase;
class PostgresDatabaseTest extends \PHPUnit_Framework_TestCase
{
/** @var PostgresDatabase */
protected $classInstance;
protected $db = 'test_db';
protected $user = 'test_user';
protected $tables = array('test_table_1', 'test_table_2');
protected $pass = 'test_password';
protected $file = 'dump.dump';
protected $dump;
protected $restore;
protected function setUp()
{
$this->classInstance = new PostgresDatabase($this->db, $this->user, $this->pass, $this->tables);
$this->dump = 'PGPASSWORD="test_password" pg_dump -Fc --no-acl --no-owner -h "localhost" '.
'-U "test_user" "test_db" -t "test_table_1" "test_table_2" > "dump.dump"';
$this->restore = 'PGPASSWORD="test_password" pg_restore --clean --no-acl --no-owner -h "localhost" '.
'-U "test_user" -d "test_db" "dump.dump"';
}
public function testDump()
{
$this->assertEquals($this->dump, $this->classInstance->dump($this->file));
}
public function testRestore()
{
$this->assertEquals($this->restore, $this->classInstance->restore($this->file));
}
public function testGetFileExtension()
{
$this->assertEquals('dump', $this->classInstance->getFileExtension());
}
}
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from transifex.txcommon.tests import base, utils
from transifex.projects.models import Project
class ProjectViewsTests(base.BaseTestCase, base.NoticeTypes):
# Note: The Project lookup field is tested elsewhere.
def setUp(self, *args, **kwargs):
super(ProjectViewsTests, self).setUp(*args, **kwargs)
self.url_acc = reverse('project_access_control_edit', args=[self.project.slug])
# Outsource tests
def test_project_outsource_good(self):
"""Test that a private project is visible to its maintainer."""
resp = self.client['maintainer'].get(self.url_acc, {})
self.assertContains(resp, "Test Project", status_code=200)
self.assertContains(resp, "Test Private Project", status_code=200)
def test_project_outsource_bad(self):
# Private project is not visible to another maintainer
self.assertTrue(self.user['registered'] not in self.project_private.maintainers.all())
self.project.maintainers.add(self.user['registered'])
self.assertTrue(self.user['registered'] in self.project.maintainers.all())
resp = self.client['registered'].get(self.url_acc, {})
self.assertContains(resp, "Test Project", status_code=200)
self.assertNotContains(resp, "Test Private Project", status_code=200)
# Private project cannot be used by another maintainer to outsource
resp = self.client['registered'].post(self.url_acc, {
'outsource': self.project_private.id,
'submit_access_control': 'Save Access Control Settings',
'access_control': 'outsourced_access',
'next': '/projects/p/desktop-effects/edit/access/', })
self.assertFalse(self.project.outsource)
self.assertTemplateUsed(resp, "projects/project_form_access_control.html")
self.assertContains(resp, "Select a valid choice.")
def test_trans_instructions(self):
"""Test the project.trans_instructions model field & templates."""
self.project.trans_instructions = "http://help.transifex.net/"\
"technical/contributing.html#updating-translation-files-po-files"
self.project.save()
resp = self.client['anonymous'].get(self.urls['project'])
self.assertContains(resp, "contributing.html")
self.assertContains(resp, "Translation help pages")
def test_delete_project(self):
url = reverse('project_delete', args=[self.project.slug])
resp = self.client['maintainer'].get(url)
self.assertContains(resp, "Delete project")
user = self.user['maintainer']
resp = self.client['maintainer'].post(url, {'password': base.PASSWORD}, follow=True)
self.assertContains(resp, "was deleted.")
self.assertTrue(Project.objects.filter(slug=self.project.slug).count() == 0)
# Test messages:
self.assertContains(resp, "message_success")
def test_project_edit(self):
resp = self.client['maintainer'].get(self.urls['project_edit'])
self.assertContains(resp, "Edit Test Project", status_code=200)
self.assertContains(resp, self.project.maintainers.all()[0])
self.assertNotContains(resp, "Owner")
#save edited project
DATA = {'project-bug_tracker':'',
'project-description':'Test Project',
'project-feed':'',
'project-homepage':'',
'project-long_description':'',
'project-maintainers':'|%s|'%self.user['maintainer'].id,
'project-maintainers_text':'',
'project-name':'Test Project',
'project-slug':'project1',
'project-tags':'',
'project-trans_instructions':''}
resp = self.client['maintainer'].post(self.urls['project_edit'], DATA, follow=True)
self.assertEqual(resp.status_code, 200)
|
import os
import responses
import unittest
from geojson_elevation.backends.google import elevation
from geojson_elevation.exceptions import ElevationApiError
class TestGoogleBackend(unittest.TestCase):
def load_fixture(self, file):
return open(os.path.abspath(file)).read()
""" Google Elevation API tests """
@responses.activate
def test_1_point(self):
responses.add(
responses.GET,
"https://maps.googleapis.com/maps/api/elevation/json?locations=41.889040454306752%2C12.525333445447737",
body=self.load_fixture("tests/static/test_1_point.json"),
match_querystring=True,
content_type='application/json',
)
result = elevation('41.889040454306752,12.525333445447737')
self.assertIn('Point', result['geometry']['type'])
self.assertEqual(len(result['geometry']['coordinates']), 1)
self.assertEqual(len(result['geometry']['coordinates'][0]), 3)
@responses.activate
def test_2_points(self):
responses.add(
responses.GET,
"https://maps.googleapis.com/maps/api/elevation/json?path=41.889040454306752%2C12.525333445447737%7C41.889050454306752%2C12.525335445447737&samples=2",
body=self.load_fixture("tests/static/test_2_points.json"),
match_querystring=True,
content_type='application/json',
)
result = elevation('41.889040454306752,12.525333445447737|41.889050454306752,12.525335445447737')
self.assertIn('LineString', result['geometry']['type'])
self.assertEqual(len(result['geometry']['coordinates']), 2)
self.assertEqual(len(result['geometry']['coordinates'][0]), 3)
self.assertEqual(len(result['geometry']['coordinates'][1]), 3)
@responses.activate
def test_maximum_sampling(self):
responses.add(
responses.GET,
"https://maps.googleapis.com/maps/api/elevation/json?path=41.889040454306752%2C12.525333445447737%7C41.872041927699982%2C12.582239191900001&samples=512",
body=self.load_fixture("tests/static/test_maximum_sampling.json"),
match_querystring=True,
content_type='application/json',
)
result = elevation('41.889040454306752,12.525333445447737|41.872041927699982,12.582239191900001', sampling=4)
self.assertIn('LineString', result['geometry']['type'])
self.assertEqual(len(result['geometry']['coordinates']), 512)
self.assertEqual(len(result['geometry']['coordinates'][0]), 3)
self.assertEqual(len(result['geometry']['coordinates'][-1]), 3)
@responses.activate
def test_automatic_sampling(self):
responses.add(
responses.GET,
"https://maps.googleapis.com/maps/api/elevation/json?path=41.8890404543067518%2C12.5253334454477372%7C41.8972185849048984%2C12.4902286938660296&samples=72",
body=self.load_fixture("tests/static/test_automatic_sampling.json"),
match_querystring=True,
content_type='application/json',
)
result = elevation('41.8890404543067518,12.5253334454477372|41.8972185849048984,12.4902286938660296')
self.assertIn('LineString', result['geometry']['type'])
self.assertEqual(len(result['geometry']['coordinates']), 72)
self.assertEqual(len(result['geometry']['coordinates'][0]), 3)
self.assertEqual(len(result['geometry']['coordinates'][-1]), 3)
def test_elevation_api_exception(self):
with self.assertRaises(ElevationApiError):
elevation('43432430,2321321320')
|
# 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.
# pylint: disable=invalid-name, unused-argument
"""Faster R-CNN and Mask R-CNN operations."""
import topi
from topi.util import get_const_tuple, get_float_tuple, get_const_int
from .. import op as reg
from ..op import OpPattern
@reg.register_compute("vision.roi_align")
def compute_roi_align(attrs, inputs, _, target):
"""Compute definition of roi_align"""
assert attrs.layout == "NCHW"
return [topi.vision.rcnn.roi_align_nchw(
inputs[0], inputs[1], pooled_size=get_const_tuple(attrs.pooled_size),
spatial_scale=attrs.spatial_scale, sample_ratio=attrs.sample_ratio)]
@reg.register_schedule("vision.roi_align")
def schedule_roi_align(_, outs, target):
"""Schedule definition of roi_align"""
with target:
return topi.generic.vision.schedule_roi_align(outs)
reg.register_pattern("vision.roi_align", OpPattern.OUT_ELEMWISE_FUSABLE)
@reg.register_compute("vision.roi_pool")
def compute_roi_pool(attrs, inputs, _, target):
"""Compute definition of roi_pool"""
assert attrs.layout == "NCHW"
return [topi.vision.rcnn.roi_pool_nchw(
inputs[0], inputs[1], pooled_size=get_const_tuple(attrs.pooled_size),
spatial_scale=attrs.spatial_scale)]
@reg.register_schedule("vision.roi_pool")
def schedule_roi_pool(_, outs, target):
"""Schedule definition of roi_pool"""
with target:
return topi.generic.vision.schedule_roi_pool(outs)
reg.register_pattern("vision.roi_pool", OpPattern.OUT_ELEMWISE_FUSABLE)
@reg.register_compute("vision.proposal")
def compute_proposal(attrs, inputs, _, target):
"""Compute definition of proposal"""
scales = get_float_tuple(attrs.scales)
ratios = get_float_tuple(attrs.ratios)
feature_stride = attrs.feature_stride
threshold = attrs.threshold
rpn_pre_nms_top_n = attrs.rpn_pre_nms_top_n
rpn_post_nms_top_n = attrs.rpn_post_nms_top_n
rpn_min_size = attrs.rpn_min_size
iou_loss = bool(get_const_int(attrs.iou_loss))
with target:
return [
topi.vision.rcnn.proposal(inputs[0], inputs[1], inputs[2], scales, ratios,
feature_stride, threshold, rpn_pre_nms_top_n,
rpn_post_nms_top_n, rpn_min_size, iou_loss)
]
@reg.register_schedule("vision.proposal")
def schedule_proposal(_, outs, target):
"""Schedule definition of proposal"""
with target:
return topi.generic.schedule_proposal(outs)
reg.register_pattern("vision.proposal", OpPattern.OPAQUE)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "United States - Chart of accounts",
"version": "1.1",
"author": "OpenERP SA",
"category": 'Localization/Account Charts',
"description": """
United States - Chart of accounts
""",
'website': 'http://www.openerp.com',
'init_xml': [],
"depends": [
"account_chart",
],
'update_xml': [
"l10n_us_account_type.xml",
'account_chart_template.xml',
'account.account.template.csv',
'account_tax_code_template.xml',
'account_tax_template.xml',
'account_chart_template_after.xml',
'l10n_us_wizard.xml'
],
'demo_xml': [
],
'test': [
],
'installable': True,
'auto_install': False,
'certificate': '0092156316669',
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
#!/usr/bin/python3
# coding: utf-8
# All files under MIT license
# Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
# See 'LICENSE' file.
# For 'Repl.it'.
import os,sys
try:
input = raw_input
except NameError:
pass
loop = True
DEMOS = (
"Blank",
"Hello",
"Chatroom",
"Notes",
"TodoMVC",
"Hangman",
"15-puzzle",
"Contacts",
"Widgets",
"Chatrooms",
"Reversi",
"MatPlotLib"
)
DEMOS_AMOUNT = len(DEMOS)
def normalize(item):
if ( isinstance(item,str) ):
return item, 0
else:
return item
while loop:
for id in range(0,DEMOS_AMOUNT):
label, amount = normalize(DEMOS[id])
letter = chr(id + ord('a'))
if amount:
print(letter, 0, ", ", letter, 1, ", …, ", letter, amount, ": ", label, " (tutorial)", sep='')
else:
print(letter, ": ", label, sep='')
entry = input("Select one of above demo: ").lower()
try:
id = int(ord(entry[:1]) - ord('a'))
label, amount = normalize(DEMOS[id])
affix = "tutorials" if amount else "examples"
if ( amount ):
number = int(entry[1:])
if ( ( number < 0 ) or ( number > amount ) ):
raise
# Needed by Repl.it
suffix = "part" + entry[1:] if amount else 'main'
sample = affix + "." + label + "." + suffix
sys.argv[0]=affix + '/' + label + "/"
if True: # Simplifies debugging when set to False
try:
__import__(sample)
except ImportError:
print("\tERROR: could not launch '" + sys.argv[0] + suffix + ".py'!")
loop = False
except:
loop = False
else:
__import__(sample)
except:
print("'" + entry + "' is not a valid sample id. Please retry.\n")
|
package edu.hm.gamedev.server.packets.server2client;
import edu.hm.gamedev.server.packets.Packet;
import edu.hm.gamedev.server.packets.Type;
public abstract class SomethingFailedPacket<T extends Enum<T>> extends Packet {
private final T reason;
private final String message;
protected SomethingFailedPacket(Type type, T reason, String message) {
super(type);
this.reason = reason;
this.message = message;
}
public T getReason() {
return reason;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "SomethingFailedPacket{" +
"reason=" + reason +
", message='" + message + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
SomethingFailedPacket that = (SomethingFailedPacket) o;
if (message != null ? !message.equals(that.message) : that.message != null) {
return false;
}
if (reason != null ? !reason.equals(that.reason) : that.reason != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (reason != null ? reason.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
return result;
}
}
|
# Copyright (c) 2015 OpenStack Foundation.
# 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.
import codecs
import os
import os.path
import fixtures
from oslo_config import fixture as config
from oslotest import base as test_base
from oslo_policy import _checks
from oslo_policy import policy
class PolicyBaseTestCase(test_base.BaseTestCase):
def setUp(self):
super(PolicyBaseTestCase, self).setUp()
self.conf = self.useFixture(config.Config()).conf
self.config_dir = self.useFixture(fixtures.TempDir()).path
self.conf(args=['--config-dir', self.config_dir])
self.enforcer = policy.Enforcer(self.conf)
self.addCleanup(self.enforcer.clear)
def get_config_file_fullname(self, filename):
return os.path.join(self.config_dir, filename.lstrip(os.sep))
def create_config_file(self, filename, contents):
"""Create a configuration file under the config dir.
Also creates any intermediate paths needed so the file can be
in a subdirectory.
"""
path = self.get_config_file_fullname(filename)
pardir = os.path.dirname(path)
if not os.path.exists(pardir):
os.makedirs(pardir)
with codecs.open(path, 'w', encoding='utf-8') as f:
f.write(contents)
class FakeCheck(_checks.BaseCheck):
def __init__(self, result=None):
self.result = result
def __str__(self):
return str(self.result)
def __call__(self, target, creds, enforcer):
if self.result is not None:
return self.result
return (target, creds, enforcer)
|
# Copyright 2011 OpenStack Foundation
# 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.
from trove.openstack.common import log as logging
import os
from migrate.versioning import api as versioning_api
# See LP bug #719834. sqlalchemy-migrate changed location of
# exceptions.py after 0.6.0.
try:
from migrate.versioning import exceptions as versioning_exceptions
except ImportError:
from migrate import exceptions as versioning_exceptions
from trove.common import exception
logger = logging.getLogger('trove.db.sqlalchemy.migration')
def db_version(options, repo_path=None):
"""Return the database's current migration number.
:param options: options dict
:retval version number
"""
repo_path = get_migrate_repo_path(repo_path)
sql_connection = options['sql_connection']
try:
return versioning_api.db_version(sql_connection, repo_path)
except versioning_exceptions.DatabaseNotControlledError:
msg = ("database '%(sql_connection)s' is not under migration control"
% {'sql_connection': sql_connection})
raise exception.DatabaseMigrationError(msg)
def upgrade(options, version=None, repo_path=None):
"""Upgrade the database's current migration level.
:param options: options dict
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(options, repo_path) # Ensure db is under migration control
repo_path = get_migrate_repo_path(repo_path)
sql_connection = options['sql_connection']
version_str = version or 'latest'
logger.info("Upgrading %(sql_connection)s to version %(version_str)s" %
{'sql_connection': sql_connection, 'version_str': version_str})
return versioning_api.upgrade(sql_connection, repo_path, version)
def downgrade(options, version, repo_path=None):
"""Downgrade the database's current migration level.
:param options: options dict
:param version: version to downgrade to
:retval version number
"""
db_version(options, repo_path) # Ensure db is under migration control
repo_path = get_migrate_repo_path(repo_path)
sql_connection = options['sql_connection']
logger.info("Downgrading %(sql_connection)s to version %(version)s" %
{'sql_connection': sql_connection, 'version': version})
return versioning_api.downgrade(sql_connection, repo_path, version)
def version_control(options, repo_path=None):
"""Place a database under migration control.
:param options: options dict
"""
sql_connection = options['sql_connection']
try:
_version_control(options)
except versioning_exceptions.DatabaseAlreadyControlledError:
msg = ("database '%(sql_connection)s' is already under migration "
"control" % {'sql_connection': sql_connection})
raise exception.DatabaseMigrationError(msg)
def _version_control(options, repo_path):
"""Place a database under migration control.
:param options: options dict
"""
repo_path = get_migrate_repo_path(repo_path)
sql_connection = options['sql_connection']
return versioning_api.version_control(sql_connection, repo_path)
def db_sync(options, version=None, repo_path=None):
"""Place a database under migration control and perform an upgrade.
:param options: options dict
:param repo_path: used for plugin db migrations, defaults to main repo
:retval version number
"""
try:
_version_control(options, repo_path)
except versioning_exceptions.DatabaseAlreadyControlledError:
pass
upgrade(options, version=version, repo_path=repo_path)
def get_migrate_repo_path(repo_path=None):
"""Get the path for the migrate repository."""
default_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
repo_path = repo_path or default_path
assert os.path.exists(repo_path)
return repo_path
|
# 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.
import pyarrow.benchmark as pb
from . import common
class PandasObjectIsNull(object):
size = 10 ** 5
types = ('int', 'float', 'object', 'decimal')
param_names = ['type']
params = [types]
def setup(self, type_name):
gen = common.BuiltinsGenerator()
if type_name == 'int':
lst = gen.generate_int_list(self.size)
elif type_name == 'float':
lst = gen.generate_float_list(self.size, use_nan=True)
elif type_name == 'object':
lst = gen.generate_object_list(self.size)
elif type_name == 'decimal':
lst = gen.generate_decimal_list(self.size)
else:
assert 0
self.lst = lst
def time_PandasObjectIsNull(self, *args):
pb.benchmark_PandasObjectIsNull(self.lst)
|
<?php
class smsruSMS extends waSMSAdapter
{
public function getControls()
{
return array(
'api_id' => array(
'value' => '',
'title' => 'api_id',
'description' => 'Введите значение параметра api_id для вашего аккаунта в сервисе sms.ru',
),
);
}
/**
* @param string $to
* @param string $text
* @return mixed
*/
public function send($to, $text)
{
$ch = curl_init("http://sms.ru/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"api_id" => $this->getOption('api_id'),
"to" => $to,
"text" => $text
));
$result = curl_exec($ch);
curl_close($ch);
$this->log($to, $text, $result);
$result = explode("\n", $result);
if ($result[0] == 100) {
unset($result[0]);
return $result;
} else {
return false;
}
}
}
|
from django.conf import settings
from django.urls import path, register_converter
from mapentity.registry import registry
from geotrek.altimetry.urls import AltimetryEntityOptions
from geotrek.common.urls import PublishableEntityOptions, LangConverter
from mapentity.registry import MapEntityOptions
from . import models
from .views import (
TrekDocumentPublic, TrekDocumentBookletPublic, TrekMapImage, TrekMarkupPublic,
TrekGPXDetail, TrekKMLDetail, WebLinkCreatePopup,
CirkwiTrekView, CirkwiPOIView, TrekPOIViewSet,
TrekServiceViewSet
)
register_converter(LangConverter, 'lang')
app_name = 'trekking'
urlpatterns = [
path('api/<lang:lang>/treks/<int:pk>/pois.geojson', TrekPOIViewSet.as_view({'get': 'list'}), name="trek_poi_geojson"),
path('api/<lang:lang>/treks/<int:pk>/services.geojson', TrekServiceViewSet.as_view({'get': 'list'}), name="trek_service_geojson"),
path('api/<lang:lang>/treks/<int:pk>/<slug:slug>.gpx', TrekGPXDetail.as_view(), name="trek_gpx_detail"),
path('api/<lang:lang>/treks/<int:pk>/<slug:slug>.kml', TrekKMLDetail.as_view(), name="trek_kml_detail"),
path('api/<lang:lang>/treks/<int:pk>/meta.html', TrekKMLDetail.as_view(), name="trek_meta"),
path('popup/add/weblink/', WebLinkCreatePopup.as_view(), name='weblink_add'),
path('api/cirkwi/circuits.xml', CirkwiTrekView.as_view()),
path('api/cirkwi/pois.xml', CirkwiPOIView.as_view()),
path('image/trek-<int:pk>-<lang:lang>.png', TrekMapImage.as_view(), name='trek_map_image'),
]
class TrekEntityOptions(AltimetryEntityOptions, PublishableEntityOptions):
"""
Add more urls using mixins:
- altimetry views (profile, dem etc.)
- public documents views
We override trek public view to add more context variables and
preprocess attributes.
"""
document_public_view = TrekDocumentPublic
document_public_booklet_view = TrekDocumentBookletPublic
markup_public_view = TrekMarkupPublic
class POIEntityOptions(PublishableEntityOptions):
pass
class ServiceEntityOptions(MapEntityOptions):
pass
urlpatterns += registry.register(models.Trek, TrekEntityOptions, menu=settings.TREKKING_MODEL_ENABLED)
urlpatterns += registry.register(models.POI, POIEntityOptions, menu=settings.POI_MODEL_ENABLED)
urlpatterns += registry.register(models.Service, ServiceEntityOptions, menu=settings.SERVICE_MODEL_ENABLED)
|
# -*- coding: utf-8 -*-
import unittest
import pinyin
from pinyin._compat import u
class BasicTestSuite(unittest.TestCase):
"""Basic test cases."""
def test_get(self):
self.assertEqual(pinyin.get('你好'),
pinyin.get('你好', format="diacritical"))
self.assertEqual(pinyin.get(u('你好'), format="strip"), u('nihao'))
self.assertEqual(pinyin.get(u('你好'), format="numerical"), u('ni3hao3'))
self.assertEqual(pinyin.get(u('你好'), format="diacritical"), u('nǐhǎo'))
self.assertEqual(pinyin.get('你好吗?'), u('nǐhǎoma?'))
self.assertEqual(pinyin.get('你好吗?'), u('nǐhǎoma?'))
self.assertEqual(pinyin.get('你好'), u('nǐhǎo'))
self.assertEqual(pinyin.get('叶'), u('yè'))
self.assertEqual(pinyin.get('少女'), u('shǎonv̌'))
def test_get_with_delimiter(self):
self.assertEqual(pinyin.get('你好', " "), u('nǐ hǎo'))
self.assertEqual(pinyin.get('你好吗?', " "), u('nǐ hǎo ma ?'))
self.assertEqual(pinyin.get('你好吗?', " "), u('nǐ hǎo ma ?'))
def test_get_initial_with_delimiter(self):
self.assertEqual(pinyin.get_initial('你好', "-"), u('n-h'))
self.assertEqual(pinyin.get_initial('你好吗?', "-"), u('n-h-m-?'))
self.assertEqual(pinyin.get_initial('你好吗?', "-"), u('n-h-m-?'))
def test_get_initial(self):
self.assertEqual(pinyin.get_initial('你好'), u('n h'))
self.assertEqual(pinyin.get_initial('你好吗?'), u('n h m ?'))
self.assertEqual(pinyin.get_initial('你好吗?'), u('n h m ?'))
self.assertEqual(pinyin.get_initial('你好'), 'n h')
def test_mixed_chinese_english_input(self):
self.assertEqual(pinyin.get('hi你好'), u('hinǐhǎo'))
def test_correct_diacritical(self):
self.assertEqual(pinyin.get("操"), u("cāo"))
self.assertEqual(pinyin.get("小"), u("xiǎo"))
self.assertEqual(pinyin.get("绝"), u("jué"))
self.assertEqual(pinyin.get("被"), u("bèi"))
self.assertEqual(pinyin.get("略"), u("lvè"))
if __name__ == '__main__':
unittest.main()
|
package sniper.histogram.service;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.HdrHistogram.ConcurrentHistogram;
import org.HdrHistogram.Histogram;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sniper.histogram.dataObject.meta.BaseMeta;
import sniper.histogram.dataObject.meta.Meta;
import sniper.histogram.dataObject.result.HistogramResult;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.zip.Deflater;
import static java.nio.ByteOrder.BIG_ENDIAN;
/**
* Created by peiliping on 16-7-15.
*/
public class BaseHistogramService {
protected static Logger LOG = LoggerFactory.getLogger(BaseHistogramService.class);
protected final ConcurrentHashMap<String, Pair<Meta, Histogram>> writerMap = new ConcurrentHashMap<>();
protected final ConcurrentSkipListMap<String, Pair<Meta, Histogram>> readerMap = new ConcurrentSkipListMap<>();
protected final long lowest;
protected final long highest;
protected final int precisions;
public BaseHistogramService(long lowest, long highest, int precisions) {
this.lowest = lowest;
this.highest = highest;
this.precisions = precisions;
}
public BaseHistogramService() {
this(1, Long.MAX_VALUE, 3);
}
public void addRecord(String nameSpace, String metric, long timestamp, long value, long count) {
String key = buildKey(nameSpace, metric, timestamp);
Pair<Meta, Histogram> pair = writerMap.get(key);
if (pair == null) {
for (; ; ) {
pair = Pair.of(buildMeta(nameSpace, metric, timestamp), buildHistogram(timestamp));
Pair<Meta, Histogram> old = writerMap.putIfAbsent(key, pair);
if (old == null) {
readerMap.put(key, pair);
break;
}
}
}
pair.getRight().recordValueWithCount(value, count);
while (true) {
long old = pair.getLeft().getLastModifyTime().get();
if (timestamp < old || pair.getLeft().getLastModifyTime().compareAndSet(old, timestamp))
break;
}
}
public void addRecord(String nameSpace, String metric, long timestamp, long value) {
addRecord(nameSpace, metric, timestamp, value, 1);
}
protected String buildKey(String nameSpace, String metric, long timestamp) {
return BaseMeta.builder().nameSpace(nameSpace).metric(metric).build().buildKey();
}
protected Meta buildMeta(String nameSpace, String metric, long timestamp) {
return BaseMeta.builder().nameSpace(nameSpace).metric(metric).build();
}
protected Histogram buildHistogram(long startTime) {
Histogram hsm = new ConcurrentHistogram(lowest, highest, precisions);
hsm.setAutoResize(true);
hsm.setStartTimeStamp(startTime);
return hsm;
}
public ConcurrentNavigableMap<String, Pair<Meta, Histogram>> acquireAllData() {
return readerMap.clone();
}
public void shuffle(ConcurrentNavigableMap<String, Pair<Meta, Histogram>> part, String path) throws IOException {
File file = new File(path);
for (Map.Entry<String, Pair<Meta, Histogram>> val : part.entrySet()) {
Meta baseMeta = val.getValue().getLeft();
Histogram hsm = val.getValue().getRight();
hsm.setEndTimeStamp(baseMeta.getLastModifyTime().get());
HistogramResult result = buildResult(baseMeta, hsm);
Files.append(JSON.toJSONString(result) + "\n", file, Charsets.UTF_8);
readerMap.remove(val.getKey());
writerMap.remove(val.getKey());
}
}
protected HistogramResult buildResult(Meta baseMeta, Histogram hsm) {
return HistogramResult.builder().nameSpace(baseMeta.getNameSpace()).metric(baseMeta.getMetric()).timeWindow(null).startTime(hsm.getStartTimeStamp())
.endTime(hsm.getEndTimeStamp()).totalCount(hsm.getTotalCount()).mean(hsm.getMean()).min(hsm.getMinValue()).max(hsm.getMaxValue()).p1(hsm.getValueAtPercentile(1))
.p99(hsm.getValueAtPercentile(99)).footprint(buildFootPrint(hsm)).histogram(compressData(hsm)).build();
}
protected String compressData(Histogram hsm) {
ByteBuffer targetBuffer = ByteBuffer.allocate(hsm.getNeededByteBufferCapacity()).order(BIG_ENDIAN);
targetBuffer.clear();
int compressedLength = hsm.encodeIntoCompressedByteBuffer(targetBuffer, Deflater.BEST_COMPRESSION);
byte[] compressedArray = Arrays.copyOf(targetBuffer.array(), compressedLength);
return DatatypeConverter.printBase64Binary(compressedArray);
}
protected long[] buildFootPrint(Histogram hsm) {
long[] fp = new long[21];
for (int i = 0; i < 21; i++)
fp[i] = hsm.getValueAtPercentile(i * 5);
return fp;
}
}
|
/*
This file is part of the clang-lazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected]
Author: Sérgio Martins <[email protected]>
Copyright (C) 2015 Sergio Martins <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "variantsanitizer.h"
#include "Utils.h"
#include "checkmanager.h"
using namespace std;
using namespace clang;
VariantSanitizer::VariantSanitizer(const std::string &name)
: CheckBase(name)
{
}
static bool isMatchingClass(const std::string &name)
{
static const vector<string> classes = {"QBitArray", "QByteArray", "QChar", "QDate", "QDateTime",
"QEasingCurve", "QJsonArray", "QJsonDocument", "QJsonObject",
"QJsonValue", "QLocale", "QModelIndex", "QPoint", "QPointF",
"QRect", "QRectF", "QRegExp", "QString", "QRegularExpression",
"QSize", "QSizeF", "QStringList", "QTime", "QUrl", "QUuid" };
return find(classes.cbegin(), classes.cend(), name) != classes.cend();
}
void VariantSanitizer::VisitStmt(clang::Stmt *stm)
{
auto callExpr = dyn_cast<CXXMemberCallExpr>(stm);
if (callExpr == nullptr)
return;
CXXMethodDecl *methodDecl = callExpr->getMethodDecl();
if (methodDecl == nullptr || methodDecl->getNameAsString() != "value")
return;
CXXRecordDecl *decl = methodDecl->getParent();
if (decl == nullptr || decl->getNameAsString() != "QVariant")
return;
FunctionTemplateSpecializationInfo *specializationInfo = methodDecl->getTemplateSpecializationInfo();
if (specializationInfo == nullptr || specializationInfo->TemplateArguments == nullptr || specializationInfo->TemplateArguments->size() != 1)
return;
const TemplateArgument &argument = specializationInfo->TemplateArguments->get(0);
QualType qt = argument.getAsType();
const Type *t = qt.getTypePtrOrNull();
if (t == nullptr)
return;
bool matches = false;
if (t->isBooleanType() /*|| t->isIntegerType() || t->isFloatingType()*/) {
matches = true;
} else {
CXXRecordDecl *recordDecl = t->getAsCXXRecordDecl();
matches = t->isClassType() && recordDecl && isMatchingClass(recordDecl->getNameAsString());
}
if (matches) {
std::string error = std::string("Use QVariant::toFoo() instead of QVariant::value<Foo>()");
emitWarning(stm->getLocStart(), error.c_str());
}
}
REGISTER_CHECK("variant-sanitizer", VariantSanitizer)
|
using System;
using DocsBr.Utils;
namespace DocsBr.Validation.IE
{
/// <summary>
/// Validação da IE do Ceará
/// </summary>
/// <remarks>
/// ROTEIRO DE CRÍTICA DA INSCRIÇÃO ESTADUAL:
/// http://www.sintegra.gov.br/Cad_Estados/cad_CE.html
/// </remarks>
public class IECearaValidator : IIEValidator
{
private string inscEstadual;
public IECearaValidator(string inscEstadual)
{
this.inscEstadual = new OnlyNumbers(inscEstadual).ToString();
}
public bool IsValid()
{
if (!IsSizeValid()) return false;
return HasValidCheckDigits();
}
private bool IsSizeValid()
{
return this.inscEstadual.Length == 9;
}
private bool HasValidCheckDigits()
{
string number = this.inscEstadual.Substring(0, this.inscEstadual.Length - 1);
DigitoVerificador digitoVerificador = new DigitoVerificador(number)
.ComMultiplicadoresDeAte(2, 9)
.Substituindo("0", 10, 11);
return digitoVerificador.CalculaDigito() == this.inscEstadual.Substring(this.inscEstadual.Length - 1, 1);
}
}
}
|
# -*- coding: utf-8 -*-
# kommons - A library for common classes and functions
#
# Copyright (C) 2013 Björn Ricks <[email protected]>
#
# 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.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
""" Kommon python modules, classes and functions
Kommons is a collection of python modules, classes and functions which are used
in several projects and simplify standard recurrent tasks
"""
__version_info__ = ("0", "1dev1")
__version__ = '.'.join(__version_info__)
__description__ = "A python library for common classes and functions"
__author__ = u"Björn Ricks"
__author_email__ = "[email protected]",
__url__ = "http://github.com/bjoernricks/python-quilt",
__license__ = "LGPLv2.1+",
# vim: et sw=4 ts=4 tw=80:
|
namespace Khala.EventSourcing
{
using System;
using Khala.Messaging;
using Newtonsoft.Json;
public abstract class DomainEvent : IDomainEvent, IPartitioned
{
public Guid SourceId { get; set; }
public int Version { get; set; }
public DateTime RaisedAt { get; set; }
[JsonIgnore]
public virtual string PartitionKey => SourceId.ToString();
public void Raise(IVersionedEntity source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
SourceId = source.Id;
Version = source.Version + 1;
RaisedAt = DateTime.UtcNow;
}
}
}
|
# Copyright (c) 2011, Enthought, Ltd.
# Authors: Pietro Berkes <[email protected]>, Andrey Rzhetsky,
# Bob Carpenter
# License: Modified BSD license (2-clause)
"""Utility functions."""
import numpy as np
from numpy import log
#: In annotations arrays, this is the value used to indicate missing values
MISSING_VALUE = -1
class PyannoError(ValueError):
"""ValueError subclass raised by pyAnno functions and methods.
"""
pass
def labels_count(annotations, nclasses, missing_value_label=MISSING_VALUE):
"""Compute the total count of labels in observed annotations.
Raises a PyannoValueError if there are no valid annotations.
Arguments
---------
annotations : array-like object, shape = (n_items, n_annotators)
annotations[i,j] is the annotation made by annotator j on item i
nclasses : int
Number of label classes in `annotations`
Returns
-------
count : list of length n_classes
count[k] is the number of elements of class k in `annotations`
"""
annotations = np.asarray(annotations)
valid = annotations != missing_value_label
nobservations = valid.sum()
if nobservations == 0:
# no valid observations
raise PyannoValueError('No valid annotations')
return list(np.bincount(annotations[valid], minlength=nclasses))
def majority_vote(annotations, missing_value_label=MISSING_VALUE):
"""Compute an estimate of the real class by majority vote.
In case of ties, return the class with smallest number.
If a row only contains invalid entries, return `MISSING_VALUE`.
Arguments
---------
annotations : array-like object, shape = (n_items, n_annotators)
annotations[i,j] is the annotation made by annotator j on item i
Return
------
vote : list of length n_items
vote[i] is the majority vote estimate for item i
"""
annotations = np.asarray(annotations)
nitems = annotations.shape[0]
valid = annotations != missing_value_label
vote = [0] * nitems
for i in range(nitems):
if not np.any(valid[i,:]):
# no valid entries on this row
vote[i] = missing_value_label
else:
count = np.bincount(annotations[i, valid[i,:]])
vote[i] = count.argmax()
return vote
def labels_frequency(annotations, nclasses):
"""Compute the total frequency of labels in observed annotations.
Example:
>>> labels_frequency([[1, 1, 2], [-1, 1, 2]], 4)
array([ 0. , 0.6, 0.4, 0. ])
Arguments
---------
annotations : array-like object, shape = (n_items, n_annotators)
annotations[i,j] is the annotation made by annotator j on item i
nclasses : int
Number of label classes in `annotations`
Returns
-------
freq : ndarray, shape = (n_classes, )
freq[k] is the frequency of elements of class k in `annotations`, i.e.
their count over the number of total of observed (non-missing) elements
"""
return np.histogram(annotations, bins=range(nclasses+1), normed=True)[0]
#annotations = np.array(annotations)
#freq = lambda x: np.sum(annotations == x)
#tot = np.sum(np.array(annotations >= 0)
#return np.array(map(freq, range(nclasses)))/float(tot)
|
<!DOCTYPE html>
<html>
<head>
<title>Clothes - By Mayur Decor</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="home decoration shopping store" />
<meta name="keyword" content="clothes,furnishing"/>
<link rel="canonical" href="localhost:5050" />
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
<script src="/static/js/jquery-3.1.1.min.js"></script>
<script src="/static/js/bootstrap.js"></script>
</head>
<body>
<!-- - - - - - - - - - - - - - - - - HEADER SECTION - - - - - - - - - - - - -->
<section class="header">
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-brand" style="margin-left: 0px;">
<h1>
<a href="/">
<img src="/static/images/company-logo(4).png" alt="mayur furnishing store" >
</a>
</h1>
</div>
<nav class="nav navbar-nav primary-nav-hover">
<ul class="navigation-ul clearfix">
<li > <a href="/curtains"> Curtains </a> </li>
<li > <a href="/sofa"> Sofa </a> </li>
<li > <a href="/chairs" > Desginer Chair's </a> </li>
<li > <a href="/clothes" class="active"> Clothes </a> </li
</ul>
</nav>
<div class="floatright">
<nav class="nav navbar-nav">
<form class="form-inline" style="margin-top: 5px;">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</nav>
<nav class="nav navbar-nav user-login-cart">
<ul class="clearfix" style="margin-top: 5px;">
<li>
<a class="cart-animation"></a>
<a href="/viewcart"> <img src="/static/images/header-shop-cart.png" class="shop-cart" alt="shop cart"> </a>
</li>
<li> <img src="/static/images/header-user-login.png" class="user-login" alt="user login"> </li>
<li> <label class="username"></label></li>
<li>
<div class="dropdown">
<a id="dLabel" href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="ture">
<span class="caret"></span> </a>
<ul class="dropdown-menu" aria-labelledby="dLabel">
<li> <a href="/history"> history </a> </li>
<li> <a href="/logout"> logout </a> </li>
<!-- <li> <a href="#"> test </a> </li> -->
</ul>
</div>
</li>
</ul>
</nav>
</div>
</div>
</nav>
</section>
<!-- - - - - - - - - - - - - - MIDDLE SECTION - - - - - - - - - - - - - - -->
<section class="middle-section">
<div class="container">
<div class="col-md-2 left-Side-Menu">
<div class="product-type">
<span class='type-title'>Clothes Type</span>
<ul class="product-type-ul" id="product-type">
</ul>
</div>
</div>
<div class="col-lg-10 product-list-container">
<ul class="product-list row" id="product-list">
</ul>
</div>
</div>
</section>
<!-- - - - - - - - - - - - - - - - - FOOTER SECTION - - - - - - - - - - - -->
<section class="footer-section">
<footer>
<div class="navbar navbar-inverse ">
<div class="row">
<div class="container">
<div class="col-md-3 col-sm-6 footerleft">
<div class="locateUs"> LOCATE US AT </div>
<span> B.No : 13 / b, R.no : 005, <span>
<span> Goregaon (EAST) </span>
<span> Mumbai :- 400065 </span>
</div>
<div class="col-md-3 footerleft">
<div class="locateUs">CONTACT US </div>
<span> +91 8291436982 </span>
<span> [email protected] </span>
</div>
<div class="col-md-6">
<div class="locateUs"> FIND US ON </div>
<ul class="footer-ul clearfix">
<li> <a href="#"> <img src="/static/images/facebook.png" alt="facebook"> </a> </li>
<li> <a href="#"> <img src="/static/images/instagram.png" alt="instagram"> </a> </li>
<li> <a href="#"> <img src="/static/images/youtube.png" alt="youtub"> </a> </li>
<li> <a href="#"> <img src="/static/images/twitter.png" alt="twitter"> </a> </li>
<li> <a href="#"> <img src="/static/images/google-plus.png" alt="google-plus"> </a> </li>
<li> <a href="#"> <img src="/static/images/google-maps.png" alt="google- maps"> </a> </li>
</ul>
</div>
</div>
</div>
</div>
</footer>
</section>
</body>
<script type="text/javascript" src="/static/js/searchbar.js"></script>
<script type="text/javascript" src="/static/js/userSessionHandler.js"></script>
<script type="text/javascript" src="/static/js/clothes.js"></script>
</html>
|
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.validation;
import com.thoughtworks.go.domain.materials.ValidationBean;
import org.apache.commons.lang.StringUtils;
public class LengthValidator extends Validator<String> {
private final int length;
public LengthValidator(int length) {
super("Only " + length + " charactors are allowed");
this.length = length;
}
public ValidationBean validate(String value) {
if (StringUtils.isEmpty(value)) {
return ValidationBean.valid();
}
if (value.length() <= length) {
return ValidationBean.valid();
} else {
return ValidationBean.notValid("Only " + length + " charactors are allowed");
}
}
}
|
package batfish.representation.cisco;
public class RouteMapMatchNeighborLine extends RouteMapMatchLine {
private static final long serialVersionUID = 1L;
private String _neighborIp;
public RouteMapMatchNeighborLine(String neighborIP) {
_neighborIp = neighborIP;
}
public String getNeighborIp() {
return _neighborIp;
}
@Override
public RouteMapMatchType getType() {
return RouteMapMatchType.NEIGHBOR;
}
}
|
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice('"-I' + slice_dir + '" Test.ice')
import Test, TestI
def run(args, communicator):
adapter = communicator.createObjectAdapter("TestAdapter")
adapter2 = communicator.createObjectAdapter("TestAdapter2")
adapter3 = communicator.createObjectAdapter("TestAdapter3")
object = TestI.ThrowerI()
adapter.add(object, Ice.stringToIdentity("thrower"))
adapter2.add(object, Ice.stringToIdentity("thrower"))
adapter3.add(object, Ice.stringToIdentity("thrower"))
adapter.activate()
adapter2.activate()
adapter3.activate()
communicator.waitForShutdown()
return True
try:
initData = Ice.InitializationData()
initData.properties = Ice.createProperties(sys.argv)
initData.properties.setProperty("Ice.Warn.Dispatch", "0")
initData.properties.setProperty("Ice.Warn.Connections", "0");
initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010")
initData.properties.setProperty("Ice.MessageSizeMax", "10")
initData.properties.setProperty("TestAdapter2.Endpoints", "default -p 12011")
initData.properties.setProperty("TestAdapter2.MessageSizeMax", "0")
initData.properties.setProperty("TestAdapter3.Endpoints", "default -p 12012")
initData.properties.setProperty("TestAdapter3.MessageSizeMax", "1")
with Ice.initialize(sys.argv, initData) as communicator:
status = run(sys.argv, communicator)
except:
traceback.print_exc()
status = False
sys.exit(not status)
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'qtype_missingtype', language 'pt_br', branch 'MOODLE_30_STABLE'
*
* @package qtype_missingtype
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['answerno'] = 'Resposta {$a}';
$string['cannotchangeamissingqtype'] = 'Você não pode fazer nada em uma questão do tipo faltante.';
$string['deletedquestion'] = 'Questão faltante';
$string['deletedquestiontext'] = 'A questão está faltando. Não foi possível mostrar nada.';
$string['missing'] = 'Questão de um tipo que não está instalado no sistema';
$string['missingqtypewarning'] = 'Esta questão é de um tipo que não está instalado no sistema. Você não será capaz de fazer nada com essa questão.';
$string['pluginname'] = 'Tipo de falha';
$string['pluginnameadding'] = 'Adicionando uma questão de um um tipo que não está instalado no sistema';
$string['pluginnameediting'] = 'Editando questão de um tipo que não está instalada nesse sistema';
$string['warningmissingtype'] = '<b> Esta pergunta é de um tipo que ainda não foi instalado em seu Moodle. <br /> Informe, por favor, o seu administrador do Moodle. </ b>';
|
# coding=utf-8
import sys
import config
import utils
import datetime
from scrapy.spiders import Spider
from scrapy.http import Request
from sql import SqlManager
class BaseSpider(Spider):
name = 'basespider'
def __init__(self, *a, **kw):
super(BaseSpider, self).__init__(*a, **kw)
self.urls = []
self.headers = {}
self.timeout = 10
self.is_record_web_page = False
self.sql = SqlManager()
def init(self):
self.meta = {
'download_timeout': self.timeout,
}
self.dir_log = 'log/proxy/%s' % self.name
utils.make_dir(self.dir_log)
self.sql.init_proxy_table(config.free_ipproxy_table)
def start_requests(self):
for i, url in enumerate(self.urls):
yield Request(
url=url,
headers=self.headers,
meta=self.meta,
dont_filter=True,
callback=self.parse_page,
errback=self.error_parse,
)
def parse_page(self, response):
self.write(response.body)
pass
def error_parse(self, failure):
request = failure.request
pass
def add_proxy(self, proxy):
self.sql.insert_proxy(config.free_ipproxy_table, proxy)
def write(self, data):
if self.is_record_web_page:
with open('%s/%s.html' % (self.dir_log, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')),
'w') as f:
f.write(data)
f.close()
def close(spider, reason):
spider.sql.commit()
|
#pragma once
#include <vector>
#include <stdint.h>
#include <d3d9.h>
#include "Plugin/D3D9/D3D9PreDeclare.h"
class D3D9AdapterList{
public:
D3D9AdapterList();
~D3D9AdapterList();
void Enumerate( IDirect3D9* device );
private:
std::vector<D3D9AdapterPtr> adapters_;
uint32_t current_adpater_;
};
|
<?php namespace ProcessWire;
require_once(dirname(__FILE__) . '/ProcessPageListRender.php');
/**
* JSON implementation of the Page List rendering
*
*/
class ProcessPageListRenderJSON extends ProcessPageListRender {
protected $systemIDs = array();
public function __construct(Page $page, PageArray $children) {
parent::__construct($page, $children);
$this->systemIDs = array(
$this->config->http404PageID,
$this->config->adminRootPageID,
$this->config->trashPageID,
$this->config->loginPageID,
);
}
public function renderChild(Page $page) {
$outputFormatting = $page->outputFormatting;
$page->setOutputFormatting(true);
$class = '';
$type = '';
$note = '';
$label = '';
$icons = array();
if(in_array($page->id, $this->systemIDs)) {
$type = 'System';
if($page->id == $this->config->http404PageID) $label = $this->_('404 Page Not Found'); // Label for '404 Page Not Found' page in PageList // Overrides page title if used
else if($page->id == $this->config->adminRootPageID) $label = $this->_('Admin'); // Label for 'Admin' page in PageList // Overrides page title if used
else if($page->id == $this->config->trashPageID && isset($this->actionLabels['trash'])) $label = $this->actionLabels['trash']; // Label for 'Trash' page in PageList // Overrides page title if used
// if label is not overridden by a language pack, make $label blank to use the page title instead
if(in_array($label, array('Trash', 'Admin', '404 Page Not Found'))) $label = '';
}
if($page->getAccessParent() === $page && $page->parent->id) {
$accessTemplate = $page->getAccessTemplate();
if($accessTemplate && $accessTemplate->hasRole('guest')) {
$accessTemplate = $page->parent->getAccessTemplate();
if($accessTemplate && !$accessTemplate->hasRole('guest') && !$page->isTrash()) {
$class .= ' PageListAccessOn';
$icons[] = 'key fa-flip-horizontal';
}
} else {
$accessTemplate = $page->parent->getAccessTemplate();
if($accessTemplate && $accessTemplate->hasRole('guest')) {
$class .= ' PageListAccessOff';
$icons[] = 'key';
}
}
}
if($page->id == $this->config->trashPageID) {
$note = "< " . $this->_("Trash open: drag pages below here to trash them"); // Message that appears next to the Trash page when open
$icons = array('trash-o'); // override any other icons
} else {
if($page->hasStatus(Page::statusTemp)) $icons[] = 'bolt';
if($page->hasStatus(Page::statusLocked)) $icons[] = 'lock';
if($page->hasStatus(Page::statusDraft)) $icons[] = 'paperclip';
}
if(!$label) $label = $this->getPageLabel($page);
if(count($icons)) foreach($icons as $n => $icon) {
$label .= "<i class='PageListStatusIcon fa fa-fw fa-$icon'></i>";
}
$a = array(
'id' => $page->id,
'label' => $label,
'status' => $page->status,
'numChildren' => $page->numChildren(1),
'path' => $page->template->slashUrls || $page->id == 1 ? $page->path() : rtrim($page->path(), '/'),
'template' => $page->template->name,
//'rm' => $this->superuser && $page->trashable(),
'actions' => array_values($this->getPageActions($page)),
);
if($class) $a['addClass'] = trim($class);
if($type) $a['type'] = $type;
if($note) $a['note'] = $note;
$page->setOutputFormatting($outputFormatting);
return $a;
}
public function render() {
$children = array();
$extraPages = array(); // pages forced to bottom of list
foreach($this->children as $page) {
if(!$this->superuser && !$page->listable()) continue;
if(in_array($page->id, $this->systemIDs)) {
$extraPages[] = $page;
continue;
}
$child = $this->renderChild($page);
$children[] = $child;
}
if($this->superuser) foreach($extraPages as $page) {
$children[] = $this->renderChild($page);
}
$json = array(
'page' => $this->renderChild($this->page),
'children' => $children,
'start' => $this->start,
'limit' => $this->limit,
);
if($this->getOption('getArray')) return $json;
header("Content-Type: application/json;");
return json_encode($json);
}
}
|
using Neptuo;
using Neptuo.Commands;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Commands
{
/// <summary>
/// Renames a category with a key <see cref="CategoryKey"/>.
/// </summary>
public class RenameCategory : Command
{
/// <summary>
/// Gets a key of the category to rename.
/// </summary>
public IKey CategoryKey { get; private set; }
/// <summary>
/// Gets a new name of the category.
/// </summary>
public string NewName { get; private set; }
/// <summary>
/// Renames a category with a key <paramref name="categoryKey"/>.
/// </summary>
/// <param name="categoryKey">A key of the category to rename.</param>
/// <param name="newName">A new name of the category.</param>
public RenameCategory(IKey categoryKey, string newName)
{
Ensure.Condition.NotEmptyKey(categoryKey);
Ensure.NotNull(newName, "newName");
CategoryKey = categoryKey;
NewName = newName;
}
}
}
|
/*
* Copyright (C) 2013-2015 Gonçalo Baltazar <[email protected]>
*
* This file is part of NBTEditor.
*
* NBTEditor 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.
*
* NBTEditor 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 NBTEditor. If not, see <http://www.gnu.org/licenses/>.
*/
package com.goncalomb.bukkit.nbteditor.nbt.attributes;
import java.util.HashMap;
public enum AttributeType {
// Mobs
MAX_HEALTH("MaxHealth", "generic.maxHealth", 0.0, Double.MAX_VALUE),
FOLLOW_RANGE("FollowRange", "generic.followRange", 0.0, 2048),
KNOCKBACK_RESISTANCE("KnockbackResistance", "generic.knockbackResistance", 0.0, 1.0),
MOVEMENT_SPEED("MovementSpeed", "generic.movementSpeed", 0.0, Double.MAX_VALUE),
ATTACK_DAMAGE("AttackDamage", "generic.attackDamage", 0.0, Double.MAX_VALUE),
// Horses
JUMP_STRENGTH("JumpStrength", "horse.jumpStrength", 0.0, 2),
// Zombies
SPAWN_REINFORCEMENTS("SpawnReinforcements", "zombie.spawnReinforcements", 0.0, 1.0);
private static final HashMap<String, AttributeType> _attributes = new HashMap<String, AttributeType>();
private static final HashMap<String, AttributeType> _attributesInternal = new HashMap<String, AttributeType>();
private String _name;
String _internalName;
private double _min;
private double _max;
static {
for (AttributeType type : values()) {
_attributes.put(type._name.toLowerCase(), type);
_attributesInternal.put(type._internalName, type);
}
}
private AttributeType(String name, String internalName, double min, double max) {
_name = name;
_internalName = internalName;
_min = min;
_max = max;
}
public String getName() {
return _name;
}
public double getMin() {
return _min;
}
public double getMax() {
return _max;
}
public static AttributeType getByName(String name) {
return _attributes.get(name.toLowerCase());
}
static AttributeType getByInternalName(String name) {
return _attributesInternal.get(name);
}
@Override
public String toString() {
return _name;
}
}
|
#!/usr/bin/python
import unittest
from PySide.QtGui import QApplication
from QtMobility.Contacts import *
class QtContactsUsage(unittest.TestCase):
def testNewandRetrieveContact(self):
app = QApplication([])
cm = QContactManager()
#Create a new Contact
exampleContact = QContact()
nameDetail = QContactName()
nameDetail.setFirstName("John")
nameDetail.setLastName("PySide")
phoneNumberDetail = QContactPhoneNumber()
phoneNumberDetail.setNumber("+123 4567")
exampleContact.saveDetail(nameDetail)
exampleContact.saveDetail(phoneNumberDetail)
self.assert_(cm.saveContact(exampleContact))
filtr = QContactLocalIdFilter()
filtr.add(exampleContact.localId())
newContact = cm.contacts(filtr)[0]
surname = newContact.detail(QContactName.DefinitionName).value(QContactName.FieldLastName)
phone = newContact.detail(QContactPhoneNumber.DefinitionName).value(QContactPhoneNumber.FieldNumber)
self.assertEqual("PySide", surname)
self.assertEqual("+123 4567", phone)
self.assert_(cm.removeContact(exampleContact.localId()))
class PhoneNumberTest(unittest.TestCase):
def basicTest(self):
number = QContactPhoneNumber()
self.assertEqual(number.number(), '')
subtypes = [QContactPhoneNumber.SubTypeCar, QContactPhoneNumber.SubTypeFax]
number.setSubTypes(subtypes)
self.assertEqual(number.subTypes(), subtypes)
self.assertEqual(number.value(QContactPhoneNumber.FieldSubTypes), subtypes)
if __name__ == '__main__':
unittest.main()
|
/**
* Input Placeholder Polyfill
* MIT Licensed
* Created by Christopher Rolfe
*/
if (!('placeholder' in document.createElement("input"))) {
// Get all the inputs
var inputs = document.getElementsByTagName('input');
// Loop over them
for (var i = 0; i < inputs.length; i++) {
// If they don't have a preset value
if (!inputs[i].value) {
// The set the placeholder
inputs[i].value = inputs[i].getAttribute('placeholder');
}
// Attach event listeners for click and blur
// Click so that we can clear the placeholder if we need to
// Blur to re-add it if needed
if (inputs[i].addEventListener) {
inputs[i].addEventListener('click', hidePlaceholderOnFocus, false);
inputs[i].addEventListener('blur', unfocusOnAnElement, false);
} else if (inputs[i].attachEvent) {
inputs[i].attachEvent('onclick', hidePlaceholderOnFocus);
inputs[i].attachEvent('onblur', unfocusOnAnElement);
}
}
/**
* When the input value is the same as the placeholder clear it
*/
function hidePlaceholderOnFocus(event) {
target = (event.currentTarget) ? event.currentTarget : event.srcElement;
if (target.value == target.getAttribute('placeholder')) {
target.value = '';
}
}
/**
* When the input has an empty value put the placeholder back in
*/
function unfocusOnAnElement(event) {
target = (event.currentTarget) ? event.currentTarget : event.srcElement;
if (target.value == '') {
target.value = target.getAttribute('placeholder');
}
}
}
|
#!/usr/bin/env python
import json
import os
import os.path as osp
import skimage.io
here = osp.dirname(osp.abspath(__file__))
def main():
item_data_dir = osp.join(here, 'item_data')
for item_name_upper in os.listdir(item_data_dir):
item_dir = osp.join(item_data_dir, item_name_upper)
if not osp.isdir(item_dir):
continue
item_name_lower = item_name_upper.lower()
frame_id = 0
for fname in sorted(os.listdir(item_dir)):
if fname.startswith(item_name_upper):
continue
fname = osp.join(item_dir, fname)
ext = osp.splitext(fname)[1]
if not (osp.isfile(fname) and ext in ['.jpg', '.png']):
continue
img = skimage.io.imread(fname)
frame_id += 1
dst_fname = osp.join(
item_dir, '{:s}_{:03d}.png'.format(item_name_upper, frame_id))
skimage.io.imsave(dst_fname, img)
print('{:s}: {:s} -> {:s}'
.format(item_name_lower, fname, dst_fname))
os.remove(fname)
if __name__ == '__main__':
main()
|
# Copyright (c) 2017 itsonlyme.name
#
# 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.
import os
import uuid
import json
import pickle
import unittest
import sklearn.neural_network as snn
from swiftclient import client
from e2emlstorlets.tools.swift_access import parse_config,\
get_auth, put_local_file, deploy_storlet
class TestRecognizeFace(unittest.TestCase):
def setUp(self):
self.container_name = str(uuid.uuid4())
conf = parse_config('access.cfg')
self.url, self.token = get_auth(conf)
self.repo_dir=conf['repo_dir']
deploy_storlet(conf, 'e2emlstorlets/video_recognize_face/video_recognize_face.py',
'video_recognize_face.MovieRecognizeFace')
client.put_container(self.url, self.token, self.container_name)
put_local_file(self.url, self.token, self.container_name,
os.path.join(conf['repo_dir'], 'test/data'),
'eran_swapped_mov.avi')
headers = {'X-Object-Meta-name-to-id': json.dumps({'eran': 1})}
put_local_file(self.url, self.token, self.container_name,
os.path.join(conf['repo_dir'], 'test/data'),
'model', headers=headers)
def _tearDown(self):
client.delete_object(self.url, self.token,
self.container_name,
'eran_swapped_mov.avi')
client.delete_object(self.url, self.token,
self.container_name,
'model')
client.delete_object(self.url, self.token,
self.container_name,
'recognized_mov.avi')
client.delete_container(self.url, self.token, self.container_name)
def invoke_storlet(self):
headers = {'X-Run-Storlet': 'video_recognize_face.py'}
source_obj1 = 'eran_swapped_mov.avi'
source_obj2 = os.path.join('/' + self.container_name,
'model')
headers['X-Storlet-Extra-Resources'] = source_obj2
dst_path = os.path.join(self.container_name, 'recognized_mov.avi')
response_dict = {}
client.copy_object(
self.url, self.token,
self.container_name, source_obj1,
destination=dst_path,
headers=headers,
response_dict=response_dict)
self.assertTrue(response_dict['status']==201)
def test_recognize_face(self):
self.invoke_storlet()
headers, body = client.get_object(self.url, self.token,
self.container_name, 'recognized_mov.avi')
|
#pylint: disable=E0401,C0103
from pyrevit import revit, DB
from pyrevit import script
output = script.get_output()
areas = DB.FilteredElementCollector(revit.doc)\
.OfCategory(DB.BuiltInCategory.OST_Areas)\
.WhereElementIsNotElementType().ToElements()
rooms = DB.FilteredElementCollector(revit.doc)\
.OfCategory(DB.BuiltInCategory.OST_Rooms)\
.WhereElementIsNotElementType().ToElements()
spaces = DB.FilteredElementCollector(revit.doc)\
.OfCategory(DB.BuiltInCategory.OST_MEPSpaces)\
.WhereElementIsNotElementType().ToElements()
processed_items = {DB.Area: [],
DB.Architecture.Room: [],
DB.Mechanical.Space: []}
selection = revit.get_selection()
def calc_and_print(items, item_type, type_name, match_name):
item_total_area = 0.0
item_count = 0
if match_name not in processed_items[item_type]:
print("{} TYPE IS: {}".format(type_name, match_name))
for item in items:
item_name = \
item.Parameter[DB.BuiltInParameter.ROOM_NAME].AsString()
item_number = \
item.Parameter[DB.BuiltInParameter.ROOM_NUMBER].AsString()
item_level = \
item.Parameter[
DB.BuiltInParameter.ROOM_LEVEL_ID].AsValueString()
if revit.query.is_placed(item):
if match_name == item_name:
area_value = \
item.Parameter[DB.BuiltInParameter.ROOM_AREA].AsDouble()
print('{} {} #{} \"{}\" @ \"{}\" = {}'.format(
output.linkify(item.Id),
type_name.title(),
item_number,
item_name,
item_level,
revit.units.format_area(area_value)
))
item_total_area += area_value
item_count += 1
else:
print(':cross_mark: '
'SKIPPED \"NOT PLACED\" {} {} #{} \"{}\" @ \"{}\"'
.format(
output.linkify(item.Id),
type_name.title(),
item_number,
item_name,
item_level))
print("TOTAL OF {} {}S WERE FOUND.".format(item_count, type_name))
processed_items[item_type].append(match_name)
return item_total_area, item_count
for el in selection.elements:
count = 0
total = 0.0
if isinstance(el, DB.Area):
target_name = el.Parameter[DB.BuiltInParameter.ROOM_NAME].AsString()
area_total, area_count = \
calc_and_print(areas, DB.Area, 'AREA', target_name)
count += area_count
total += area_total
elif isinstance(el, DB.Architecture.Room):
target_name = el.Parameter[DB.BuiltInParameter.ROOM_NAME].AsString()
area_total, area_count = \
calc_and_print(rooms, DB.Architecture.Room, 'ROOM', target_name)
count += area_count
total += area_total
elif isinstance(el, DB.Mechanical.Space):
target_name = el.Parameter[DB.BuiltInParameter.ROOM_NAME].AsString()
area_total, area_count = \
calc_and_print(spaces, DB.Mechanical.Space, 'SPACE', target_name)
count += area_count
total += area_total
if count != 0:
average = total / count
print('\nAVERAGE AREA OF THE SELECTED TYPE IS:'
'\n{}'
'\n ======================================='
'\n{} ACRE'
'\n{} HECTARES'.format(revit.units.format_area(average),
average / 43560,
average / 107639))
|
import { IHttpClient } from '../http';
import { getTypedResponse, BaseResource } from './resource';
import { License } from '../models';
import { CancellationToken } from '../cancellation-token';
export class LicenseResource extends BaseResource {
constructor(httpClient: IHttpClient) {
super(httpClient);
}
async get(usage: boolean = false, token?: CancellationToken): Promise<License> {
const response = await this.httpClient.get('licensing', usage ? {usage} : undefined, token);
return getTypedResponse<License>(response);
}
async refresh(usage: boolean = false, token?: CancellationToken): Promise<License> {
const response = await this.httpClient.post('licensing/refresh', null, usage ? {usage} : undefined, token);
return getTypedResponse<License>(response);
}
async activate(key: string, usage: boolean = false, token?: CancellationToken): Promise<License> {
const response = await this.httpClient.post('licensing/activate', {key}, usage ? {usage} : undefined, token);
return getTypedResponse<License>(response);
}
}
|
using System;
using System.Dynamic;
namespace AL.Data
{
public interface IDbContext : IDisposable
{
DbContextData Data { get; }
IDbContext IgnoreIfAutoMapFails(bool ignoreIfAutoMapFails);
IDbContext UseTransaction(bool useTransaction);
IDbContext UseSharedConnection(bool useSharedConnection);
IDbContext CommandTimeout(int timeout);
IDbCommand Sql(string sql, params object[] parameters);
IDbCommand MultiResultSql { get; }
ISelectBuilder<TEntity> Select<TEntity>(string sql);
IInsertBuilder Insert(string tableName);
IInsertBuilder<T> Insert<T>(string tableName, T item);
IInsertBuilderDynamic Insert(string tableName, ExpandoObject item);
IUpdateBuilder Update(string tableName);
IUpdateBuilder<T> Update<T>(string tableName, T item);
IUpdateBuilderDynamic Update(string tableName, ExpandoObject item);
IDeleteBuilder Delete(string tableName);
IDeleteBuilder<T> Delete<T>(string tableName, T item);
IStoredProcedureBuilder StoredProcedure(string storedProcedureName);
IStoredProcedureBuilder<T> StoredProcedure<T>(string storedProcedureName, T item);
IStoredProcedureBuilderDynamic StoredProcedure(string storedProcedureName, ExpandoObject item);
IDbContext EntityFactory(IEntityFactory entityFactory);
IDbContext ConnectionString(string connectionString, IDbProvider dbProvider);
IDbContext ConnectionStringName(string connectionstringName, IDbProvider dbProvider);
IDbContext IsolationLevel(IsolationLevel isolationLevel);
IDbContext Commit();
IDbContext Rollback();
IDbContext OnConnectionOpening(Action<ConnectionEventArgs> action);
IDbContext OnConnectionOpened(Action<ConnectionEventArgs> action);
IDbContext OnConnectionClosed(Action<ConnectionEventArgs> action);
IDbContext OnExecuting(Action<CommandEventArgs> action);
IDbContext OnExecuted(Action<CommandEventArgs> action);
IDbContext OnError(Action<ErrorEventArgs> action);
}
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* 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.
*/
import {map} from '../../src/core/util/map.js';
describe('map', () => {
it('should iterate over array and returns new array', () => {
const array = [1, 2, 3];
const iteratee = jasmine.createSpy('iteratee').and.callFake((a) => a + a);
const result = map(array, iteratee);
expect(result).toBeDefined();
expect(result).toEqual([2, 4, 6]);
expect(iteratee).toHaveBeenCalledWith(1, 0, array);
expect(iteratee).toHaveBeenCalledWith(2, 1, array);
expect(iteratee).toHaveBeenCalledWith(3, 2, array);
});
it('should iterate over array like object and returns new array', () => {
const arrayLike = {
'length': 3,
'0': 1,
'1': 2,
'2': 3,
};
const iteratee = jasmine.createSpy('iteratee').and.callFake((a) => a + a);
const result = map(arrayLike, iteratee);
expect(result).toBeDefined();
expect(result).toEqual([2, 4, 6]);
expect(iteratee).toHaveBeenCalledWith(1, 0, arrayLike);
expect(iteratee).toHaveBeenCalledWith(2, 1, arrayLike);
expect(iteratee).toHaveBeenCalledWith(3, 2, arrayLike);
});
});
|
//--------------------------------------------------------------------------------
// This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed
// under the MIT License, available in the root of this distribution and
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Jason Zink
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// TGrowableVertexBufferDX11
//
//--------------------------------------------------------------------------------
#ifndef TGrowableVertexBufferDX11_h
#define TGrowableVertexBufferDX11_h
//--------------------------------------------------------------------------------
#include "PipelineManagerDX11.h"
#include "TGrowableBufferDX11.h"
//--------------------------------------------------------------------------------
namespace Glyph3
{
template <class T>
class TGrowableVertexBufferDX11 : public TGrowableBufferDX11<T>
{
public:
TGrowableVertexBufferDX11();
virtual ~TGrowableVertexBufferDX11();
virtual void UploadData( PipelineManagerDX11* pPipeline );
virtual ResourcePtr GetBuffer();
protected:
virtual void CreateResource( unsigned int elements );
virtual void DeleteResource( );
private:
ResourcePtr m_VB;
};
#include "TGrowableVertexBufferDX11.inl"
};
//--------------------------------------------------------------------------------
#endif // TGrowableVertexBufferDX11_h
//--------------------------------------------------------------------------------
|
<?php
/*********************************************************************************
* FairnessTNA is a Workforce Management program forked from TimeTrex in 2013,
* copyright Aydan Coskun. Original code base is copyright TimeTrex Software Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact Aydan Coskun via issue tracker on github.com/aydancoskun
********************************************************************************/
/**
* @package PayrollDeduction\CA
*/
class PayrollDeduction_CA_NT extends PayrollDeduction_CA {
var $provincial_income_tax_rate_options = array(
20190101 => array(
array('income' => 43137, 'rate' => 5.9, 'constant' => 0),
array('income' => 86277, 'rate' => 8.6, 'constant' => 1165),
array('income' => 140267, 'rate' => 12.2, 'constant' => 4271),
array('income' => 140267, 'rate' => 14.05, 'constant' => 6866),
),
20180101 => array(
array('income' => 42209, 'rate' => 5.9, 'constant' => 0),
array('income' => 84420, 'rate' => 8.6, 'constant' => 1140),
array('income' => 137248, 'rate' => 12.2, 'constant' => 4179),
array('income' => 137248, 'rate' => 14.05, 'constant' => 6718),
),
20170101 => array(
array('income' => 41585, 'rate' => 5.9, 'constant' => 0),
array('income' => 83172, 'rate' => 8.6, 'constant' => 1123),
array('income' => 135219, 'rate' => 12.2, 'constant' => 4117),
array('income' => 135219, 'rate' => 14.05, 'constant' => 6619),
),
20160101 => array(
array('income' => 41011, 'rate' => 5.9, 'constant' => 0),
array('income' => 82024, 'rate' => 8.6, 'constant' => 1107),
array('income' => 133353, 'rate' => 12.2, 'constant' => 4060),
array('income' => 133353, 'rate' => 14.05, 'constant' => 6527),
),
20150101 => array(
array('income' => 40484, 'rate' => 5.9, 'constant' => 0),
array('income' => 80971, 'rate' => 8.6, 'constant' => 1093),
array('income' => 131641, 'rate' => 12.2, 'constant' => 4008),
array('income' => 131641, 'rate' => 14.05, 'constant' => 6443),
),
20140101 => array(
array('income' => 39808, 'rate' => 5.9, 'constant' => 0),
array('income' => 79618, 'rate' => 8.6, 'constant' => 1075),
array('income' => 129441, 'rate' => 12.2, 'constant' => 3941),
array('income' => 129441, 'rate' => 14.05, 'constant' => 6336),
),
20130101 => array(
array('income' => 39453, 'rate' => 5.9, 'constant' => 0),
array('income' => 78908, 'rate' => 8.6, 'constant' => 1065),
array('income' => 128286, 'rate' => 12.2, 'constant' => 3906),
array('income' => 128286, 'rate' => 14.05, 'constant' => 6279),
),
20120101 => array(
array('income' => 38679, 'rate' => 5.9, 'constant' => 0),
array('income' => 77360, 'rate' => 8.6, 'constant' => 1044),
array('income' => 125771, 'rate' => 12.2, 'constant' => 3829),
array('income' => 125771, 'rate' => 14.05, 'constant' => 6156),
),
20110101 => array(
array('income' => 37626, 'rate' => 5.9, 'constant' => 0),
array('income' => 75253, 'rate' => 8.6, 'constant' => 1016),
array('income' => 122345, 'rate' => 12.2, 'constant' => 3725),
array('income' => 122345, 'rate' => 14.05, 'constant' => 5988),
),
20100101 => array(
array('income' => 37106, 'rate' => 5.9, 'constant' => 0),
array('income' => 74214, 'rate' => 8.6, 'constant' => 1002),
array('income' => 120656, 'rate' => 12.2, 'constant' => 3674),
array('income' => 120656, 'rate' => 14.05, 'constant' => 5906),
),
20090101 => array(
array('income' => 36885, 'rate' => 5.9, 'constant' => 0),
array('income' => 73772, 'rate' => 8.6, 'constant' => 996),
array('income' => 119936, 'rate' => 12.2, 'constant' => 3652),
array('income' => 119936, 'rate' => 14.05, 'constant' => 5871),
),
20080101 => array(
array('income' => 35986, 'rate' => 5.90, 'constant' => 0),
array('income' => 71973, 'rate' => 8.60, 'constant' => 972),
array('income' => 117011, 'rate' => 12.20, 'constant' => 3563),
array('income' => 117011, 'rate' => 14.05, 'constant' => 5727),
),
20070101 => array(
array('income' => 35315, 'rate' => 5.90, 'constant' => 0),
array('income' => 70631, 'rate' => 8.60, 'constant' => 954),
array('income' => 114830, 'rate' => 12.20, 'constant' => 3496),
array('income' => 114830, 'rate' => 14.05, 'constant' => 5621),
),
);
}
?>
|
<?php declare(strict_types=1);
namespace App\Repository;
use Doctrine\DBAL\Connection as Db;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class TransactionRepository
{
public function __construct(
protected Db $db
)
{
}
public function get_count_for_user_id(int $user_id, string $schema):int
{
return $this->db->fetchOne('select count(*)
from ' . $schema . '.transactions
where id_to = ? or id_from = ?', [$user_id, $user_id]);
}
public function get(int $id, string $schema):array
{
$data = $this->db->fetchAssociative('select *
from ' . $schema . '.transactions
where id = ?', [$id]);
if (!$data)
{
throw new NotFoundHttpException(sprintf('Transaction %d does not exist in %s',
$id, __CLASS__));
}
return $data;
}
public function getNext(int $id, string $schema)
{
return $this->db->fetchOne('select id
from ' . $schema . '.transactions
where id > ?
order by id asc
limit 1', [$id]) ?? null;
}
public function getPrev(int $id, string $schema)
{
return $this->db->fetchOne('select id
from ' . $schema . '.transactions
where id < ?
order by id desc
limit 1', [$id]) ?? null;
}
public function updateDescription(int $id, string $description, string $schema)
{
$this->db->update($schema . '.transactions', ['description' => $description], ['id' => $id]);
}
}
|
# coding=utf-8
"""
Jenkins statistics reports generator
Run it in command line after adjust configuration on jenkins_statistics_config.py file
Generates a report in following format:
---------------------------------------------------------------------------------------
------------------------------- JOBS EXECUTADOS POR MÊS -------------------------------
---------------------------------------------------------------------------------------
01/2015 | 02/2015 | 03/2015 | 04/2015 | 05/2015 | 06/2015 | 07/2015 | 08/2015 | 09/2015
---------------------------------------------------------------------------------------
8 | 7 | 15 | 12 | 12 | 15 | 16 | 31 | 30
---------------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------- BUILDS EXECUTADOS POR MÊS --------------------------
-------------------------------------------------------------------------------
| Month/Year | None | ABORTED | FAILURE | SUCCESS | UNSTABLE |
-------------------------------------------------------------------------------
| 01/2015 | 0 | 0 | 12 | 7 | 10 |
-------------------------------------------------------------------------------
"""
import datetime
from jenkins_date_range_functions import get_months_array, get_starting_month
import jenkins_api_functions
import jenkins_statistics
import jenkins_statistics_config
def get_data_from_jenkins():
"""
Get job details from Jenkins server
:return: Job details, ``list(dict)``
"""
inicio = datetime.datetime.now()
print "start gettting data: ", inicio
dados = jenkins_api_functions.get_jobs_details(
jenkins_statistics_config.JENKINS_URL,
jenkins_statistics_config.JENKINS_USER,
jenkins_statistics_config.JENKINS_PASSWORD)
print u"finish getting data: ", inicio, datetime.datetime.now()
print u"elapsed time: {0}".format(datetime.datetime.now() - inicio)
return dados
def print_reports(jobs_details):
"""
Print reports: Jobs by month/year and Builds by month/year
:param jobs_details: Job details, ``list``
"""
date_range = get_months_array(get_starting_month(jenkins_statistics_config.NUMBER_OF_MONTHS_TO_GET_DATA,
jenkins_statistics_config.INCLUDE_ACTUAL_MONTH),
jenkins_statistics_config.NUMBER_OF_MONTHS_TO_GET_DATA)
print ""
summary_jobs_by_month(jobs_details, date_range)
print ""
summary_builds_by_month(jobs_details, date_range)
print ""
date_range.reverse()
for item in range(2):
print top_jobs(jobs_details, date_range[item][1], date_range[item][0])
print ""
def top_jobs(jobs_details, year, month):
"""
Print top jobs by year/month
:param jobs_details: Jobs
:param year: Year
:param month: Month
"""
titulo = u"| TOP JOBS BY BUILDS: {0} |".format(jenkins_statistics.get_formatted_month_year(month, year))
separador = u'{:-^' + str(len(titulo) + 40) + '}'
separador_detalhe = u'| {:^' + str(len(titulo) + 40 - 4) + '} |'
print separador.format('')
print titulo
print separador.format('')
tops = jenkins_statistics.top_jobs_by_builds(jobs_details, year, month)
for job in tops:
print separador_detalhe.format("{0}: {1}".format(job[1], job[0]))
print separador.format('')
def summary_jobs_by_month(jobs_details, date_range):
"""
Print report jobs by month
:param date_range: Date range to report
:param jobs_details: Jobs details, ``list``
"""
jobs_por_mes = jenkins_statistics.get_summary_jobs_by_month(jobs_details)
sorted_data = sorted(jobs_por_mes)
titulo = [item[0][0]
for item in sorted_data
if (item[0][1], item[0][2]) in date_range]
if len(titulo) == 0:
return
detalhe = ["{0:^7}".format(item[1])
for item in sorted_data
if (item[0][1], item[0][2]) in date_range]
separador = u'{:-^' + str(len(" | ".join(titulo))) + '}'
print separador.format('')
print separador.format(u" ACTIVE JOBS BY MONTH/YEAR (Active = at least one build) ")
print separador.format('')
print " | ".join(titulo)
print separador.format('')
print " | ".join(detalhe)
print separador.format('')
def summary_builds_by_month(jobs_details, date_range):
"""
Print report builds by month/year
:param year: Date Range to select data
:param jobs_details: Jobs details, ``list``
"""
builds_por_mes = jenkins_statistics.get_summary_builds_by_month(jobs_details)
selected_data = [item
for item in builds_por_mes
if (item[0][1], item[0][2]) in date_range]
resultado = []
for result in [item[1] for item in selected_data]:
resultado += [s[0] for s in result]
resultados_possiveis = sorted(list(set(resultado)))
print ""
titulo = u"| Month/Year | " + \
"".join(["{0:^10} | ".format(s) for s in resultados_possiveis])
separador = u'{:-^' + str(len(titulo)) + '}'
print separador.format('')
print separador.format(u" BUILDS BY MONTH ")
print separador.format('')
print titulo
print separador.format('')
for item in selected_data:
result = item[1]
mes_ano = item[0][0]
detalhe_mes_ano = "| {0:^13}| ".format(mes_ano)
for resultado in resultados_possiveis:
qtd_builds = sum([r[1] for r in result if r[0] == resultado])
detalhe_mes_ano += " {0:^9} | ".format(qtd_builds)
print detalhe_mes_ano
print separador.format('')
if __name__ == '__main__':
print_reports(get_data_from_jenkins())
|
# -*- coding: utf-8 -*-
#
# File: uwosh_ploneprojects.py
#
# Copyright (c) 2008 by []
# Generator: ArchGenXML Version 2.0
# http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# 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; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
__author__ = """unknown <unknown>"""
__docformat__ = 'plaintext'
# There are three ways to inject custom code here:
#
# - To set global configuration variables, create a file AppConfig.py.
# This will be imported in config.py, which in turn is imported in
# each generated class and in this file.
# - To perform custom initialisation after types have been registered,
# use the protected code section at the bottom of initialize().
import logging
logger = logging.getLogger('uwosh_ploneprojects')
logger.debug('Installing Product')
import os
import os.path
from Globals import package_home
import Products.CMFPlone.interfaces
from Products.Archetypes import listTypes
from Products.Archetypes.atapi import *
from Products.Archetypes.utils import capitalize
from Products.CMFCore import DirectoryView
from Products.CMFCore import permissions as cmfpermissions
from Products.CMFCore import utils as cmfutils
from Products.CMFPlone.utils import ToolInit
from config import *
DirectoryView.registerDirectory('skins', product_globals)
##code-section custom-init-head #fill in your manual code here
##/code-section custom-init-head
def initialize(context):
"""initialize product (called by zope)"""
##code-section custom-init-top #fill in your manual code here
##/code-section custom-init-top
# imports packages and types for registration
import content
# Initialize portal content
all_content_types, all_constructors, all_ftis = process_types(
listTypes(PROJECTNAME),
PROJECTNAME)
cmfutils.ContentInit(
PROJECTNAME + ' Content',
content_types = all_content_types,
permission = DEFAULT_ADD_CONTENT_PERMISSION,
extra_constructors = all_constructors,
fti = all_ftis,
).initialize(context)
# Give it some extra permissions to control them on a per class limit
for i in range(0,len(all_content_types)):
klassname=all_content_types[i].__name__
if not klassname in ADD_CONTENT_PERMISSIONS:
continue
context.registerClass(meta_type = all_ftis[i]['meta_type'],
constructors= (all_constructors[i],),
permission = ADD_CONTENT_PERMISSIONS[klassname])
##code-section custom-init-bottom #fill in your manual code here
##/code-section custom-init-bottom
|
import asyncio
import uuid
import pickle
from functools import partial
from .base import create_session_factory
from .cookie_session import SecureCookie, SessionBackendStore
__all__ = [
'RedisBackend',
'RedisSessionFactory',
]
_loads = partial(pickle.loads)
_dumps = partial(pickle.dumps, protocol=pickle.HIGHEST_PROTOCOL)
def RedisSessionFactory(redis_pool, secret_key, cookie_name, *,
loads=_loads, dumps=_dumps, key_prefix='session:',
session_max_age=None, loop=None, **kwargs):
cookie_store = SecureCookie(secret_key, cookie_name,
session_max_age=session_max_age,
**kwargs)
backend = RedisBackend(redis_pool, loads=loads, dumps=dumps,
session_max_age=session_max_age)
return create_session_factory(session_id_store=cookie_store,
backend_store=backend,
loop=loop)
class RedisBackend(SessionBackendStore):
"""Redis session store backend.
"""
def __init__(self, redis_pool, *, loads=_loads, dumps=_dumps,
key_prefix='session:', session_max_age=None):
self._redis_pool = redis_pool
self._loads = loads
self._dumps = dumps
self._key_prefix = key_prefix
self.session_max_age = session_max_age
@asyncio.coroutine
def load_session_data(self, cookie_value):
"""Loads session data pointed by sid stored in cookies.
"""
sid = cookie_value
key = self._make_key(sid)
with (yield from self._redis_pool) as redis:
packed = yield from redis.get(key)
if packed is not None:
try:
data = self._loads(packed)
except (TypeError, ValueError):
pass
else:
return data, sid
return None, None
@asyncio.coroutine
def save_session_data(self, session):
"""Saves session data in redis and returns sid.
"""
if session.new:
sid = self.new_sid()
else:
sid = session.identity
key = self._make_key(sid)
with (yield from self._redis_pool) as redis:
if not session and sid:
yield from redis.delete(key)
return None
data = self._dumps(dict(session))
if self.session_max_age is not None:
yield from redis.setex(key, self.session_max_age, data)
else:
yield from redis.set(key, data)
return sid
def new_sid(self):
"""Returns new sid.
"""
return uuid.uuid4().hex
def _make_key(self, sid):
return '{prefix}{sid}'.format(
prefix=self._key_prefix, sid=sid).encode('utf-8')
|
import weakref
import importlib
from numba import _dynfunc
class Environment(_dynfunc.Environment):
"""Stores globals and constant pyobjects for runtime.
It is often needed to convert b/w nopython objects and pyobjects.
"""
__slots__ = ('env_name', '__weakref__')
# A weak-value dictionary to store live environment with env_name as the
# key.
_memo = weakref.WeakValueDictionary()
@classmethod
def from_fndesc(cls, fndesc):
try:
# Avoid creating new Env
return cls._memo[fndesc.env_name]
except KeyError:
inst = cls(fndesc.lookup_globals())
inst.env_name = fndesc.env_name
cls._memo[fndesc.env_name] = inst
return inst
def can_cache(self):
is_dyn = '__name__' not in self.globals
return not is_dyn
def __reduce__(self):
return _rebuild_env, (
self.globals.get('__name__'),
self.consts,
self.env_name,
)
def __del__(self):
return
def __repr__(self):
return f"<Environment {self.env_name!r} >"
def _rebuild_env(modname, consts, env_name):
env = lookup_environment(env_name)
if env is not None:
return env
mod = importlib.import_module(modname)
env = Environment(mod.__dict__)
env.consts[:] = consts
env.env_name = env_name
# Cache loaded object
Environment._memo[env_name] = env
return env
def lookup_environment(env_name):
"""Returns the Environment object for the given name;
or None if not found
"""
return Environment._memo.get(env_name)
|
package com.ctrip.xpipe.redis.checker.healthcheck.actions.interaction.processor;
import com.ctrip.xpipe.exception.XpipeException;
/**
* @author chen.zhu
* <p>
* Sep 06, 2018
*/
public class HealthEventProcessorException extends XpipeException {
public HealthEventProcessorException(String message){
super(message);
}
public HealthEventProcessorException(String message, Throwable th) {
super(message, th);
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/plugin/plugin_create_instance_in_paint.h"
#include "base/logging.h"
#include "content/test/plugin/plugin_client.h"
namespace NPAPIClient {
CreateInstanceInPaintTest::CreateInstanceInPaintTest(
NPP id, NPNetscapeFuncs *host_functions)
: PluginTest(id, host_functions),
window_(NULL), created_(false) {
}
NPError CreateInstanceInPaintTest::SetWindow(NPWindow* pNPWindow) {
if (pNPWindow->window == NULL)
return NPERR_NO_ERROR;
if (test_id() == "1") {
if (!window_) {
static ATOM window_class = 0;
if (!window_class) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_DBLCLKS;
wcex.lpfnWndProc =
&NPAPIClient::CreateInstanceInPaintTest::WindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = GetModuleHandle(NULL);
wcex.hIcon = 0;
wcex.hCursor = 0;
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = L"CreateInstanceInPaintTestWindowClass";
wcex.hIconSm = 0;
window_class = RegisterClassEx(&wcex);
}
HWND parent = reinterpret_cast<HWND>(pNPWindow->window);
window_ = CreateWindowEx(
WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR,
MAKEINTATOM(window_class), 0,
WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE ,
0, 0, 100, 100, parent, 0, GetModuleHandle(NULL), 0);
DCHECK(window_);
// TODO: this property leaks.
::SetProp(window_, L"Plugin_Instance", this);
}
} else if (test_id() == "2") {
SignalTestCompleted();
} else {
NOTREACHED();
}
return NPERR_NO_ERROR;
}
LRESULT CALLBACK CreateInstanceInPaintTest::WindowProc(
HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
if (message == WM_PAINT) {
CreateInstanceInPaintTest* this_instance =
reinterpret_cast<CreateInstanceInPaintTest*>
(::GetProp(window, L"Plugin_Instance"));
if (this_instance->test_id() == "1" && !this_instance->created_) {
::RemoveProp(window, L"Plugin_Instance");
this_instance->created_ = true;
this_instance->HostFunctions()->geturlnotify(
this_instance->id(), "javascript:CreateNewInstance()", NULL,
reinterpret_cast<void*>(1));
}
}
return DefWindowProc(window, message, wparam, lparam);
}
} // namespace NPAPIClient
|
import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def location_type(self):
"""
Return location type for current result
"""
return self.current_data['geometry']['location_type']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
types = self.current_data['types']
return (types == [u'street_address'] or types == [u'premise'])
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
|
#
# Copyright (C) 2007-2011 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV 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.
#
# 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 NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""
Django ORM wrapper for the NAV logger database
"""
from django.db import models
from nav.models.fields import VarcharField
class LoggerCategory(models.Model):
"""
Model for the logger.category-table
"""
category = VarcharField(db_column='category', unique=True, primary_key=True)
def __unicode__(self):
return self.category
class Meta:
db_table = '"logger"."category"'
class Origin(models.Model):
"""
Model for the logger.origin-table
"""
origin = models.AutoField(db_column='origin', primary_key=True)
name = VarcharField(db_column='name')
category = models.ForeignKey(LoggerCategory, db_column='category')
def __unicode__(self):
return self.name
class Meta:
db_table = '"logger"."origin"'
class Priority(models.Model):
"""
Model for the logger.priority-table
"""
priority = models.AutoField(db_column='priority', primary_key=True)
keyword = VarcharField(db_column='keyword', unique=True)
description = VarcharField(db_column='description')
def __unicode__(self):
return self.keyword
class Meta:
db_table = '"logger"."priority"'
class LogMessageType(models.Model):
"""
Model for the logger.log_message_type-table
"""
type = models.AutoField(db_column='type', primary_key=True)
priority = models.ForeignKey(Priority, db_column='priority')
facility = VarcharField(db_column='facility')
mnemonic = VarcharField(db_column='mnemonic')
def __unicode__(self):
return u"{0}-{1}-{2}".format(
self.facility,
self.priority,
self.mnemonic
).upper()
class Meta:
db_table = '"logger"."log_message_type"'
unique_together = (('priority', 'facility', 'mnemonic'),)
class LogMessage(models.Model):
"""
Model for the logger.log_message-table
"""
id = models.AutoField(db_column='id', primary_key=True)
time = models.DateTimeField(db_column='time', auto_now=True)
origin = models.ForeignKey(Origin, db_column='origin')
newpriority = models.ForeignKey(Priority, db_column='newpriority')
type = models.ForeignKey(LogMessageType, db_column='type')
message = VarcharField(db_column='message')
class Meta:
db_table = '"logger"."log_message"'
class ErrorError(models.Model):
"""
Model for the logger.errorerror-table
"""
id = models.AutoField(db_column='id', primary_key=True)
message = VarcharField(db_column='message')
class Meta:
db_table = '"logger"."errorerror"'
class MessageView(models.Model):
"""
This is actually a class for a database-view 'message_view'.
Do not change attributes unless You know what You are doing!
Check: https://docs.djangoproject.com/en/dev/ref/models/options/
"""
origin = models.ForeignKey(Origin, db_column='origin', primary_key=True)
type = models.ForeignKey(LogMessageType, db_column='type')
newpriority = models.ForeignKey(Priority, db_column='newpriority')
category = models.ForeignKey(LoggerCategory, db_column='category')
time = models.DateTimeField(db_column='time')
class Meta:
db_table = '"logger"."message_view"'
# Models for database-views must set this option.
managed = False
|
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../globals.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../config/web.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function(yii\base\Event $event){
$event->sender->response->on(yii\web\Response::EVENT_BEFORE_SEND, function($e){
ob_start("ob_gzhandler");
});
$event->sender->response->on(yii\web\Response::EVENT_AFTER_SEND, function($e){
ob_end_flush();
});
});
$application->run();
|
import sys
import unittest
import re
import os.path
import warnings
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from Exscript.account import Account, AccountPool, AccountManager
class AccountManagerTest(unittest.TestCase):
CORRELATE = AccountManager
def setUp(self):
self.am = AccountManager()
self.data = {}
self.account = Account('user', 'test')
def testConstructor(self):
self.assertEqual(0, self.am.default_pool.n_accounts())
def testReset(self):
self.testAddAccount()
self.am.reset()
self.assertEqual(self.am.default_pool.n_accounts(), 0)
def testAddAccount(self):
self.assertEqual(0, self.am.default_pool.n_accounts())
account = Account('user', 'test')
self.am.add_account(account)
self.assertEqual(1, self.am.default_pool.n_accounts())
def testAddPool(self):
self.assertEqual(0, self.am.default_pool.n_accounts())
account = Account('user', 'test')
self.am.add_account(account)
self.assertEqual(1, self.am.default_pool.n_accounts())
def match_cb(host):
self.data['match-called'] = True
self.data['host'] = host
return True
# Replace the default pool.
pool1 = AccountPool()
self.am.add_pool(pool1)
self.assertEqual(self.am.default_pool, pool1)
# Add another pool, making sure that it does not replace
# the default pool.
pool2 = AccountPool()
pool2.add_account(self.account)
self.am.add_pool(pool2, match_cb)
self.assertEqual(self.am.default_pool, pool1)
def testGetAccountFromHash(self):
pool1 = AccountPool()
acc1 = Account('user1')
pool1.add_account(acc1)
self.am.add_pool(pool1)
acc2 = Account('user2')
self.am.add_account(acc2)
self.assertEqual(self.am.get_account_from_hash(acc1.__hash__()), acc1)
self.assertEqual(self.am.get_account_from_hash(acc2.__hash__()), acc2)
def testAcquireAccount(self):
account1 = Account('user1', 'test')
self.assertRaises(ValueError, self.am.acquire_account)
self.am.add_account(account1)
self.assertEqual(self.am.acquire_account(), account1)
account1.release()
account2 = Account('user2', 'test')
self.am.add_account(account2)
self.assertEqual(self.am.acquire_account(account2), account2)
account2.release()
account = self.am.acquire_account()
self.assertNotEqual(account, None)
account.release()
account3 = Account('user3', 'test')
pool = AccountPool()
pool.add_account(account3)
self.am.add_pool(pool)
self.assertEqual(self.am.acquire_account(account2), account2)
account2.release()
self.assertEqual(self.am.acquire_account(account3), account3)
account3.release()
account = self.am.acquire_account()
self.assertNotEqual(account, None)
account.release()
def testAcquireAccountFor(self):
self.testAddPool()
def start_cb(data, conn):
data['start-called'] = True
# Make sure that pool2 is chosen (because the match function
# returns True).
account = self.am.acquire_account_for('myhost')
account.release()
self.assertEqual(self.data, {'match-called': True, 'host': 'myhost'})
self.assertEqual(self.account, account)
def testReleaseAccounts(self):
account1 = Account('foo')
pool = AccountPool()
pool.add_account(account1)
pool.acquire_account(account1, 'one')
self.am.add_pool(pool, lambda x: None)
account2 = Account('bar')
self.am.add_account(account2)
self.am.acquire_account(account2, 'two')
self.assertNotIn(account1, pool.unlocked_accounts)
self.assertNotIn(account2, self.am.default_pool.unlocked_accounts)
self.am.release_accounts('two')
self.assertNotIn(account1, pool.unlocked_accounts)
self.assertIn(account2, self.am.default_pool.unlocked_accounts)
self.am.release_accounts('one')
self.assertIn(account1, pool.unlocked_accounts)
self.assertIn(account2, self.am.default_pool.unlocked_accounts)
def suite():
return unittest.TestLoader().loadTestsFromTestCase(AccountManagerTest)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
|
"""
====================================
Outlier detection on a real data set
====================================
This example illustrates the need for robust covariance estimation
on a real data set. It is useful both for outlier detection and for
a better understanding of the data structure.
We selected two sets of two variables from the boston housing data set
as an illustration of what kind of analysis can be done with several
outlier detection tools. For the purpose of vizualisation, we are working
with two-dimensional examples, but one should be aware that things are
not so trivial in high-dimension, as it will be pointed out.
In both examples below, the main result is that the empirical covariance
estimate, as a non-robust one, is highly influenced by the heterogeneous
structure of the observations. Although the robust covariance estimate is
able to focus on the main mode of the data distribution, it sticks to the
assumption that the data should be Gaussian distributed, yielding some biased
estimation of the data structure, but yet accurate to some extent.
The One-Class SVM algorithm
First example
-------------
The first example illustrates how robust covariance estimation can help
concentrating on a relevant cluster when another one exists. Here, many
observations are confounded into one and break down the empirical covariance
estimation.
Of course, some screening tools would have pointed out the presence of two
clusters (Support Vector Machines, Gaussian Mixture Models, univariate
outlier detection, ...). But had it been a high-dimensional example, none
of these could be applied that easily.
Second example
--------------
The second example shows the ability of the Minimum Covariance Determinant
robust estimator of covariance to concentrate on the main mode of the data
distribution: the location seems to be well estimated, although the covariance
is hard to estimate due to the banana-shaped distribution. Anyway, we can
get rid of some outlying observations.
The One-Class SVM is able to capture the real data structure, but the
difficulty is to adjust its kernel bandwith parameter so as to obtain
a good compromise between the shape of the data scatter matrix and the
risk of over-fitting the data.
"""
print __doc__
# Author: Virgile Fritsch <[email protected]>
# License: BSD
import numpy as np
from sklearn.covariance import EllipticEnvelop
from sklearn.svm import OneClassSVM
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn.datasets import load_boston
# Get data
X1 = load_boston()['data'][:, [8, 10]] # two clusters
X2 = load_boston()['data'][:, [5, 12]] # "banana"-shaped
# Define "classifiers" to be used
classifiers = {
"Empirical Covariance": EllipticEnvelop(support_fraction=1.,
contamination=0.261),
"Robust Covariance (Minimum Covariance Determinant)":
EllipticEnvelop(contamination=0.261),
"OCSVM": OneClassSVM(nu=0.261, gamma=0.05)}
colors = ['m', 'g', 'b']
legend1 = {}
legend2 = {}
# Learn a frontier for outlier detection with several classifiers
xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500))
xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500))
for i, (clf_name, clf) in enumerate(classifiers.iteritems()):
plt.figure(1)
clf.fit(X1)
Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()])
Z1 = Z1.reshape(xx1.shape)
legend1[clf_name] = plt.contour(
xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i])
plt.figure(2)
clf.fit(X2)
Z2 = clf.decision_function(np.c_[xx2.ravel(), yy2.ravel()])
Z2 = Z2.reshape(xx2.shape)
legend2[clf_name] = plt.contour(
xx2, yy2, Z2, levels=[0], linewidths=2, colors=colors[i])
# Plot the results (= shape of the data points cloud)
plt.figure(1) # two clusters
plt.title("Outlier detection on a real data set (boston housing)")
plt.scatter(X1[:, 0], X1[:, 1], color='black')
bbox_args = dict(boxstyle="round", fc="0.8")
arrow_args = dict(arrowstyle="->")
plt.annotate("several confounded points", xy=(24, 19),
xycoords="data", textcoords="data",
xytext=(13, 10), bbox=bbox_args, arrowprops=arrow_args)
plt.xlim((xx1.min(), xx1.max()))
plt.ylim((yy1.min(), yy1.max()))
plt.legend((legend1.values()[0].collections[0],
legend1.values()[1].collections[0],
legend1.values()[2].collections[0]),
(legend1.keys()[0], legend1.keys()[1], legend1.keys()[2]),
loc="upper center",
prop=matplotlib.font_manager.FontProperties(size=12))
plt.ylabel("accessibility to radial highways")
plt.xlabel("pupil-teatcher ratio by town")
plt.figure(2) # "banana" shape
plt.title("Outlier detection on a real data set (boston housing)")
plt.scatter(X2[:, 0], X2[:, 1], color='black')
plt.xlim((xx2.min(), xx2.max()))
plt.ylim((yy2.min(), yy2.max()))
plt.legend((legend2.values()[0].collections[0],
legend2.values()[1].collections[0],
legend2.values()[2].collections[0]),
(legend2.keys()[0], legend2.keys()[1], legend2.keys()[2]),
loc="upper center",
prop=matplotlib.font_manager.FontProperties(size=12))
plt.ylabel("% lower status of the population")
plt.xlabel("average number of rooms per dwelling")
plt.show()
|
'''sashwindow_tools.py - custom painting of sashwindows
This module takes over painting the sash window to make it a little more obvious
CellProfiler is distributed under the GNU General Public License.
See the accompanying file LICENSE for details.
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2015 Broad Institute
All rights reserved.
Please see the AUTHORS file for credits.
Website: http://www.cellprofiler.org
'''
import wx
from wx.aui import PyAuiDockArt
from cellprofiler.preferences import get_background_color
'''The size of the gripper the long way. This is about 5 dots worth.'''
GRIPPER_SIZE = 32
'''The size of the gripper the short way.'''
GRIPPER_HEIGHT = 8
def sw_bind_to_evt_paint(window):
'''Bind to wx.EVT_PAINT to take over the painting
window - a wx.SashWindow
'''
window.Bind(wx.EVT_PAINT, on_sashwindow_paint)
__art = None
__pane_info = None
def get_art_and_pane_info():
global __art
global __pane_info
if __art is None:
__art = PyAuiDockArt()
__pane_info = wx.aui.AuiPaneInfo()
__pane_info.Gripper(True)
return __art, __pane_info
def on_sashwindow_paint(event):
assert isinstance(event, wx.PaintEvent)
window = event.EventObject
assert isinstance(window, wx.SashWindow)
dc = wx.PaintDC(window)
dc.BeginDrawing()
dc.Background = wx.Brush(get_background_color())
dc.Clear()
art, pane_info = get_art_and_pane_info()
w, h = window.GetClientSizeTuple()
for edge, orientation in (
(wx.SASH_LEFT, wx.VERTICAL),
(wx.SASH_TOP, wx.HORIZONTAL),
(wx.SASH_RIGHT, wx.VERTICAL),
(wx.SASH_BOTTOM, wx.HORIZONTAL)):
if window.GetSashVisible(edge):
margin = window.GetEdgeMargin(edge)
if orientation == wx.VERTICAL:
sy = 0
sh = h
sw = margin
gw = GRIPPER_HEIGHT
gh = GRIPPER_SIZE
gy = (h - GRIPPER_SIZE) / 2
pane_info.GripperTop(False)
if edge == wx.SASH_LEFT:
gx = sx = 0
else:
sx = w - margin
gx = w - gw
else:
sx = 0
sw = w
sh = margin
gw = GRIPPER_SIZE
gh = GRIPPER_HEIGHT
gx = (w - GRIPPER_SIZE) / 2
pane_info.GripperTop(True)
if edge == wx.SASH_TOP:
gy = sy = 0
else:
sy = h - margin
gy = h - gh
art.DrawSash(dc, window, orientation, wx.Rect(sx, sy, sw, sh))
art.DrawGripper(dc, window, wx.Rect(gx, gy, gw, gh), pane_info)
dc.EndDrawing()
def sp_bind_to_evt_paint(window):
'''Take over painting the splitter of a splitter window'''
window.Bind(wx.EVT_PAINT, on_splitter_paint)
def on_splitter_paint(event):
assert isinstance(event, wx.PaintEvent)
window = event.EventObject
assert isinstance(window, wx.SplitterWindow)
dc = wx.PaintDC(window)
dc.BeginDrawing()
dc.Background = wx.Brush(get_background_color())
dc.Clear()
art, pane_info = get_art_and_pane_info()
w, h = window.GetClientSizeTuple()
margin = window.GetSashSize()
pos = window.GetSashPosition()
if window.GetSplitMode() == wx.SPLIT_VERTICAL:
pane_info.GripperTop(False)
sy = 0
sh = h
sw = margin
gw = GRIPPER_HEIGHT
sx = pos - margin/2
gx = pos - gw / 2
gy = (h - GRIPPER_SIZE) / 2
gh = GRIPPER_SIZE
orientation = wx.VERTICAL
else:
pane_info.GripperTop(True)
sx = 0
sw = h
sh = margin
gh = GRIPPER_HEIGHT
sy = pos - margin / 2
gx = (w - GRIPPER_SIZE) / 2
gy = pos - GRIPPER_SIZE / 2
gw = GRIPPER_SIZE
orientation = wx.HORIZONTAL
art.DrawSash(dc, window, orientation, wx.Rect(sx, sy, sw, sh))
art.DrawGripper(dc, window, wx.Rect(gx, gy, gw, gh), pane_info)
dc.EndDrawing()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# **************************************************************************
# Copyright © 2016 jianglin
# File Name: views.py
# Author: jianglin
# Email: [email protected]
# Created: 2016-12-15 22:08:06 (CST)
# Last Update: Thursday 2018-07-26 10:45:40 (CST)
# By:
# Description:
# **************************************************************************
from flask import redirect, render_template, request, url_for
from flask_login import current_user, login_required
from forums.api.forums.models import Board
from forums.api.tag.models import Tags
from forums.api.topic.models import Topic, Reply
from forums.api.collect.models import Collect
from forums.common.utils import gen_filter_dict, gen_order_by
from forums.common.views import BaseMethodView as MethodView
from .models import User
class UserListView(MethodView):
@login_required
def get(self):
query_dict = request.data
page, number = self.pageinfo
keys = ['username']
order_by = gen_order_by(query_dict, keys)
filter_dict = gen_filter_dict(query_dict, keys)
users = User.query.filter_by(
**filter_dict).order_by(*order_by).paginate(page, number, True)
return render_template('user/user_list.html', users=users)
class UserView(MethodView):
def get(self, username):
query_dict = request.data
user = User.query.filter_by(username=username).first_or_404()
page, number = self.pageinfo
keys = ['title']
order_by = gen_order_by(query_dict, keys)
filter_dict = gen_filter_dict(query_dict, keys)
filter_dict.update(author_id=user.id)
topics = Topic.query.filter_by(
**filter_dict).order_by(*order_by).paginate(page, number, True)
setting = user.setting
topic_is_allowed = False
if setting.topic_list == 1 or (setting.topic_list == 2 and
current_user.is_authenticated):
topic_is_allowed = True
if current_user.is_authenticated and current_user.id == user.id:
topic_is_allowed = True
data = {
'topics': topics,
'user': user,
'topic_is_allowed': topic_is_allowed
}
return render_template('user/user.html', **data)
class UserReplyListView(MethodView):
def get(self, username):
query_dict = request.data
user = User.query.filter_by(username=username).first_or_404()
page, number = self.pageinfo
keys = ['title']
order_by = gen_order_by(query_dict, keys)
filter_dict = gen_filter_dict(query_dict, keys)
filter_dict.update(author_id=user.id)
replies = Reply.query.filter_by(
**filter_dict).order_by(*order_by).paginate(page, number, True)
setting = user.setting
replies_is_allowed = False
if setting.rep_list == 1 or (current_user.is_authenticated and
setting.rep_list == 2):
replies_is_allowed = True
if current_user.is_authenticated and current_user.id == user.id:
replies_is_allowed = True
data = {
'replies': replies,
'user': user,
'replies_is_allowed': replies_is_allowed
}
return render_template('user/replies.html', **data)
class UserFollowerListView(MethodView):
@login_required
def get(self, username):
user = User.query.filter_by(username=username).first_or_404()
page, number = self.pageinfo
followers = user.followers.paginate(page, number, True)
data = {'followers': followers, 'user': user}
return render_template('user/followers.html', **data)
class UserFollowingListView(MethodView):
@login_required
def get(self, username):
return redirect(url_for('follow.topic'))
class UserCollectListView(MethodView):
def get(self, username):
return redirect(url_for('follow.collect'))
|
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 org.jboss.pnc.integration.client;
import com.jayway.restassured.response.Response;
import org.jboss.pnc.integration.client.util.RestResponse;
import org.jboss.pnc.rest.restmodel.BuildConfigurationSetRest;
public class BuildConfigurationSetRestClient extends AbstractRestClient<BuildConfigurationSetRest> {
public static final String BUILD_CONFIGURATION_SET_REST_ENDPOINT = "/pnc-rest/rest/build-configuration-sets/";
public BuildConfigurationSetRestClient() {
super(BUILD_CONFIGURATION_SET_REST_ENDPOINT, BuildConfigurationSetRest.class);
}
public RestResponse<BuildConfigurationSetRest> trigger(int id, boolean rebuildAll) {
Response response = request().when().queryParam("rebuildAll", rebuildAll).post(collectionUrl + id + "/build");
response.then().statusCode(200);
try {
return new RestResponse(response, null);
} catch (Exception e) {
throw new AssertionError("JSON unmarshalling error", e);
}
}
}
|
package au.edu.ersa.conveyer.util;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class Q <T> {
private BlockingQueue<T> q;
public Q(BlockingQueue<T> q) {
this.q = q;
}
public void put(T t) {
try {
q.put(t);
} catch (InterruptedException e) { throw new RuntimeException(e); }
}
public T get() {
try {
return q.take();
} catch (InterruptedException e) { throw new RuntimeException(e); }
}
public T get(int time, TimeUnit unit) {
try {
return q.poll(time, unit);
} catch (InterruptedException e) { throw new RuntimeException(e); }
}
}
|
#!/usr/bin/env python3.6
import sys
import os
import stat
import logging
import unittest
import tempfile
import time
from pathlib import Path
sys.path.append(str(Path('.').cwd().parent))
from swen import flowexecutor
logging.basicConfig(
format="%(asctime)s %(name)s %(levelname)s: %(message)s",
level=logging.DEBUG
)
class FlowTests(unittest.TestCase):
def setUp(self):
self.flow_dir = "flow"
def test_flow_0000(self):
flow_id = "flow_0000"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, None)
self.assertEqual(stdout, None)
self.assertEqual(stderr, None)
def test_flow_0001(self):
flow_id = "flow_0001"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0002(self):
flow_id = "flow_0002"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0003(self):
flow_id = "flow_0003"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0004(self):
flow_id = "flow_0004"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0005(self):
flow_id = "flow_0005"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0006(self):
flow_id = "flow_0006"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
def test_flow_0007(self):
flow_id = "flow_0007"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 10)
def test_flow_0008(self):
flow_id = "flow_0008"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
s = str(stdout, 'utf-8')
self.assertIn(".", s)
self.assertIn("..", s)
self.assertEqual(exit_code, 0)
def test_flow_0009(self):
flow_id = "flow_0009"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(str(stderr, 'utf-8'), '')
self.assertEqual(exit_code, 0)
def test_flow_0010(self):
flow_id = "flow_0010"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(str(stdout, 'utf-8'), '24\n')
self.assertEqual(exit_code, 0)
def test_flow_0011(self):
flow_id = "flow_0011"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(str(stdout, 'utf-8'), '/tmp\n')
self.assertEqual(exit_code, 0)
def test_flow_0012(self):
flow_id = "flow_0012"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(str(stdout, 'utf-8'), '4\n')
self.assertEqual(exit_code, 0)
def test_flow_0013(self):
flow_id = "flow_0013"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(str(stdout, 'utf-8'), '10\n')
self.assertEqual(exit_code, 0)
def test_flow_0014(self):
flow_id = "flow_0014"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 1)
def test_flow_0000_with_execution_graph(self):
flow_id = "flow_0000"
eg = self._call_flow_executor_execution_graph(flow_id)
self.assertEqual(eg, [])
def test_flow_0001_with_execution_graph(self):
flow_id = "flow_0001"
eg = self._call_flow_executor_execution_graph(flow_id)
self.assertEqual(len(eg), 1)
for s in [str(s) for s in eg]:
self.assertTrue("TERMINATED" in s)
def test_flow_0016_with_execution_graph(self):
flow_id = "flow_0016"
eg = self._call_flow_executor_execution_graph(flow_id)
self.assertEqual(len(eg), 2)
def test_flow_0017_with_var_substitution(self):
flow_id = "flow_0017"
(exit_code, stdout, stderr) = self._call_flow_executor(flow_id)
self.assertEqual(exit_code, 0)
self.assertEqual(str(stdout, "utf-8"), "hello world\n")
def _call_flow_executor(self, flow_id):
yml_path = self.flow_dir + "/" + "{}/{}.yml".format(flow_id, flow_id)
logging.info("Testing flow: id={!r}, yaml={!r}".format(flow_id, yml_path))
with open(yml_path) as yml:
fe = flowexecutor.FlowExecutor(yml)
return fe.execute()
def _call_flow_executor_execution_graph(self, flow_id):
yml_path = self.flow_dir + "/" + "{}/{}.yml".format(flow_id, flow_id)
logging.info("Testing flow: id={!r}, yaml={!r}".format(flow_id, yml_path))
with open(yml_path) as yml:
fe = flowexecutor.FlowExecutor(yml)
fe.execute()
return fe.execution_graph
if __name__ == '__main__':
unittest.main()
|
'use strict';
module.exports = {
db: 'mongodb://localhost/classified-test',
port: 3001,
app: {
title: 'classified - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
<?php
// src/Timesheet/Bundle/HrBundle/Form/Type/FPRUserAllocationType.php
namespace Timesheet\Bundle\HrBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FPRUserAllocationType extends AbstractType
{
private $fpreaders;
private $fpreaderNames;
private $readerUsers;
private $localId;
private $actionUrl;
private $fpuser = array();
public function __construct($fpreaders, $readerUsers, $fpuser, $fpreaderNames, $localId, $actionUrl)
{
$this->fpreaders = $fpreaders;
$this->fpreaderNames = $fpreaderNames;
$this->readerUsers = $readerUsers;
if (isset($fpuser) && is_array($fpuser) && count($fpuser)) {
foreach ($fpuser as $fpu) {
$this->fpuser[$fpu['id']]=$fpu['readerUserId'];
}
}
$this->localId = $localId;
$this->actionUrl = $actionUrl;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('localId', 'hidden', array(
'data'=>$this->localId
))
->add('submit', 'submit', array(
'label'=>'Save',
'attr'=>array('class'=>'submitButton')
));
if (isset($this->fpreaders) && is_array($this->fpreaders) && count($this->fpreaders)) {
foreach ($this->fpreaders as $fpr) {
$builder
->add('user'.$fpr['id'], 'choice', array(
'choices'=>((isset($this->readerUsers[$fpr['id']]))?($this->readerUsers[$fpr['id']]):(array())),
'label'=>'User at '.((isset($this->fpreaderNames[$fpr['id']]))?($this->fpreaderNames[$fpr['id']]):('reader '.$fpr['id'])),
'required'=>false,
'empty_value'=>' - Please select - ',
'data'=>((isset($this->fpuser[$fpr['id']]))?($this->fpuser[$fpr['id']]):(null))
));
}
}
if ($this->actionUrl) {
$builder->setAction($this->actionUrl);
}
}
public function getName()
{
return 'fpruserallocation';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
}
}
|
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> #
# Copyright 2013 AKFish <[email protected]> #
# Copyright 2013 Vincent Jacques <[email protected]> #
# Copyright 2014 Vincent Jacques <[email protected]> #
# Copyright 2016 Jannis Gebauer <[email protected]> #
# Copyright 2016 Peter Buckley <[email protected]> #
# Copyright 2018 Wan Liuyang <[email protected]> #
# Copyright 2018 sfdye <[email protected]> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub 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. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import github.GithubObject
import github.Repository
import github.NamedUser
class PullRequestPart(github.GithubObject.NonCompletableGithubObject):
"""
This class represents PullRequestParts
"""
def __repr__(self):
return self.get__repr__({"sha": self._sha.value})
@property
def label(self):
"""
:type: string
"""
return self._label.value
@property
def ref(self):
"""
:type: string
"""
return self._ref.value
@property
def repo(self):
"""
:type: :class:`github.Repository.Repository`
"""
return self._repo.value
@property
def sha(self):
"""
:type: string
"""
return self._sha.value
@property
def user(self):
"""
:type: :class:`github.NamedUser.NamedUser`
"""
return self._user.value
def _initAttributes(self):
self._label = github.GithubObject.NotSet
self._ref = github.GithubObject.NotSet
self._repo = github.GithubObject.NotSet
self._sha = github.GithubObject.NotSet
self._user = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "label" in attributes: # pragma no branch
self._label = self._makeStringAttribute(attributes["label"])
if "ref" in attributes: # pragma no branch
self._ref = self._makeStringAttribute(attributes["ref"])
if "repo" in attributes: # pragma no branch
self._repo = self._makeClassAttribute(github.Repository.Repository, attributes["repo"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CardWarsBatka")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CardWarsBatka")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b132b0fa-8d45-47a1-ae6e-13aa4c0e0e38")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/location/LocationService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/location/model/BatchUpdateDevicePositionError.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace LocationService
{
namespace Model
{
class AWS_LOCATIONSERVICE_API BatchUpdateDevicePositionResult
{
public:
BatchUpdateDevicePositionResult();
BatchUpdateDevicePositionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
BatchUpdateDevicePositionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline const Aws::Vector<BatchUpdateDevicePositionError>& GetErrors() const{ return m_errors; }
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline void SetErrors(const Aws::Vector<BatchUpdateDevicePositionError>& value) { m_errors = value; }
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline void SetErrors(Aws::Vector<BatchUpdateDevicePositionError>&& value) { m_errors = std::move(value); }
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline BatchUpdateDevicePositionResult& WithErrors(const Aws::Vector<BatchUpdateDevicePositionError>& value) { SetErrors(value); return *this;}
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline BatchUpdateDevicePositionResult& WithErrors(Aws::Vector<BatchUpdateDevicePositionError>&& value) { SetErrors(std::move(value)); return *this;}
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline BatchUpdateDevicePositionResult& AddErrors(const BatchUpdateDevicePositionError& value) { m_errors.push_back(value); return *this; }
/**
* <p>Contains error details for each device that failed to update its
* position.</p>
*/
inline BatchUpdateDevicePositionResult& AddErrors(BatchUpdateDevicePositionError&& value) { m_errors.push_back(std::move(value)); return *this; }
private:
Aws::Vector<BatchUpdateDevicePositionError> m_errors;
};
} // namespace Model
} // namespace LocationService
} // namespace Aws
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.