text
string
/* * Parsing of numeric literals (E5 Sections 7.8.3, B.1.1). */ /*--- { "skip": true } ---*/ /* * Optional octal syntax, E5 Section B.1.1. */ /*=== 1036956 ===*/ try { print(03751234); } catch (e) { print(e.name); } /* FIXME: test 088, 099 */ /*=== 1 true ===*/ /* Fraction period not necessarily followed by decimals. */ try { print(1.); print(1. === 1); } catch (e) { print(e.name); }
# kennitala.py - functions for handling Icelandic identity codes # coding: utf-8 # # Copyright (C) 2015 Tuomas Toivonen # Copyright (C) 2015 Arthur de Jong # # 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 """Kennitala (Icelandic personal and organisation identity code). Module for handling Icelandic personal and organisation identity codes (kennitala). >>> validate('450401-3150') # organisation '4504013150' >>> validate('120174-3399') # individual '1201743399' >>> validate('530575-0299') Traceback (most recent call last): ... InvalidChecksum: ... >>> validate('320174-3399') Traceback (most recent call last): ... InvalidComponent: ... >>> format('1201743399') '120174-3399' """ import re import datetime from stdnum.exceptions import * from stdnum.util import clean # Icelandic personal and organisation identity codes are composed of # date part, a dash, two random digits, a checksum, and a century # indicator where '9' for 1900-1999 and '0' for 2000 and beyond. For # organisations instead of birth date, the registration date is used, # and number 4 is added to the first digit. _kennitala_re = re.compile( r'^(?P<day>[01234567]\d)(?P<month>[01]\d)(?P<year>\d\d)' r'(?P<random>\d\d)(?P<control>\d)' r'(?P<century>[09])$') def compact(number): """Convert the kennitala to the minimal representation. This strips surrounding whitespace and separation dash, and converts it to upper case.""" return clean(number, '-').upper().strip() def checksum(number): """Calculate the checksum.""" weights = (3, 2, 7, 6, 5, 4, 3, 2, 1, 0) return sum(weights[i] * int(n) for i, n in enumerate(number)) % 11 def validate(number): """Checks to see if the number provided is a valid kennitala. It checks the format, whether a valid date is given and whether the check digit is correct.""" number = compact(number) match = _kennitala_re.search(number) if not match: raise InvalidFormat() day = int(match.group('day')) month = int(match.group('month')) year = int(match.group('year')) if match.group('century') == '9': year += 1900 else: year += 2000 # check if birth date or registration data is valid try: if day >= 40: # organisation datetime.date(year, month, day - 40) else: # individual datetime.date(year, month, day) except ValueError: raise InvalidComponent() # validate the checksum if checksum(number) != 0: raise InvalidChecksum() return number def is_valid(number): """Checks to see if the number provided is a valid HETU. It checks the format, whether a valid date is given and whether the check digit is correct.""" try: return bool(validate(number)) except ValidationError: return False def format(number): """Reformat the passed number to the standard format.""" number = compact(number) return number[:6] + '-' + number[6:]
# # 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; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Authors: # Caner Candan <caner@candan.fr>, http://caner.candan.fr # import numpy as np from numpy import * class Base: def __init__(self, size): self.size = size def __call__(self, ind): pass class Zerofy(Base): """Set all the bits of the solution to false. >>> ind = Individual() >>> init = Zerofy(10) >>> init(ind) >>> ind [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] """ def __init__(self, size): Base.__init__(self, size) def __call__(self, ind): ind += [0] * self.size class Defined(Base): """Set a defined number of bits to true and the rest to false. >>> ind = Individual() >>> init = Defined(10,5) >>> init(ind) >>> ind [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] """ def __init__(self, size, defined_size): Base.__init__(self, size) self.defined_size = defined_size def __call__(self, ind): ind += [0] * (self.size-self.defined_size) + [1] * self.defined_size class Random(Base): """Set all the bits of solution to a random value. >>> random.seed(0) >>> ind = Individual() >>> init = Random(10) >>> init(ind) >>> ind [0, 1, 1, 0, 1, 1, 1, 1, 1, 1] """ def __init__(self, size): Base.__init__(self, size) def __call__(self, ind): ind += random.choice(2,size=self.size) if __name__ == "__main__": import doctest doctest.testmod()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `SIGFPE` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, SIGFPE"> <title>libc::consts::os::posix88::SIGFPE - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>consts</a>::<wbr><a href='../index.html'>os</a>::<wbr><a href='index.html'>posix88</a></p><script>window.sidebarCurrent = {name: 'SIGFPE', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>consts</a>::<wbr><a href='../index.html'>os</a>::<wbr><a href='index.html'>posix88</a>::<wbr><a class='constant' href=''>SIGFPE</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-509' class='srclink' href='../../../../src/libc/lib.rs.html#3010' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const SIGFPE: <a class='type' href='../../../../libc/types/os/arch/c95/type.c_int.html' title='libc::types::os::arch::c95::c_int'>c_int</a><code> = </code><code>8</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../../"; window.currentCrate = "libc"; window.playgroundUrl = "https://play.rust-lang.org/"; </script> <script src="../../../../jquery.js"></script> <script src="../../../../main.js"></script> <script src="../../../../playpen.js"></script> <script async src="../../../../search-index.js"></script> </body> </html>
""" Python tests for the Survey models """ from collections import OrderedDict from django.contrib.auth.models import User from django.test.client import Client from survey.models import SurveyForm from survey.utils import is_survey_required_for_course, is_survey_required_and_unanswered from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory class SurveyModelsTests(ModuleStoreTestCase): """ All tests for the utils.py file """ def setUp(self): """ Set up the test data used in the specific tests """ super(SurveyModelsTests, self).setUp() self.client = Client() # Create two accounts self.password = 'abc' self.student = User.objects.create_user('student', 'student@test.com', self.password) self.student2 = User.objects.create_user('student2', 'student2@test.com', self.password) self.staff = User.objects.create_user('staff', 'staff@test.com', self.password) self.staff.is_staff = True self.staff.save() self.test_survey_name = 'TestSurvey' self.test_form = '<input name="foo"></input>' self.student_answers = OrderedDict({ 'field1': 'value1', 'field2': 'value2', }) self.student2_answers = OrderedDict({ 'field1': 'value3' }) self.course = CourseFactory.create( course_survey_required=True, course_survey_name=self.test_survey_name ) self.survey = SurveyForm.create(self.test_survey_name, self.test_form) def test_is_survey_required_for_course(self): """ Assert the a requried course survey is when both the flags is set and a survey name is set on the course descriptor """ self.assertTrue(is_survey_required_for_course(self.course)) def test_is_survey_not_required_for_course(self): """ Assert that if various data is not available or if the survey is not found then the survey is not considered required """ course = CourseFactory.create() self.assertFalse(is_survey_required_for_course(course)) course = CourseFactory.create( course_survey_required=False ) self.assertFalse(is_survey_required_for_course(course)) course = CourseFactory.create( course_survey_required=True, course_survey_name="NonExisting" ) self.assertFalse(is_survey_required_for_course(course)) course = CourseFactory.create( course_survey_required=False, course_survey_name=self.test_survey_name ) self.assertFalse(is_survey_required_for_course(course)) def test_user_not_yet_answered_required_survey(self): """ Assert that a new course which has a required survey but user has not answered it yet """ self.assertTrue(is_survey_required_and_unanswered(self.student, self.course)) temp_course = CourseFactory.create( course_survey_required=False ) self.assertFalse(is_survey_required_and_unanswered(self.student, temp_course)) temp_course = CourseFactory.create( course_survey_required=True, course_survey_name="NonExisting" ) self.assertFalse(is_survey_required_and_unanswered(self.student, temp_course)) def test_user_has_answered_required_survey(self): """ Assert that a new course which has a required survey and user has answers for it """ self.survey.save_user_answers(self.student, self.student_answers, None) self.assertFalse(is_survey_required_and_unanswered(self.student, self.course)) def test_staff_must_answer_survey(self): """ Assert that someone with staff level permissions does not have to answer the survey """ self.assertFalse(is_survey_required_and_unanswered(self.staff, self.course))
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ WebJournal widget - display photos from given collections """ from invenio.bibformat_engine import BibFormatObject from invenio.search_engine import perform_request_search from invenio.config import CFG_CERN_SITE, CFG_SITE_URL, CFG_SITE_RECORD def format_element(bfo, collections, max_photos="3", separator="<br/>"): """ Display the latest pictures from the given collection(s) @param collections: comma-separated list of collection form which photos have to be fetched @param max_photos: maximum number of photos to display @param separator: separator between photos """ try: int_max_photos = int(max_photos) except: int_max_photos = 0 try: collections_list = [coll.strip() for coll in collections.split(',')] except: collections_list = [] out = get_widget_html(bfo.lang, int_max_photos, collections_list, separator, bfo.lang) return out def escape_values(bfo): """ Called by BibFormat in order to check if output of this element should be escaped. """ return 0 def get_widget_html(language, max_photos, collections, separator, ln): """ Returns the content of the widget """ latest_photo_ids = perform_request_search(c=collections, rg=max_photos, of='id') images_urls = [] for recid in latest_photo_ids[:max_photos]: try: photo_record = BibFormatObject(recid) except: # todo: Exception, no photo in this selection continue if language == "fr": try: title = photo_record.fields('246_1a', escape=1)[0] except KeyError: try: title = photo_record.fields('245__a', escape=1)[0] except: title = "" else: try: title = photo_record.fields('245__a', escape=1)[0] except KeyError: # todo: exception, picture with no title title = "" if CFG_CERN_SITE and photo_record.fields('8567_'): # Get from 8567_ dfs_images = photo_record.fields('8567_') for image_block in dfs_images: if image_block.get("y", '') == "Icon": if image_block.get("u", '').startswith("http://"): images_urls.append((recid, image_block["u"], title)) break # Just one image per record else: # Get from 8564_ images = photo_record.fields('8564_') for image_block in images: if image_block.get("x", '').lower() == "icon": if image_block.get("q", '').startswith("http://"): images_urls.append((recid, image_block["q"], title)) break # Just one image per record # Build output html_out = separator.join(['<a href="%s/%s/%i?ln=%s"><img class="phr" width="100" height="67" src="%s"/>%s</a>' % (CFG_SITE_URL, CFG_SITE_RECORD, recid, ln, photo_url, title) for (recid, photo_url, title) in images_urls]) return html_out
const express = require('express'); const app = express(); const Router = require('express').Router; const path = require('path'); const ejs = require('ejs'); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); app.use("/styles", express.static(__dirname + '/css')); app.use("/scripts", express.static(__dirname + '/js')); app.use("/lib", express.static(__dirname + '/lib')); app.use("/plugin", express.static(__dirname + '/plugin')); app.use("/chartjs", express.static(__dirname + '/chartjs')); // require('./settings')(app); require('./models')(app); require('./actions')(app); require('./routes')(app); console.log(`server listening on port 1337`); app.listen(1337);
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "NSView.h" @interface IDEDebugGaugeReportContentBackground : NSView { BOOL _hasBottomBorder; } @property BOOL hasBottomBorder; // @synthesize hasBottomBorder=_hasBottomBorder; - (void)drawRect:(struct CGRect)arg1; - (id)initWithCoder:(id)arg1; - (id)initWithFrame:(struct CGRect)arg1; - (void)_dvt_commonInit; @end
<?php /** * Kunena Component * @package Kunena.Administrator.Template * @subpackage Users * * @copyright (C) 2008 - 2016 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined ( '_JEXEC' ) or die (); /** @var KunenaAdminViewUser $this */ ?> <div id="kunena" class="admin override"> <div id="j-sidebar-container" class="span2"> <div id="sidebar"> <div class="sidebar-nav"><?php include KPATH_ADMIN.'/template/joomla30/common/menu.php'; ?></div> </div> </div> <div id="j-main-container" class="span10"> <form action="<?php echo KunenaRoute::_('administrator/index.php?option=com_kunena') ?>" method="post" id="adminForm" name="adminForm"> <input type="hidden" name="view" value="users" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="1" /> <?php echo JHtml::_( 'form.token' ); ?> <fieldset> <legend><?php echo JText::_('COM_KUNENA_A_MOVE_USERMESSAGES'); ?></legend> <table class="table table-striped"> <thead> <tr> <th width="25%">Ttitle</th> <th width="25%">Opiton</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td> <?php echo JText::_('COM_KUNENA_CATEGORY_TARGET'); ?> </td> <td> <?php echo $this->catslist; ?> </td> <td> <strong><?php echo JText::_('COM_KUNENA_MOVEUSERMESSAGES_USERS_CURRENT'); ?></strong> <ol> <?php foreach($this->users as $user) { echo '<li>'.$this->escape($user->username).' ('.JText::_('COM_KUNENA_TRASH_AUTHOR_USERID').' '.$this->escape($user->id).')</li> '; } ?> </ol> </td> </tr> </tbody> </table> </fieldset> </form> </div> <div class="pull-right small"> <?php echo KunenaVersion::getLongVersionHTML(); ?> </div> </div>
function f(n: any) { return null; } function g<A, B>(x: any) { return null; } interface A { } interface B { } var A, B; f(g<A, B>(7)); f(g < A, B > 7); // Should error f(g < A, B > +(7)); // Should error
/* tslint:disable */ import { ConcreteFragment } from "relay-runtime"; import { ArtistRow_artist$ref } from "./ArtistRow_artist.graphql"; import { Dropdown_aggregation$ref } from "./Dropdown_aggregation.graphql"; import { TotalCount_filter_artworks$ref } from "./TotalCount_filter_artworks.graphql"; export type ArtworkAggregation = "COLOR" | "DIMENSION_RANGE" | "FOLLOWED_ARTISTS" | "GALLERY" | "INSTITUTION" | "MAJOR_PERIOD" | "MEDIUM" | "MERCHANDISABLE_ARTISTS" | "PARTNER_CITY" | "PERIOD" | "PRICE_RANGE" | "TOTAL" | "%future added value"; declare const _Artists_gene$ref: unique symbol; export type Artists_gene$ref = typeof _Artists_gene$ref; export type Artists_gene = { readonly __id: string; readonly artists: ({ readonly pageInfo: { readonly hasNextPage: boolean; }; readonly edges: ReadonlyArray<({ readonly node: ({ readonly __id: string; readonly " $fragmentRefs": ArtistRow_artist$ref; }) | null; }) | null> | null; }) | null; readonly filter_aggregations: ({ readonly aggregations: ReadonlyArray<({ readonly slice: ArtworkAggregation | null; readonly " $fragmentRefs": Dropdown_aggregation$ref; }) | null> | null; readonly " $fragmentRefs": TotalCount_filter_artworks$ref; }) | null; readonly " $refType": Artists_gene$ref; }; const node: ConcreteFragment = (function(){ var v0 = { "kind": "ScalarField", "alias": null, "name": "__id", "args": null, "storageKey": null }; return { "kind": "Fragment", "name": "Artists_gene", "type": "Gene", "metadata": { "connection": [ { "count": "count", "cursor": "cursor", "direction": "forward", "path": [ "artists" ] } ] }, "argumentDefinitions": [ { "kind": "LocalArgument", "name": "aggregations", "type": "[ArtworkAggregation]", "defaultValue": [ "MEDIUM", "TOTAL", "PRICE_RANGE", "DIMENSION_RANGE" ] }, { "kind": "LocalArgument", "name": "count", "type": "Int", "defaultValue": 10 }, { "kind": "LocalArgument", "name": "cursor", "type": "String", "defaultValue": "" } ], "selections": [ v0, { "kind": "LinkedField", "alias": "artists", "name": "__Artists_artists_connection", "storageKey": null, "args": null, "concreteType": "ArtistConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "pageInfo", "storageKey": null, "args": null, "concreteType": "PageInfo", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "hasNextPage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endCursor", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "ArtistEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Artist", "plural": false, "selections": [ v0, { "kind": "FragmentSpread", "name": "ArtistRow_artist", "args": null }, { "kind": "ScalarField", "alias": null, "name": "__typename", "args": null, "storageKey": null } ] }, { "kind": "ScalarField", "alias": null, "name": "cursor", "args": null, "storageKey": null } ] } ] }, { "kind": "LinkedField", "alias": "filter_aggregations", "name": "filtered_artworks", "storageKey": null, "args": [ { "kind": "Variable", "name": "aggregations", "variableName": "aggregations", "type": "[ArtworkAggregation]" }, { "kind": "Literal", "name": "include_medium_filter_in_aggregation", "value": true, "type": "Boolean" }, { "kind": "Literal", "name": "size", "value": 0, "type": "Int" } ], "concreteType": "FilterArtworks", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "TotalCount_filter_artworks", "args": null }, { "kind": "LinkedField", "alias": null, "name": "aggregations", "storageKey": null, "args": null, "concreteType": "ArtworksAggregationResults", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "slice", "args": null, "storageKey": null }, { "kind": "FragmentSpread", "name": "Dropdown_aggregation", "args": null } ] }, v0 ] } ] }; })(); (node as any).hash = 'c21a21d79040bd329707d9e8f2d6f805'; export default node;
/* $Header: /cvsup/minix/src/lib/ack/libp/rcka.c,v 1.1 2005/10/10 15:27:47 beng Exp $ */ /* * (c) copyright 1990 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ /* Author: Hans van Eck */ #include <em_abs.h> extern _trp(); struct array_descr { int lbound; unsigned n_elts_min_one; unsigned size; /* doesn't really matter */ }; _rcka(descr, index) struct array_descr *descr; { if( index < descr->lbound || index > (int) descr->n_elts_min_one + descr->lbound ) _trp(EARRAY); }
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\RIFF; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Cropped extends AbstractTag { protected $Id = 'ICRP'; protected $Name = 'Cropped'; protected $FullName = 'RIFF::Info'; protected $GroupName = 'RIFF'; protected $g0 = 'RIFF'; protected $g1 = 'RIFF'; protected $g2 = 'Audio'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Cropped'; }
/* Copyright (C) 2015 Panagiotis Roubatsis 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. */ #include "CubeData.h" #include <fstream> #include <vector> #include <cstdlib> #include <sstream> #include <bitset> #include <regex> std::vector<int> getFrameIterations(std::ifstream& file){ std::vector<int> frames; while(!file.eof()){ std::string line; getline(file, line); //Get the number between the drawBuffer(int) to get the 'iterations' value if(std::regex_search(line.begin(), line.end(), std::tr1::regex("drawBuffer\\(\\d.+\\)"))){ std::string iterStr = line.substr(line.find("(") + 1, line.find(")") - line.find("(") - 1); frames.push_back(atoi(iterStr.c_str())); } } file.clear(); file.seekg(0, std::ios::beg); return frames; } std::vector<std::string> tokenizeByDelimiter(std::string in, char delim){ std::vector<std::string> tokens; std::stringstream ss(in); std::string token; while(!ss.eof()){ getline(ss, token, delim); tokens.push_back(token); } return tokens; } unsigned short htoi(std::string sHex){ std::stringstream ss; sHex = sHex.substr(2, sHex.length() - 2); //Remove 0x from the front ss << std::hex << sHex; unsigned short x; ss >> x; return x; } std::vector<CubeFrame> getFrames(std::ifstream& file){ std::vector<CubeFrame> frames; std::vector<int> iter = getFrameIterations(file); std::string line; while(line != "word frameBuffers[][4] = {") getline(file, line); getline(file, line); int frameIndex = 0; do{ line = line.substr(1, line.find("}") - 1); std::vector<std::string> strHexNums = tokenizeByDelimiter(line, ','); std::vector<unsigned short> nums; for(size_t i = 0; i < strHexNums.size(); i++) nums.push_back(htoi(strHexNums[i])); CubeFrame frame; for(size_t i = 0; i < nums.size(); i++){ std::bitset<16> b(nums[i]); for(size_t j = b.size() - 1; j > 0; j--) frame.states.push_back(b[j] ? C_LED_ON : C_LED_OFF); frame.states.push_back(b[0] ? C_LED_ON : C_LED_OFF); } frame.duration = iter[frameIndex]; frames.push_back(frame); frameIndex++; getline(file, line); }while(line != "};"); file.clear(); file.seekg(0, std::ios::beg); return frames; } std::string removeQuotesFromPath(std::string filePath){ if(filePath.length() == 0) return ""; if(filePath[0] != '\"') return filePath[0] + removeQuotesFromPath(filePath.substr(1, filePath.length() - 1)); else return removeQuotesFromPath(filePath.substr(1, filePath.length() - 1)); } //Function defined in CubeData.h void importCubeFromArduino444Source(CubeData* data, std::string filePath){ std::ifstream file(removeQuotesFromPath(filePath)); data->_frames = getFrames(file); data->_ledCube->load(data->_frames[0].states); data->_currentFrame = 0; file.close(); }
# -*- coding: utf-8 -*- import logging import scrapy from items import UrlItem class CategorySpider(scrapy.Spider): name = "category" allowed_domains = ["aliexpress.com"] start_urls = ( 'http://www.aliexpress.com/', ) prefix = '' base_url = '' def __init__(self, reducer): self.reducer = reducer def start_requests(self): CategorySpider.prefix = self.settings['prefix'] CategorySpider.base_url = self.settings['base_url'] yield self.request_page() def request_page(self, page=1): url = CategorySpider.base_url if '.html' in url: # 按类别进行搜索 url = url[:url.index('.html')] + '/{}'.format(page) + url[url.index('.html'):] else: # 按关键词进行搜索 url = '{}&page={}'.format(url, page) self.log('request url: {}'.format(url), logging.INFO) return scrapy.Request(url=url, meta={'page': page}, callback=self.parse) def parse(self, response): list_items = [item.css('a.product').xpath('@href').extract() + item.css('a.rate-num').xpath('text()').extract() + item.css('a.order-num-a').xpath('em/text()').extract() for item in response.css('li.list-item')] self.log('request page: {}, crawl product: {}'.format(response.url, len(list_items)), logging.INFO) for href, rate, order in ( (list_item[0][:list_item[0].index('?')], int(list_item[1][list_item[1].index('(') + 1:list_item[1].index(')')]), float(list_item[2][list_item[2].index('(') + 1:list_item[2].index(')')])) for list_item in list_items if len(list_item) == 3): if self.reducer(rate, order): item = UrlItem() item['prefix'] = CategorySpider.prefix item['type'] = 'product' item['url'] = href yield item if len(list_items) > 0: yield self.request_page(int(response.meta['page']) + 1) else: self.log('category spider finish, base url: {}'.format(self.base_url), logging.INFO)
#pragma once #if XRGAME_EXPORTS | XRSE_FACTORY_EXPORTS #define _memcpy std::memcpy #define _memset std::memset #define _strlen xr_strlen #else #define _memcpy memcpy #define _memset memset #define _strlen strlen #endif class CMailSlotMsg { char m_buff[2048]; DWORD m_len; int m_pos; inline void Read(void* dst, int sz) { _memcpy(dst, (void*)(&m_buff[0] + m_pos), sz); m_pos += sz; }; inline void Write(const void* src, int sz) { _memcpy((void*)(&m_buff[0] + m_pos), src, sz); m_pos += sz; m_len = m_pos; }; public: CMailSlotMsg() { Reset(); }; inline void Reset() { m_len = 0; m_pos = 0; _memset(m_buff, 0, 2048); }; inline void SetBuffer(const char* b, int sz) { Reset(); _memcpy(m_buff, b, sz); m_len = sz; m_pos = 0; }; inline void* GetBuffer() { return m_buff; }; inline void SetLen(DWORD l) { m_len = l; }; inline DWORD GetLen() const { return m_len; }; inline BOOL r_string(char* dst) { int sz; r_int(sz); Read(dst, sz + 1); return TRUE; }; inline BOOL w_string(const char* dst) { size_t sz = _strlen(dst); w_int((int)sz); Write(dst, (int)(sz + 1)); return TRUE; }; inline BOOL r_float(float& dst) { Read(&dst, sizeof(float)); return TRUE; }; inline BOOL w_float(const float src) { Write(&src, sizeof(float)); return TRUE; }; inline BOOL r_int(int& dst) { Read(&dst, sizeof(int)); return TRUE; }; inline BOOL w_int(const int src) { Write(&src, sizeof(int)); return TRUE; }; inline BOOL r_buff(void* dst, int sz) { Read(dst, sz); return TRUE; }; inline BOOL w_buff(void* src, int sz) { Write(src, sz); return TRUE; }; }; inline HANDLE CreateMailSlotByName(const char* slotName) { HANDLE hSlot = CreateMailslot(slotName, 0, // no maximum message size MAILSLOT_WAIT_FOREVER, // no time-out for operations (LPSECURITY_ATTRIBUTES)NULL); // no security attributes return hSlot; } inline BOOL CheckExisting(const char* slotName) { HANDLE hFile; BOOL res; hFile = CreateFile(slotName, GENERIC_WRITE, FILE_SHARE_READ, // required to write to a mailslot (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); res = (hFile != INVALID_HANDLE_VALUE); if (res) CloseHandle(hFile); return res; } inline BOOL SendMailslotMessage(const char* slotName, CMailSlotMsg& msg) { BOOL fResult; HANDLE hFile; DWORD cbWritten; hFile = CreateFile(slotName, GENERIC_WRITE, FILE_SHARE_READ, // required to write to a mailslot (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); R_ASSERT(hFile != INVALID_HANDLE_VALUE); if (hFile == INVALID_HANDLE_VALUE) return false; fResult = WriteFile(hFile, msg.GetBuffer(), msg.GetLen(), &cbWritten, (LPOVERLAPPED)NULL); R_ASSERT(fResult); fResult = CloseHandle(hFile); R_ASSERT(fResult); return fResult; } inline BOOL CheckMailslotMessage(HANDLE hSlot, CMailSlotMsg& msg) { DWORD cbMessage, cMessage, cbRead; BOOL fResult; HANDLE hEvent; OVERLAPPED ov; cbMessage = cMessage = cbRead = 0; hEvent = CreateEvent(NULL, FALSE, FALSE, "__Slot"); if (NULL == hEvent) return FALSE; ov.Offset = 0; ov.OffsetHigh = 0; ov.hEvent = hEvent; fResult = GetMailslotInfo(hSlot, // mailslot handle (LPDWORD)NULL, // no maximum message size &cbMessage, // size of next message &cMessage, // number of messages (LPDWORD)NULL); // no read time-out R_ASSERT(fResult); if (!fResult || cbMessage == MAILSLOT_NO_MESSAGE) { CloseHandle(hEvent); return false; } msg.Reset(); fResult = ReadFile(hSlot, msg.GetBuffer(), cbMessage, &cbRead, &ov); msg.SetLen(cbRead); R_ASSERT(fResult); CloseHandle(hEvent); return fResult; }
var OWF = OWF || {}; OWF.Events = { Widget: { BEFORE_LAUNCH: 'beforeWidgetLaunch', AFTER_LAUNCH: 'afterWidgetLaunch' }, Dashboard: { COMPLETE_RENDER: 'dashboardCompleteRender', CHANGED: 'dashboardChanged' }, Banner: { DOCKED: 'docked', UNDOCKED: 'undocked' } };
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework.Content; namespace Ed.Contentious.Xna { /// <summary> /// An adapter to the XnaContentContext for supporting the XNA content /// pipeline. Modifies the standard ContentContext calls to provide sane /// inputs to ContentManager. Make sure to read the IntelliSense docs for /// details. /// </summary> /// <remarks> /// Patching together Contentious and XNA is kind of boilerplate-y, but /// very doable. Since you've already defined all your ContentParsers, you /// already have the guts of the importer/processor logic already done. /// </remarks> public class XnaContentContext : ContentContext { protected readonly ContentManager XNAContent; protected readonly IServiceProvider Services; protected readonly Dictionary<Type, Dictionary<String, IDisposable>> IdempotentLookupTable = new Dictionary<Type, Dictionary<String, IDisposable>>(); /// <summary> /// Constructor. Internally constructs the XNA ContentManager. /// </summary> /// <param name="rootDirectory"> /// The value for ContentManager.RootDirectory. Usually but not always /// "Content". /// </param> /// <param name="services"> /// The services container for your game. Usually accessible via the /// Services member of your Game class. /// </param> public XnaContentContext(String rootDirectory, IServiceProvider services) : base(null) { Services = services; XNAContent = new ContentManager(services, rootDirectory); } protected XnaContentContext(XnaContentContext parent) : base(parent) { Services = parent.Services; XNAContent = new ContentManager(parent.Services, parent.XNAContent.RootDirectory); } /// <summary> /// Creates a child context. This method works as it does in a desktop /// environment. /// </summary> /// <returns>The new child context.</returns> protected override ContentContext CreateChildContextReal() { return new XnaContentContext(this); } protected override bool IsLoaded<TLoadType>(string key) { Type t = typeof(TLoadType); ContentInfo info = GetInfo(t); if (info.Idempotent == false) { throw new InvalidOperationException("IsLoaded<T> fails because " + t + " is not idempotent."); } String fullPath = BuildPath(info, key); Dictionary<String, IDisposable> table; if (IdempotentLookupTable.TryGetValue(t, out table) == false) { return false; } return table.ContainsKey(fullPath); } protected override TLoadType LoadInContext<TLoadType>(String key) { Type t = typeof (TLoadType); ContentInfo info = GetInfo(t); String fullPath = BuildPath(info, key); TLoadType obj; if (info.Idempotent) { Boolean checkLookupTable = true; Dictionary<String, IDisposable> table; if (IdempotentLookupTable.TryGetValue(t, out table) == false) { table = new Dictionary<String, IDisposable>(); IdempotentLookupTable.Add(t, table); checkLookupTable = false; } IDisposable o; if (checkLookupTable == false || table.TryGetValue(fullPath, out o) == false) { obj = XNAContent.Load<TLoadType>(fullPath); table.Add(fullPath, obj); } else { obj = (TLoadType)o; } } else // not idempotent objects { obj = XNAContent.Load<TLoadType>(fullPath); } return obj; } protected override void DisposeContext() { XNAContent.Dispose(); } protected String BuildPath(ContentInfo info, String key) { String p = (info.SubRoot != null) ? Path.Combine(info.SubRoot, key) : key; // because XNA's developers made the A+ decision to chop off // file extensions when adding content. That doesn't screw with // everyone else ever, right guys? return Path.Combine(Path.GetDirectoryName(p), Path.GetFileName(p)); } } }
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2013 Vindeka, LLC. # # 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 from swiftly.client import Client from swiftly.concurrency import Concurrency from gate.common.utils import get_logger class SwiftTransport(object): name = 'swift' def __init__(self, conf): self.conf = conf self.logger = get_logger(conf, log_route='transport.memcached') self.auth_url = conf.get('auth_url', 'http://localhost:5000/') self.auth_user = conf.get('auth_user', 'gate') self.auth_key = conf.get('auth_key', 'gate') self.proxy = conf.get('proxy', 'None') if self.proxy == 'None': self.proxy = None self.retries = int(conf.get('retries', '4')) self.swift_proxy = conf.get('swift_proxy', 'None') if self.swift_proxy == 'None': self.swift_proxy = None self.cache_path = conf.get('cache_path', '/var/gate/object-store/cache') dir_path = os.path.dirname(os.path.abspath(cache_path)) if not os.path.exists(dir_path): os.makedirs(dir_path) self.concurrency = int(conf.get('put_threads', 5)) self.segment_size = int(conf.get('segment_size', 262144000)) def open(self): self.client = Client( auth_url, auth_user, auth_key, proxy=proxy, retries=retries, swift_proxy=swift_proxy, cache_path=cache_path, ) try: (status, reason, headers, contents) = \ __swiftly_client.head_account() except: self.logger.error('Connection failed: connection refused.') return False if status != 200: self.logger.error('Connection failed: (%d) %s' % (status, reason)) return False self.logger.debug('Connection made to swift.') return True def close(self): self.client.close() self.logger.debug('Connection closed.') def get_stream(self, key): (container, obj) = key.split('/', limit=1) return self.client.get_object(container, obj, stream=True) def put_stream(self, key, stream): (container, obj) = key.split('/', limit=1) size = None func_size = getattr(stream, 'size', None) if func_size: size = func_size() if not size: return self.client.client.put_object(container, obj, stream) if size <= self.segment_size: headers = {'Content-Length': size} (status, reason, headers, contents) = \ self.client.put_object(container, obj, stream, headers=headers) if status != 201: self.logger.error('Failed to put object: %s/%s' % (container, obj)) return False cont_prefix = '%s_segments' % container prefix = '%s/%s/' % (obj, self.segment_size) conc = Concurrency(self.concurrency) start = 0 segment = 0 while start < size: obj_path = '%s%08d' % (prefix, segment) conc.spawn( segment, self._put_recursive, cont_prefix, obj_path, stream.copy(), start, ) for rv in conc.get_results().values(): if not rv: conc.join() self.logger.error('Failed to create segments for object: %s/%s' % (container, obj)) return rv segment += 1 start += self.client.segment_size conc.join() for rv in conc.get_results().values(): if not rv: conc.join() self.logger.error('Failed to create segments for object: %s/%s' % (container, obj)) return rv headers = {'Content-Length': 0, 'X-Object-Manifest': '%s/%s' \ % (cont_prefix, prefix)} (status, reason, headers, contents) = \ self.client.put_object(container, obj, '', headers=headers) if status != 201: self.logger.error('Failed put manifest object: %s/%s' % (container, obj)) return False return True def _put_recursive( container, obj, stream, offset, size, ): stream.seek(offset) headers = {'Content-Length': size} try: (status, reason, headers, contents) = \ self.client.put_object(container, obj, stream, headers=headers) if status != 201: return False except: return False return True def transport_factory(conf): """Returns a transport for use with gate.""" return SwiftTransport(conf)
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model frontend\models\News */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'News'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="news-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'author_id', 'preview', 'news:ntext', 'created_at', 'updated_at', ], ]) ?> </div>
package com.prometheus; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @EnableCircuitBreaker @EnableDiscoveryClient @SpringBootApplication @EnableHystrixDashboard public class AuthApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(AuthApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(AuthApplication.class, args); } }
#include "ex1.h" const float defaultRadius = 10; const float XRange = 1000; Sphere::Sphere() { set(&center.location, (myRandom() - 0.5)*XRange, 0.0, 0.0); center.speed.x = (myRandom() - 0.5)*5; center.speed.y = (myRandom() + 0.5)*7.5; center.speed.z = (myRandom() - 0.5)*5; set(&center.acceleration, 0, 0-GRAVITY_POWER, 0); radius = (myRandom() + 0.5)*defaultRadius; center.ttl = int((myRandom() + 0.5)*SPHERE_TTL); number_of_particles = int((myRandom() + 0.5)*SPHERE_PARTICLES); set(&(center.color), myRandom(), myRandom(), myRandom()); } void Sphere::move() { center.move(); } list<Particle *> Sphere::explode() { list<Particle *> toReturn; for(int i=0;i<number_of_particles;i++) toReturn.push_back(new Particle(this)); return toReturn; }
<?php namespace libs\framework; class DB { private $link; public function __construct($config) { $this->link = new \mysqli($config['DB_HOST'], $config['USERNAME'], $config['PSW'], $config['DBNAME']); if ($this->link->connect_error) { trigger_error('Error: Could not make a database link (' . $this->link->connect_errno . ') ' . $this->link->connect_error); } $this->link->set_charset("utf8"); /* set autocommit to off */ $this->link->autocommit(true); } public function query($sql){ $query = $this->link->query($sql); if(!$this->link->errno){ if($query instanceof \mysqli_result ){ $result = array(); while ($row = $query->fetch_assoc()){ $result[] = $row; } /* free result set */ $query->close(); return $result; }else{ return true; } }else{ trigger_error('Error: ' . $this->link->error . '<br />Error No: ' . $this->link->errno . '<br />' . $sql); } } public function getLastId() { return $this->link->insert_id; } public function __destruct(){ $this->link->close(); } }
import numpy as np import yaipopt def test_hs071(): x_bounds = (np.ones(4), np.repeat(5.0, 4)) constr_bounds = ([25, 40], [np.inf, 40]) obj = lambda x, new_x: x[0]*x[3]*(x[0] + x[1] + x[2]) + x[2] obj_grad = lambda x, new_x: [x[0]*x[3] + x[3]*(x[0] + x[1] + x[2]), x[0]*x[3], x[0]*x[3] + 1.0, x[0]*(x[0] + x[1] + x[2])] constr = lambda x, new_x: [x[0]*x[1]*x[2]*x[3], x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3]] constr_jac_inds = ([0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 3, 0, 1, 2, 3]) hess_inds = ([0, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]) constr_jac = lambda x, new_x: [x[1]*x[2]*x[3], x[0]*x[2]*x[3], x[0]*x[1]*x[3], x[0]*x[1]*x[2], 2.0*x[0], 2.0*x[1], 2.0*x[2], 2.0*x[3]] hess = lambda x, new_x, obj_factor, lmult, new_lmult: [ obj_factor*2*x[3] + lmult[1]*2, obj_factor*x[3] + lmult[0]*(x[2]*x[3]), lmult[1]*2, obj_factor*(x[3]) + lmult[0]*(x[1]*x[3]), lmult[0]*(x[0]*x[3]), lmult[1]*2, obj_factor*(2*x[0] + x[1] + x[2]) + lmult[0]*x[1]*x[2], obj_factor*x[0] + lmult[0]*x[0]*x[2], obj_factor*x[0] + lmult[0]*x[0]*x[1], lmult[1]*2] problem = yaipopt.Problem(x_bounds, obj, obj_grad, constr_bounds, constr, constr_jac, constr_jac_inds, hess, hess_inds) x0 = [1.0, 5.0, 5.0, 1.0] xopt, info = problem.solve(x0) expected_xopt = [1, 4.743, 3.82115, 1.379408] np.testing.assert_almost_equal(xopt, expected_xopt, decimal=6)
<?php class HTMLPurifier_ChildDef_RequiredTest extends HTMLPurifier_ChildDefHarness { public function testPrepareString() { $def = new HTMLPurifier_ChildDef_Required('foobar | bang |gizmo'); $this->assertIdentical( $def->elements, array( 'foobar' => true , 'bang' => true , 'gizmo' => true ) ); } public function testPrepareArray() { $def = new HTMLPurifier_ChildDef_Required(array('href', 'src')); $this->assertIdentical( $def->elements, array( 'href' => true , 'src' => true ) ); } public function setUp() { parent::setUp(); $this->obj = new HTMLPurifier_ChildDef_Required('dt | dd'); } public function testEmptyInput() { $this->assertResult('', false); } public function testRemoveIllegalTagsAndElements() { $this->assertResult( '<dt>Term</dt>Text in an illegal location' . '<dd>Definition</dd><b>Illegal tag</b>', '<dt>Term</dt><dd>Definition</dd>' ); $this->assertResult('How do you do!', false); } public function testIgnoreWhitespace() { // whitespace shouldn't trigger it $this->assertResult("\n<dd>Definition</dd> "); } public function testPreserveWhitespaceAfterRemoval() { $this->assertResult( '<dd>Definition</dd> <b></b> ', '<dd>Definition</dd> ' ); } public function testDeleteNodeIfOnlyWhitespace() { $this->assertResult("\t ", false); } public function testPCDATAAllowed() { $this->obj = new HTMLPurifier_ChildDef_Required('#PCDATA | b'); $this->assertResult('Out <b>Bold text</b><img />', 'Out <b>Bold text</b>'); } public function testPCDATAAllowedJump() { $this->obj = new HTMLPurifier_ChildDef_Required('#PCDATA | b'); $this->assertResult('A <i>foo</i>', 'A foo'); } } // vim: et sw=4 sts=4
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ /* * Copyright (c) 2008, 2010, 2011 Ciaran McCreesh * * This file is part of the Paludis package manager. Paludis 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. * * Paludis 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., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ #include <paludis/repositories/e/metadata_xml.hh> #include <paludis/repositories/e/xml_things_handle.hh> #include <paludis/util/pimp-impl.hh> #include <paludis/util/singleton-impl.hh> #include <paludis/util/map-impl.hh> #include <paludis/util/mutex.hh> #include <paludis/util/hashes.hh> #include <paludis/util/log.hh> #include <paludis/util/fs_path.hh> #include <paludis/util/fs_stat.hh> #include <paludis/literal_metadata_key.hh> #include <paludis/choice.hh> #include <unordered_map> using namespace paludis; using namespace paludis::erepository; typedef std::unordered_map<FSPath, std::shared_ptr<MetadataXML>, Hash<FSPath> > Store; namespace paludis { template <> struct Imp<MetadataXMLPool> { mutable Mutex mutex; mutable Store store; }; } MetadataXMLPool::MetadataXMLPool() : _imp() { } MetadataXMLPool::~MetadataXMLPool() { } const std::shared_ptr<const MetadataXML> MetadataXMLPool::metadata_if_exists(const FSPath & f) const { Context context("When handling metadata.xml file '" + stringify(f) + "':"); FSPath f_real(f.realpath_if_exists()); Lock lock(_imp->mutex); Store::const_iterator i(_imp->store.find(f_real)); if (i != _imp->store.end()) return i->second; else { std::shared_ptr<MetadataXML> metadata_xml; if (f_real.stat().is_regular_file_or_symlink_to_regular_file()) { try { if (XMLThingsHandle::get_instance()->create_metadata_xml_from_xml_file()) metadata_xml = XMLThingsHandle::get_instance()->create_metadata_xml_from_xml_file()(f); } catch (const Exception & e) { Log::get_instance()->message("e.metadata_xml.bad", ll_warning, lc_context) << "Got exception '" << e.message() << "' (" << e.what() << "), ignoring metadata.xml file '" << f_real << "'"; } } return _imp->store.insert(std::make_pair(f_real, metadata_xml)).first->second; } } namespace paludis { template class Map<ChoiceNameWithPrefix, std::string>; template class Pimp<MetadataXMLPool>; template class Singleton<MetadataXMLPool>; }
"""Tests for scripts/ivars.py.""" import re import unittest from test_utils import import_utils import_utils.prepare_lldb_import_or_exit() import lldb import_utils.prepare_for_scripts_imports() from scripts import ivars class IvarsTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(IvarsTest, self).__init__(*args, **kwargs) self.debugger = None self.target = None def tearDown(self): if self.debugger and self.target: self.debugger.DeleteTarget(self.target) def testIvars(self): """Tests the expected output of the |ivars <object>| command.""" self.debugger = lldb.SBDebugger.Create() self.debugger.SetAsync(False) self.target = self.debugger.CreateTarget('') error = lldb.SBError() process = self.target.AttachToProcessWithName(self.debugger.GetListener(), 'TestApp', False, error) if not process: self.assertTrue(False, 'Could not attach to process "TestApp"') self.debugger.SetSelectedTarget(self.target) result = lldb.SBCommandReturnObject() # First get the AppDelegate object, whose ivars we will use to test # the command. # # The output is in the format |<AppDelegate: 0x7fd704401810>|. self.debugger.GetCommandInterpreter().HandleCommand( 'po [[UIApplication sharedApplication] delegate]', result) self.assertTrue(result.Succeeded()) output = result.GetOutput() start_index = output.find('0x') self.assertTrue(start_index != -1) end_index = output.find('>') self.assertTrue(end_index != -1) delegate = output[start_index:end_index] ivars.ivars(self.debugger, delegate, result, None) self.assertTrue(result.Succeeded()) expected_output_regex = ( r'<__NSArrayM 0x\w{12}>\(\n' r'\(NSString \*\) _test -> 0x\w{9},\n' r'\(int\) _x,\n' r'\(int\*\*\) _ptr,\n' r'\(int\[5\]\) _y,\n' r'\(id const \*\) _temp,\n' r'\(id\) _something -> nil,\n' r'\(struct DummyStruct\[4\]\) _t,\n' r'\(struct DummyStruct\*\) _example,\n' r'\(union DummyUnion\) _someUnion,\n' r'\(~block~\) _myBlock -> 0x\w{9},\n' r'\(~block~\) _myBlockEmpty -> nil,\n' r'\(~function pointer~\) _myPointer,\n' r'\(UIWindow \*\) _window -> 0x\w{12}\n' r'\)' ) self.assertTrue(re.search(expected_output_regex, result.GetOutput(), re.M))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_45) on Fri Aug 28 09:51:32 EDT 2015 --> <title>Uses of Class org.apache.cassandra.io.util.ChecksummedRandomAccessReader.CorruptFileException (apache-cassandra API)</title> <meta name="date" content="2015-08-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.cassandra.io.util.ChecksummedRandomAccessReader.CorruptFileException (apache-cassandra API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/io/util/ChecksummedRandomAccessReader.CorruptFileException.html" title="class in org.apache.cassandra.io.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/io/util/class-use/ChecksummedRandomAccessReader.CorruptFileException.html" target="_top">Frames</a></li> <li><a href="ChecksummedRandomAccessReader.CorruptFileException.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.cassandra.io.util.ChecksummedRandomAccessReader.CorruptFileException" class="title">Uses of Class<br>org.apache.cassandra.io.util.ChecksummedRandomAccessReader.CorruptFileException</h2> </div> <div class="classUseContainer">No usage of org.apache.cassandra.io.util.ChecksummedRandomAccessReader.CorruptFileException</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/io/util/ChecksummedRandomAccessReader.CorruptFileException.html" title="class in org.apache.cassandra.io.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/io/util/class-use/ChecksummedRandomAccessReader.CorruptFileException.html" target="_top">Frames</a></li> <li><a href="ChecksummedRandomAccessReader.CorruptFileException.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2015 The Apache Software Foundation</small></p> </body> </html>
'use strict' import axios from 'axios' export function load () { return axios.get('/home/api/load') .then(response => response.data) } export function save (data) { return axios.post('/home/api/update', data) .then(response => response.data) }
<?php wp_reset_query(); $args = array( 'post_type' => 'testimonial' ); if( !is_null( $items ) ) $args['posts_per_page'] = $items; $tests = new WP_Query( $args ); $html = ''; if( !$tests->have_posts() ) return $html; //loop $html = ''; while( $tests->have_posts() ) : $tests->the_post(); $title = the_title( '<span class="title">', '</span>', false ); $label = yit_get_post_meta( get_the_ID(), '_site-label' ); $siteurl = yit_get_post_meta( get_the_ID(), '_site-url' ); $website = ''; if ($siteurl != ''): if ($label != ''): $website = '<a href="' . esc_url($siteurl) . '">' . $label . '</a>'; else: $website = '<a href="' . esc_url($siteurl) . '">' . $siteurl . '</a>'; endif; endif; //$website = '';// "<a href=\"" . esc_url( yit_get_post_meta( get_the_ID(), '_site-url' ) ) . "\">$website</a>"; $html .= '<div class="testimonials-list group">'; $html .= ' <div class="thumb-testimonial group">'; $html .= ' ' . get_the_post_thumbnail( null, 'thumb-testimonial' ); $html .= ' <div class="shadow-thumb"></div>'; $html .= ' <p class="name-testimonial group">' . $title . '<span class="website">' . $website . '</span></p>'; $html .= ' </div>'; $content = wpautop( get_the_content() ); $html .= ' <div class="the-post group">'; $html .= ' ' . $content; $html .= ' </div>'; $html .= '</div>'; endwhile; wp_reset_query(); ?> <?php echo $html; ?>
#!/usr/bin/env python # -*- coding: utf-8 -*- # Please note that the function 'make_request' is provided for your reference only. # You will not be able to to actually use it from within the Udacity web UI # All your changes should be in the 'extract_data' function from bs4 import BeautifulSoup import requests import json html_page = "page_source.html" def extract_data(page): data = {"eventvalidation": "", "viewstate": ""} with open(page, "r") as html: soup = BeautifulSoup(html) _eventValid = soup.find(id="__EVENTVALIDATION") data["eventvalidation"]=_eventValid["value"] _viewState = soup.find(id="__VIEWSTATE") data["viewstate"]=_viewState["value"] return data def make_request(data): eventvalidation = data["eventvalidation"] viewstate = data["viewstate"] r = requests.post("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2", data={'AirportList': "BOS", 'CarrierList': "VX", 'Submit': 'Submit', "__EVENTTARGET": "", "__EVENTARGUMENT": "", "__EVENTVALIDATION": eventvalidation, "__VIEWSTATE": viewstate }) return r.text def test(): data = extract_data(html_page) assert data["eventvalidation"] != "" assert data["eventvalidation"].startswith("/wEWjAkCoIj1ng0") assert data["viewstate"].startswith("/wEPDwUKLTI") test()
using System; using System.IO; using System.Text; namespace AldursLab.WurmApi.FileSystem { static class TransactionalFileOps { private const string FileExtensionNew = ".new"; private const string FileExtensionOld = ".old"; /// <summary> /// Empty string if nothing found. /// </summary> public static string ReadFileContents(string absolutePath) { if (!File.Exists(absolutePath)) { if (File.Exists(absolutePath + FileExtensionOld)) { File.Move(absolutePath + FileExtensionOld, absolutePath); } else if (File.Exists(absolutePath + FileExtensionNew)) { File.Move(absolutePath + FileExtensionNew, absolutePath); } else { return string.Empty; } } using (FileStream fileStream = File.OpenRead(absolutePath)) { using (var sr = new StreamReader(fileStream)) { return sr.ReadToEnd(); } } } public static void SaveFileContents(string absolutePath, string newContents) { var dir = Path.GetDirectoryName(absolutePath); if (dir == null) { throw new InvalidOperationException("Path.GetDirectoryName(absolutePath) returned null for filepath: " + absolutePath); } if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (File.Exists(absolutePath + FileExtensionNew)) { File.Delete(absolutePath + FileExtensionNew); } if (File.Exists(absolutePath + FileExtensionOld)) { File.Delete(absolutePath + FileExtensionOld); } using ( var fs = new FileStream(absolutePath + FileExtensionNew, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { using (var sw = new StreamWriter(fs, Encoding.UTF8)) { sw.Write(newContents); // forcing hard flushing to avoid incomplete physical file write, which can cause corruption on system crash fs.Flush(true); } } if (File.Exists(absolutePath)) { File.Move(absolutePath, absolutePath + FileExtensionOld); } File.Move(absolutePath + FileExtensionNew, absolutePath); File.Delete(absolutePath + FileExtensionOld); } } }
#include "game/gui/frame.h" guiframe* guiframe_create(int x, int y, int w, int h) { guiframe *frame = malloc(sizeof(guiframe)); memset(frame, 0, sizeof(guiframe)); frame->x = x; frame->y = y; frame->w = w; frame->h = h; return frame; } void guiframe_set_root(guiframe *frame, component *root_node) { if(root_node == frame->root_node) { return; } if(frame->root_node != NULL) { component_free(frame->root_node); } frame->root_node = root_node; } void guiframe_free(guiframe *frame) { if(frame == NULL) { return; } if(frame->root_node) { component_free(frame->root_node); } free(frame); } component* guiframe_find(guiframe *frame, int id) { if(frame->root_node) { return component_find(frame->root_node, id); } return NULL; } component* guiframe_get_root(const guiframe *frame) { return frame->root_node; } void guiframe_tick(guiframe *frame) { if(frame->root_node) { component_tick(frame->root_node); } } void guiframe_render(guiframe *frame) { if(frame->root_node) { component_render(frame->root_node); } } int guiframe_event(guiframe *frame, SDL_Event *event) { if(frame->root_node) { return component_event(frame->root_node, event); } return 1; } int guiframe_action(guiframe *frame, int action) { if(frame->root_node) { return component_action(frame->root_node, action); } return 1; } void guiframe_layout(guiframe *frame) { if(frame->root_node) { component_layout(frame->root_node, frame->x, frame->y, frame->w, frame->h); } }
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com) * * 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. */ #pragma once #ifndef __H__OCULAR_EVENTS_SCENE_OBJECT_ADDED_EVENT__H__ #define __H__OCULAR_EVENTS_SCENE_OBJECT_ADDED_EVENT__H__ #include "Events/AEvent.hpp" #include "Scene/SceneObject.hpp" //------------------------------------------------------------------------------------------ /** * \addtogroup Ocular * @{ */ namespace Ocular { /** * \addtogroup Core * @{ */ namespace Core { /** * \class SceneObjectAddedEvent * * Event notifying that a SceneObject has been added to the active Scene. * * String Descriptor: "SceneObjectAddedEvent" <br/> * Event Priority: Medium */ class SceneObjectAddedEvent : public AEvent { public: SceneObjectAddedEvent(SceneObject* object); SceneObjectAddedEvent(); virtual ~SceneObjectAddedEvent(); SceneObject* object; Core::UUID uuid; protected: private: }; } /** * @} End of Doxygen Groups */ } /** * @} End of Doxygen Groups */ //------------------------------------------------------------------------------------------ #endif
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.knowledgebase; import com.liferay.portal.kernel.exception.PortalException; /** * @author Brian Wing Shun Chan */ public class InvalidKBArticleUrlTitleException extends PortalException { public InvalidKBArticleUrlTitleException() { super(); } public InvalidKBArticleUrlTitleException(String msg) { super(msg); } public InvalidKBArticleUrlTitleException(String msg, Throwable cause) { super(msg, cause); } public InvalidKBArticleUrlTitleException(Throwable cause) { super(cause); } }
#pragma once #ifndef _MALLOC_HEAD_H_ #define _MALLOC_HEAD_H_ #include <stdlib.h> #define MALLOC malloc #define CALLOC calloc #define REALLOC realloc #define FREE free #endif
# coding=utf-8 """ © 2014 LinkedIn Corp. 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. """ from luminol.constants import * __all__ = ['bitmap_detector', 'derivative_detector', 'exp_avg_detector', 'default_detector', 'absolute_threshold', 'diff_percent_threshold'] class AnomalyDetectorAlgorithm(object): """ Base Class for AnomalyDetector algorithm. """ def __init__(self, class_name, time_series, baseline_time_series=None): """ Initializer :param str class_name: extended class name. :param TimeSeries time_series: a TimeSeries object. :param TimeSeries baseline_time_series: baseline TimeSeries. """ self.class_name = class_name self.time_series = time_series self.time_series_length = len(time_series) self.baseline_time_series = baseline_time_series def run(self): """ Run the algorithm to get anomalies. return list: a list of Anomaly objects. """ self._set_scores() return self.anom_scores def _denoise_scores(self, scores): """ Denoise anomaly scores. Low anomaly scores could be noisy. The following two series will have good correlation result with out denoise: [0.08, 4.6, 4.6, 4.6, 1.0, 1.0] [0.0010, 0.0012, 0.0012, 0.0008, 0.0008] while the second series is pretty flat(suppose it has a max score of 100). param dict scores: the scores to be denoised. """ if scores: maximal = max(scores.values()) if maximal: for key in scores: if scores[key] < DEFAULT_NOISE_PCT_THRESHOLD * maximal: scores[key] = 0 return scores # Need to be extended. def _set_scores(self): """ Compute anomaly scores for the time series. """ raise NotImplementedError def get_scores(self): """ Get anomaly scores for the time series. :return TimeSeries: a TimeSeries representation of the anomaly scores. """ return self.anom_scores
"""Scraper for the United States Court of Appeals for the Armed Forces CourtID: armfor Court Short Name: C.A.A.F.""" from datetime import date, datetime from juriscraper.OpinionSite import OpinionSite from lxml import html class Site(OpinionSite): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) today = date.today() if today.month > 8 and today.day > 4: url_year = today.year else: url_year = today.year - 1 self.url = 'http://www.armfor.uscourts.gov/newcaaf/opinions/%sSepTerm.htm' % url_year self.court_id = self.__module__ def _get_case_names(self): return [t for t in self.html.xpath('//table//tr[descendant::a]/td[1]/font/text()')] def _get_download_urls(self): return [t for t in self.html.xpath('//table//tr[descendant::a]/td[2]/font/a/@href')] def _get_case_dates(self): dates = [] date_formats = ('%b %d, %Y', '%B %d, %Y') for s in self.html.xpath('//table//tr[descendant::a]/td[3]/font/text()'): s = s.strip() for date_format in date_formats: try: dates.append(datetime.strptime(s, date_format).date()) break except ValueError: continue return dates def _get_docket_numbers(self): docket_numbers = [] for e in self.html.xpath('//table//table//tr[descendant::a and position() > 1]/td[2]'): s = html.tostring(e, method='text', encoding='unicode') docket_numbers.append(s.strip()[:-5]) return docket_numbers def _get_precedential_statuses(self): return ['Published'] * len(self.case_names)
import pytest import json from django.urls import reverse # All test need access to the database in this file. pytestmark = pytest.mark.django query_template = '?q_type={0}&q={1}' def test_json_search_returns_expected_results(client, name_fixtures): """Test that the search returns the Name object that was searched for and that the status code is 200. """ query = query_template.format('Personal', 'person') response = client.get(reverse('name:search-json') + query) assert response.status_code is 200 assert json.loads(response.content)[0]['name'] == 'test person' def test_json_search_with_multiple_name_types(client, name_fixtures): query = query_template.format('Personal,Organization', 'test') response = client.get( reverse('name:search-json') + query) json_results = json.loads(response.content) assert response.status_code is 200 assert len(json_results) is 2 def test_can_search(client, name_fixtures): """Test the HTML search returns correctly.""" query = query_template.format('Personal', 'test') response = client.get(reverse('name:search') + query) assert response.status_code is 200 def test_search_multiple_name_types(client, name_fixtures): query = query_template.format('Personal,Organization', 'test') response = client.get( reverse('name:search') + query) assert response.status_code is 200 def test_search_with_q(client, twenty_name_fixtures): """Search with q only. No name_types provided.""" name = twenty_name_fixtures.first() url = reverse('name:search') response = client.get(url, {'q': name.name}) name_list = response.context[-1]['name_list'] assert name in name_list def test_search_with_q_type(client, search_fixtures): url = reverse('name:search') response = client.get(url, {'q_type': 'Personal'}) name_list = response.context[-1]['name_list'] assert len(name_list) == 4 assert all(x.is_personal() for x in name_list) def test_search_with_two_q_types(client, search_fixtures): url = reverse('name:search') response = client.get(url, {'q_type': 'Personal,Event'}) name_list = response.context[-1]['name_list'] assert len(name_list) == 8 assert all(x.is_personal() or x.is_event() for x in name_list) def test_search_without_query(client, search_fixtures): url = reverse('name:search') response = client.get(url) name_list = response.context[-1]['name_list'] assert len(name_list) is 0
from django.conf import settings from django.conf.urls import patterns, url urlpatterns = patterns( 'shoppingcart.views', url(r'^postpay_callback/$', 'postpay_callback'), # Both the ~accept and ~reject callback pages are handled here url(r'^receipt/(?P<ordernum>[0-9]*)/$', 'show_receipt'), url(r'^donation/$', 'donate', name='donation'), url(r'^csv_report/$', 'csv_report', name='payment_csv_report'), # These following URLs are only valid if the ENABLE_SHOPPING_CART feature flag is set url(r'^$', 'show_cart'), url(r'^clear/$', 'clear_cart'), url(r'^remove_item/$', 'remove_item'), url(r'^add/course/{}/$'.format(settings.COURSE_ID_PATTERN), 'add_course_to_cart', name='add_course_to_cart'), url(r'^register/redeem/(?P<registration_code>[0-9A-Za-z]+)/$', 'register_code_redemption', name='register_code_redemption'), url(r'^use_code/$', 'use_code'), url(r'^update_user_cart/$', 'update_user_cart'), url(r'^reset_code_redemption/$', 'reset_code_redemption'), url(r'^billing_details/$', 'billing_details', name='billing_details'), url(r'^verify_cart/$', 'verify_cart'), ) if settings.FEATURES.get('ENABLE_PAYMENT_FAKE'): from shoppingcart.tests.payment_fake import PaymentFakeView urlpatterns += patterns( 'shoppingcart.tests.payment_fake', url(r'^payment_fake', PaymentFakeView.as_view()), )
<?php /** * Provide a public-facing view for the plugin * * This file is used to markup the public-facing aspects of the plugin. * * @link http://www.daffodilsw.com/ * @since 1.0.0 * * @package Wp_Custom_Register_Login * @subpackage Wp_Custom_Register_Login/public/partials */ ?> <div id="wpcrlLoginSection" class="container-fluid"> <div class="row"> <div class="col-xs-8 col-md-10"> <?php $wpcrl_redirect_settings = get_option('wpcrl_redirect_settings'); $wpcrl_form_settings = get_option('wpcrl_form_settings'); // check if the user already login if (!is_user_logged_in()) : $form_heading = empty($wpcrl_form_settings['wpcrl_signin_heading']) ? 'Login' : $wpcrl_form_settings['wpcrl_signin_heading']; $submit_button_text = empty($wpcrl_form_settings['wpcrl_signin_button_text']) ? 'Login' : $wpcrl_form_settings['wpcrl_signin_button_text']; $forgotpassword_button_text = empty($wpcrl_form_settings['wpcrl_forgot_password_button_text']) ? 'Forgot Password' : $wpcrl_form_settings['wpcrl_forgot_password_button_text']; $is_url_has_token = $_GET['wpcrl_reset_password_token']; ?> <form name="wpcrlLoginForm" id="wpcrlLoginForm" method="post" class="<?php echo empty($is_url_has_token) ? '' : 'hidden' ?>"> <h3><?php _e($form_heading, $this->plugin_name); ?></h3> <div id="wpcrl-login-loader-info" class="wpcrl-loader" style="display:none;"> <img src="<?php echo plugins_url('images/ajax-loader.gif', dirname(__FILE__)); ?>"/> <span><?php _e('Please wait ...', $this->plugin_name); ?></span> </div> <div id="wpcrl-login-alert" class="alert alert-danger" role="alert" style="display:none;"></div> <div class="form-group"> <label for="username"><?php _e('Username', $this->plugin_name); ?></label> <input type="text" class="form-control" name="wpcrl_username" id="wpcrl_username" placeholder="Username"> </div> <div class="form-group"> <label for="password"><?php _e('Password', $this->plugin_name); ?></label> <input type="password" class="form-control" name="wpcrl_password" id="wpcrl_password" placeholder="Password" > </div> <?php $login_redirect = (empty($wpcrl_redirect_settings['wpcrl_login_redirect']) || $wpcrl_redirect_settings['wpcrl_login_redirect'] == '-1') ? '' : $wpcrl_redirect_settings['wpcrl_login_redirect']; ?> <input type="hidden" name="redirection_url" id="redirection_url" value="<?php echo get_permalink($login_redirect); ?>" /> <?php // this prevent automated script for unwanted spam if (function_exists('wp_nonce_field')) wp_nonce_field('wpcrl_login_action', 'wpcrl_login_nonce'); ?> <button type="submit" class="btn btn-primary"><?php _e($submit_button_text, $this->plugin_name); ?></button> <?php //render forgot password button if($wpcrl_form_settings['wpcrl_enable_forgot_password']){ ?> <button id="btnForgotPassword" type="button" class="btn btn-primary"><?php _e($forgotpassword_button_text, $this->plugin_name); ?></button> <?php } ?> </form> <?php //render the reset password form if($wpcrl_form_settings['wpcrl_enable_forgot_password']){ do_shortcode('[wpcrl_resetpassword_form]'); } ?> <?php else: $current_user = wp_get_current_user(); $logout_redirect = (empty($wpcrl_redirect_settings['wpcrl_logout_redirect']) || $wpcrl_redirect_settings['wpcrl_logout_redirect'] == '-1') ? '' : $wpcrl_redirect_settings['wpcrl_logout_redirect']; echo 'Logged in as <strong>' . ucfirst($current_user->user_login) . '</strong>. <a href="' . wp_logout_url(get_permalink($logout_redirect)) . '">Log out ? </a>'; endif; ?> </div> </div> </div>
''' Inputs a SNP call file and a pileup file generated by samtools Outputs allele frequencies ''' import sys snpcall_file = sys.argv[1] snpcall_handle = open(snpcall_file, 'r') pileup_file = sys.argv[2] pileup_handle = open(pileup_file, 'r') qual_thresh = 30 #Minimum genotype quality to call a SNP genotype #Let's go through the SNP call file and the pileup files simultaneously #Every time we find a SNP in the SNP call file that qualifies, we will: # -Go to the corresponding line in the pileup file # -Count the number of reference and alternate alleles in each backcross line # (read depth of coverage, how many reference alleles, and then subtract to get number of # non-reference alleles) # -Figure out which parent strain carries the reference allele and which carries the # reference allele # -Output: Chrom, Pos, SAM-SAMlike, SAM-ORElike, ORE-SAMlike, ORE-ORElike, Long-SAMlike, Long-ORElike, Short1-SAMlike, Short1-ORElike, etc. for cur_line in snpcall_handle: #Make sure it's not a comment/header line if cur_line[0] != "#": #Get the genotypes cur_fields = cur_line.split("\t") sam_info = cur_fields[9] ore_info = cur_fields[10] sam_geno = sam_info.split(":")[0] ore_geno = ore_info.split(":")[0] sam_qual = int(sam_info.split(":")[3]) ore_qual = int(ore_info.split(":")[3]) #Keep only the SNPs for which both lines are homozygous and different from each other # Also make sure that they are high genotype qualities # Also, for now, let's skip any indel alleles because their pileups are difficult to parse not_indel = (len(cur_fields[3]) == len(cur_fields[4])) if ((sam_geno != "0/1") & (ore_geno != "0/1") & (sam_geno != ore_geno) & (sam_qual >= qual_thresh) & (ore_qual >= qual_thresh) & not_indel): #We've found a good SNP! #Now read the next line in the pileup file, and repeat until we find the one that corresponds # to the current SNP pileup_line = pileup_handle.readline() pileup_fields = pileup_line.split("\t") while not ((pileup_fields[0] == cur_fields[0]) & (pileup_fields[1] == cur_fields[1])): pileup_line = pileup_handle.readline() pileup_fields = pileup_line.split("\t") if not ((pileup_fields[0] == cur_fields[0]) & (pileup_fields[1] == cur_fields[1])): #This should never be called, really, since we just exited a while loop that ends # only when this condition is not satisfied... but just in case print("ERROR: SNP call line does not match pileup line") quit() else: #Count the number of reference and non-reference reads for each ref_counts = [] alt_counts = [] for i in range(11): coverage_col = 3 + i*3 total_coverage = int(pileup_fields[coverage_col]) #How many reference alleles were there? ref_count = pileup_fields[coverage_col+1].count('.') + pileup_fields[coverage_col+1].count(',') alt_count = total_coverage - ref_count ref_counts.append(ref_count) alt_counts.append(alt_count) #Now figure out whether SAM or ORE is the reference if sam_geno == "0/0": sam_counts = ref_counts ore_counts = alt_counts else: sam_counts = alt_counts ore_counts = ref_counts out_line = cur_fields[0] #Chromosome out_line = out_line + ',' + cur_fields[1] #Position for i in range(11): out_line = out_line + ',' + str(sam_counts[i]) out_line = out_line + ',' + str(ore_counts[i]) print(out_line) pileup_handle.close() snpcall_handle.close()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://gw.alipayobjects.com/os/lib/antd/4.3.1/dist/antd.min.css"> </head> <body> <hello-world></hello-world> <script type="module"> import React, { Component } from 'https://jspm.alibaba-inc.com/react'; import ReactDOM from 'https://jspm.alibaba-inc.com/react-dom'; import { Button } from 'https://jspm.alibaba-inc.com/antd'; class HelloWorld extends HTMLElement { connectedCallback() { ReactDOM.render(React.createElement(Button, null, "Antd Button"), this); } } customElements.define('hello-world', HelloWorld); </script> </body> </html>
{% extends "task/_index.html" %} {% block bl_content_body %} About Monte Carlo Production monitor application text {% endblock %}
import sys import time import subprocess from six.moves.urllib.parse import urlencode import scrapy from scrapy.command import ScrapyCommand from scrapy.contrib.linkextractors import LinkExtractor class Command(ScrapyCommand): default_settings = { 'LOG_LEVEL': 'INFO', 'LOGSTATS_INTERVAL': 1, 'CLOSESPIDER_TIMEOUT': 10, } def short_desc(self): return "Run quick benchmark test" def run(self, args, opts): with _BenchServer(): self.crawler_process.crawl(_BenchSpider, total=100000) self.crawler_process.start() class _BenchServer(object): def __enter__(self): from scrapy.utils.test import get_testenv pargs = [sys.executable, '-u', '-m', 'scrapy.utils.benchserver'] self.proc = subprocess.Popen(pargs, stdout=subprocess.PIPE, env=get_testenv()) self.proc.stdout.readline() def __exit__(self, exc_type, exc_value, traceback): self.proc.kill() self.proc.wait() time.sleep(0.2) class _BenchSpider(scrapy.Spider): """A spider that follows all links""" name = 'follow' total = 10000 show = 20 baseurl = 'http://localhost:8998' link_extractor = LinkExtractor() def start_requests(self): qargs = {'total': self.total, 'show': self.show} url = '{}?{}'.format(self.baseurl, urlencode(qargs, doseq=1)) return [scrapy.Request(url, dont_filter=True)] def parse(self, response): for link in self.link_extractor.extract_links(response): yield scrapy.Request(link.url, callback=self.parse)
/* * Copyright (C) 2004-2010 Geometer Plus <contact@geometerplus.com> * * 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. */ #ifndef __ZLCONFIG_H__ #define __ZLCONFIG_H__ #include <vector> #include <string> class ZLConfig; class ZLConfigManager { private: static ZLConfigManager &Instance() { return *ourInstance; } public: static bool isInitialised() { return ourIsInitialised; } static void deleteInstance() { if (ourInstance != 0) { delete ourInstance; } } protected: virtual ~ZLConfigManager(); private: virtual ZLConfig *createConfig() const = 0; protected: static ZLConfigManager *ourInstance; static bool ourIsInitialised; friend class ZLOption; }; class ZLConfig { public: virtual ~ZLConfig(); virtual void listOptionNames(const std::string &groupName, std::vector<std::string> &names) = 0; virtual void listOptionGroups(std::vector<std::string> &groups) = 0; virtual void removeGroup(const std::string &name) = 0; virtual const std::string &getDefaultValue(const std::string &group, const std::string &name, const std::string &defaultValue) const = 0; virtual const std::string &getValue(const std::string &group, const std::string &name, const std::string &defaultValue) const = 0; virtual void setValue(const std::string &group, const std::string &name, const std::string &value, const std::string &category) = 0; virtual void unsetValue(const std::string &group, const std::string &name) = 0; virtual bool isAutoSavingSupported() const = 0; virtual void startAutoSave(int seconds) = 0; }; #endif /* __ZLCONFIG_H__ */
import pygame from pygame.locals import * import random from pgu import timer rr = random.randrange class Part: def __init__(self,x,y): x,y = float(x),float(y) self.x,self.y = x,y self._x,self._y = x,y self.min = 4.0 self.max = 16.0 self.radius = 16.0 self.center = 2.0 self.search = 64.0 self._flock_frame = 0 self.near = [] class Flock: def __init__(self,rect,spacing): self.rect,self.spacing = rect,spacing self.grid = [[[] for tx in xrange(rect.left,rect.right,spacing)] for ty in xrange(rect.top,rect.bottom,spacing)] self.parts = [] def append(self,p): rect,spacing,grid,parts = self.rect,self.spacing,self.grid,self.parts self.parts.append(p) tx,ty = p._tx,p._ty = int((p.x-rect.left)/spacing),int((p.y-rect.top)/spacing) p.vx,p.vy = 0,0 grid[ty][tx].append(p) def remove(self,p): rect,spacing,grid,parts = self.rect,self.spacing,self.grid,self.parts tx,ty = p._tx,p._ty grid[ty][tx].remove(p) parts.remove(p) def __len__(self): return self.parts.__len__() def __iter__(self): return self.parts.__iter__() def loop(self): rect,spacing,grid,parts = self.rect,self.spacing,self.grid,self.parts gw,gh = len(grid[0]),len(grid) #update grid for p in parts: tx,ty = p._tx,p._ty grid[ty][tx].remove(p) tx,ty = p._tx,p._ty = int((p.x-rect.left)/spacing),int((p.y-rect.top)/spacing) grid[ty][tx].append(p) #calculate velocities for p in parts: p.vx,p.vy = p.x-p._x,p.y-p._y p._x,p._y = p.x,p.y #calculate neighbors for p in parts: tx,ty = p._tx,p._ty p.near = [] for dy in (-1,0,1): for dx in (-1,0,1): xx,yy = tx+dx,ty+dy if xx < 0 or yy < 0 or xx >= gw or yy >= gh: continue p.near.extend(grid[yy][xx]) p.near.remove(p) p.ax,p.ay = p.x,p.y p.avx,p.avy = p.vx,p.vy for _p in p.near: p.ax += _p.x p.ay += _p.y p.avx += _p.vx p.avy += _p.vy total = len(p.near)+1 p.ax /= total p.ay /= total p.avx /= total p.avy /= total #add average velocity to item for p in parts: p.x,p.y = p.x+p.avx,p.y+p.avy #move towards the center for p in parts: step = p.center ax,ay = p.ax,p.ay dx,dy = ax-p.x,ay-p.y dist = (dx*dx+dy*dy)**0.5 if dist > step: p.x,p.y = p.x+step*dx/dist,p.y+step*dy/dist #check min velocity for p in parts: step = p.min dx,dy = p.x-p._x,p.y-p._y dist = (dx*dx+dy*dy)**0.5 while dist < 0.5: dx,dy = random.randrange(-1,2),random.randrange(-1,2) dist = (dx*dx+dy*dy)**0.5 if dist < step: p.x,p.y = p._x+dx*step/dist,p._y+dy*step/dist #keep away from neighbords for p in parts: for _p in p.near: dx,dy = _p.x-p.x,_p.y-p.y dist = (dx*dx+dy*dy)**0.5 r = p.radius+_p.radius if dist < r: if dist == 0: dist,dx = 1,1 inc = r/2.0 mx,my = (p.x+_p.x)/2,(p.y+_p.y)/2 p.x,p.y = mx - (inc*dx/dist), my - (inc*dy/dist) _p.x,_p.y = mx + (inc*dx/dist), my + (inc*dy/dist) #check max velocity for p in parts: step = p.max dx,dy = p.x-p._x,p.y-p._y dist = (dx*dx+dy*dy)**0.5 if dist > step: p.x,p.y = p._x+dx*step/dist,p._y+dy*step/dist if __name__ == '__main__': try: #0/0 #HACK: so i can CTRL-c out import psyco psyco.profile() print 'psyco installed' except: print 'psyco not installed' SW,SH = 640,480 screen = pygame.display.set_mode((SW,SH)) num = 256 rad = 12 spacing = rad*3/2 border = spacing*2 myflock = Flock(pygame.Rect(-border,-border,SW+border*2,SH+border*2),spacing) for n in xrange(0,num): p = Part(rr(0,SW),rr(0,SH)) p.radius = rad myflock.append(p) t = timer.Speedometer() pygame.time.get_ticks() us = [(0,0,SW,SH)] _quit = False frames = 0 while not _quit: for e in pygame.event.get(): if e.type is QUIT: _quit = True if e.type is KEYDOWN and e.key == K_ESCAPE: _quit = True for r in us: screen.fill((0,0,0),r) _us,us = us,[] us = [] p = myflock.parts[0] #HACK!! p.x,p.y = pygame.mouse.get_pos() p.radius = 64 x,y,r = int(p.x),int(p.y),int(p.radius) pygame.draw.circle(screen,(0,0,128),(x,y),r) us.append((x-r,y-r,r*2,r*2)) myflock.loop() for p in myflock: #HACK!! p.x = max(0,min(SW,p.x)) p.y = max(0,min(SH,p.y)) rect = int(p.x),int(p.y),4,4 screen.fill((255,255,255),rect) us.append(rect) pygame.display.update(_us) pygame.display.update(us) r = t.tick() if r: print r frames += 1
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark 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. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest02126") public class BenchmarkTest02126 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getParameter("vector"); if (param == null) param = ""; String bar = doSomething(param); response.getWriter().print(bar); } // end doPost private static String doSomething(String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a30595 = param; //assign StringBuilder b30595 = new StringBuilder(a30595); // stick in stringbuilder b30595.append(" SafeStuff"); // append some safe content b30595.replace(b30595.length()-"Chars".length(),b30595.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map30595 = new java.util.HashMap<String,Object>(); map30595.put("key30595", b30595.toString()); // put in a collection String c30595 = (String)map30595.get("key30595"); // get it back out String d30595 = c30595.substring(0,c30595.length()-1); // extract most of it String e30595 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d30595.getBytes() ) )); // B64 encode and decode it String f30595 = e30595.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(f30595); // reflection return bar; } }
import datetime import time from django.conf import settings from typing import Any, Dict, Text from django.http import HttpRequest, HttpResponse from django.utils.timezone import now as timezone_now from django.utils.translation import ugettext as _ from zerver.decorator import authenticated_json_post_view, human_users_only from zerver.lib.actions import get_status_dict, update_user_presence from zerver.lib.request import has_request_variables, REQ, JsonableError from zerver.lib.response import json_success, json_error from zerver.lib.timestamp import datetime_to_timestamp from zerver.lib.validator import check_bool from zerver.models import UserActivity, UserPresence, UserProfile, get_user def get_status_list(requesting_user_profile: UserProfile) -> Dict[str, Any]: return {'presences': get_status_dict(requesting_user_profile), 'server_timestamp': time.time()} def get_presence_backend(request: HttpRequest, user_profile: UserProfile, email: Text) -> HttpResponse: try: target = get_user(email, user_profile.realm) except UserProfile.DoesNotExist: return json_error(_('No such user')) if not target.is_active: return json_error(_('No such user')) if target.is_bot: return json_error(_('Presence is not supported for bot users.')) presence_dict = UserPresence.get_status_dict_by_user(target) if len(presence_dict) == 0: return json_error(_('No presence data for %s' % (target.email,))) # For initial version, we just include the status and timestamp keys result = dict(presence=presence_dict[target.email]) aggregated_info = result['presence']['aggregated'] aggr_status_duration = datetime_to_timestamp(timezone_now()) - aggregated_info['timestamp'] if aggr_status_duration > settings.OFFLINE_THRESHOLD_SECS: aggregated_info['status'] = 'offline' for val in result['presence'].values(): val.pop('client', None) val.pop('pushable', None) return json_success(result) @human_users_only @has_request_variables def update_active_status_backend(request, user_profile, status=REQ(), ping_only=REQ(validator=check_bool, default=False), new_user_input=REQ(validator=check_bool, default=False)): # type: (HttpRequest, UserProfile, str, bool, bool) -> HttpResponse status_val = UserPresence.status_from_string(status) if status_val is None: raise JsonableError(_("Invalid status: %s") % (status,)) else: update_user_presence(user_profile, request.client, timezone_now(), status_val, new_user_input) if ping_only: ret = {} # type: Dict[str, Any] else: ret = get_status_list(user_profile) if user_profile.realm.is_zephyr_mirror_realm: # In zephyr mirroring realms, users can't see the presence of other # users, but each user **is** interested in whether their mirror bot # (running as their user) has been active. try: activity = UserActivity.objects.get(user_profile = user_profile, query="get_events_backend", client__name="zephyr_mirror") ret['zephyr_mirror_active'] = \ (activity.last_visit > timezone_now() - datetime.timedelta(minutes=5)) except UserActivity.DoesNotExist: ret['zephyr_mirror_active'] = False return json_success(ret)
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Events</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="EventDetail"> <h3>Birth</h3> <table class="infolist eventlist"> <tbody> <tr> <td class="ColumnAttribute">Gramps ID</td> <td class="ColumnGRAMPSID">E19112</td> </tr> <tr> <td class="ColumnAttribute">Date</td> <td class="ColumnColumnDate"> about 1829 </td> </tr> <tr> <td class="ColumnAttribute">Place</td> <td class="ColumnColumnPlace"> <a href="../../../plc/a/1/d15f60a4189689e8e83826dfa1a.html" title=""> </a> </td> </tr> </tbody> </table> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/a/d/d15f60a41b94642946bdc5d0fda.html" title="1861 England Census Daniel Gammon Household" name ="sref1"> 1861 England Census Daniel Gammon Household <span class="grampsid"> [S0421]</span> </a> <ol> <li id="sref1a"> <ul> <li> Page: Household 52 </li> <li> Confidence: High </li> </ul> </li> </ol> </li> </ol> </div> <div class="subsection" id="references"> <h4>References</h4> <ol class="Col1" role="Volume-n-Page"type = 1> <li> <a href="../../../ppl/6/3/d15f60a46c43eb3c9a0e7f73336.html"> GAMMON, Ann <span class="grampsid"> [I18780]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:34<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
using Android.App; using Android.OS; using Android.Widget; namespace animated_in_out { [Activity(Label = "FirstActivity", MainLauncher = true, Icon = "@drawable/icon")] public class FirstActivity : MainActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.First); var btnNext = FindViewById<Button>(Resource.Id.btnNext); var txtTitle = FindViewById<TextView>(Resource.Id.textTitle); txtTitle.Text = "First activity"; btnNext.Click += delegate { StartActivity(typeof(SecondActivity)); }; } } }
# Author: Enric Tejedor CERN 11/2018 ################################################################################ # Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. # # All rights reserved. # # # # For the licensing terms see $ROOTSYS/LICENSE. # # For the list of contributors see $ROOTSYS/README/CREDITS. # ################################################################################ r''' /** \class TArray \brief \parblock \endparblock \htmlonly <div class="pyrootbox"> \endhtmlonly ## PyROOT When used from Python, the subclasses of TArray (TArrayC, TArrayS, TArrayI, TArrayL, TArrayF and TArrayD) benefit from the following extra features: - Their size can be obtained with `len`, which is equivalent to TArray::GetSize(): \code{.py} import ROOT a = ROOT.TArrayD(2) print(len(a)) # prints '2' \endcode - Their elements can be read and written with the `getitem` and `setitem` operators, respectively: \code{.py} a[0] = 0.2 a[1] = 1.7 print(a[0]) # prints '0.2' \endcode - They are iterable: \code{.py} for elem in a: print(elem) \endcode \htmlonly </div> \endhtmlonly */ ''' from ROOT import pythonization from ._generic import _add_getitem_checked @pythonization() def pythonize_tarray(klass, name): # Parameters: # klass: class to be pythonized # name: string containing the name of the class if name == 'TArray': # Support `len(a)` as `a.GetSize()` klass.__len__ = klass.GetSize elif name.startswith('TArray'): # Add checked __getitem__. It has to be directly added to the TArray # subclasses, which have a default __getitem__. # The new __getitem__ allows to throw pythonic IndexError when index # is out of range and to iterate over the array. _add_getitem_checked(klass) return True
<h3>推荐位列表</h3> <admin:panel > <admin:table id="table" show="编号|50,名称,顺序,操作|120" class="m-table-border"> <foreach name="list" item="vo"> <tr> <td>{$vo.position_id}</td> <td>{$vo.name}</td> <td>{$vo.sequence}</td> <td><a class="u-btn u-btn-primary u-btn-small" href="{:U('edit',array('position_id'=>$vo['position_id']))}">修改</a> <a class="u-btn u-btn-danger u-btn-small del" href="javascript:;" data="{$vo.position_id}">删除</a></td> </tr> </foreach> </admin:table> </admin:panel> <script> Do.ready('base',function() { $('#table').duxTable({ deleteUrl: "{:U('del')}" }); }); </script>
/* Copyright 2016 Martin Haesemeyer Licensed under the MIT License, see License.txt. 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. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MHApi.Threading { public class TimestampedObject<K> { /// <summary> /// The timestapm associated with the contained object /// </summary> public DateTime Timestamp { get; private set; } /// <summary> /// The contained object /// </summary> public K Object { get; private set; } /// <summary> /// Constructor setting the timestamp to NOW /// </summary> /// <param name="obj">The contained object</param> public TimestampedObject(K obj) { Timestamp = DateTime.Now; Object = obj; } /// <summary> /// Constructor /// </summary> /// <param name="obj">The contained object</param> /// <param name="timestamp">The timestamp to associate with the object</param> public TimestampedObject(K obj, DateTime timestamp) { Timestamp = timestamp; Object = obj; } } }
import { Component } from '@angular/core' @Component({ selector: 'aboutUs', templateUrl: 'app/home/successStories.component.html' }) export class SuccessStoriesComponent { }
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved. // Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information. namespace NBench.Sdk { /// <summary> /// Used to invoke the benchmark methods on the user-defined /// objects that have methods marked with <see cref="PerfBenchmarkAttribute" />. /// </summary> public interface IBenchmarkInvoker { string BenchmarkName { get; } void InvokePerfSetup(BenchmarkContext context); /// <summary> /// Used for <see cref="RunMode.Throughput"/> scenarios /// </summary> /// <param name="runCount">The number of runs for which we'll execute this benchmark</param> /// <param name="context">The context used for the run</param> void InvokePerfSetup(long runCount, BenchmarkContext context); void InvokeRun(BenchmarkContext context); void InvokePerfCleanup(BenchmarkContext context); } }
import requests, time, hashlib, datetime, json from requests.auth import HTTPDigestAuth import email.utils as eut from .exceptions import * try: import simplejson as json except ImportError: try: import json except ImportError: try: from django.utils import simplejson as json except ImportError: raise ImportError('A json library is required to use ') class Roxee(object): def __init__(self, key, secret, host=None, version=None, api_section=''): self._r = RoxeeRequest(key, secret, host, version) if api_section != '': self.api_section = api_section else: for x in ['data','lookup']: setattr(self, x, Roxee( key, secret, host, version, x)) def call(self, method, params=None): try: if params: params = tuple(params.values()) else: params = '' resp = self._r.get('/%s/%s/%s' % (self.api_section, method, '/'.join(params))) except requests.exceptions.RequestException as e: raise HTTPRequestException(e) if resp.status_code != 200: raise HTTPRequestException(resp.status_code) return json.loads(resp.content.decode('utf-8')) def __getattr__(self, method_name): def get(self, *args, **kwargs): params = dict((i, j) for (i, j) in enumerate(args)) params.update(kwargs) return self.call(method_name.replace('_', '-'), params) return get.__get__(self) def __getitem__(self, method_name): def get(self, *args, **kwargs): params = dict((i, j) for (i, j) in enumerate(args)) params.update(kwargs) return self.call(method_name.replace('_', '-'), params) return get.__get__(self) class RoxeeRequest(object): SESSION = requests.session() def __init__(self, key, secret, host=None, version=None): self.key = key self.secret = secret self.host = host if host else 'api.roxee.net' self.version = version if version else '1.0' self.api_url = "http://%s/%s" % (self.host, self.version) self.algo = "md5" self._delta = 0 def get(self, url, params = {}): return self.request('GET', url, params=params) def request(self, method, url, **args): if 'headers' not in args: args['headers'] = {} args['headers']['User-Agent'] = 'PyRoxee 0.1' args['hooks'] = { 'pre_request' : self._setSignature, 'response' : self._postHook} return RoxeeRequest.SESSION.request(method, '%s%s' % (self.api_url, url), **args) def _setSignature(self, req): ts = int(time.time()) + self._delta ha = self.__hash('%s:%s:%s' % (self.key, self.secret, ts)) signature = self.__hash('%s:%s:%s' % (req.method, requests.utils.urlparse(req.url).path, ha)) sig = 'access Timestamp="%s", Signature="%s", KeyId="%s", Algorithm="%s"' % (ts,signature,self.key,self.algo) req.headers.update({'X-Signature': sig}) def _postHook(self, resp): if 'signature expired' not in resp.content.decode('utf-8'): return delta = datetime.datetime.utcnow() - datetime.datetime(*eut.parsedate(resp.headers.get('Date'))[:6]) self._delta = int(delta.total_seconds()) self._setSignature(resp.request) resp.request.send(anyway=True) _r = resp.request.response _r.history.append(resp) return _r def __hash(self, string): return hashlib.md5(string.encode('utf-8')).hexdigest()
# Nice print stuff TAB = 12*' ' NLTAB = ',\n'+TAB USAGE = """usage: autoload.py [options] Generates python code for a given database schema. options: -h, --help Show this help -u URL, --url URL Database url (e.g.: postgresql+psycopg2://postgres:user@password/Database) -o FILE, --output FILE Where to put the output (default is stdout) -s NAME, --schema NAME Name of the schema to output (default is 'default') -t T1,T2,.. , --tables T1,T2 Name of tables to inspect (default is 'all'). Support globbing character to select more tables. ex.: -t Download* will generate a model for all tables starting with Download -i --noindex Do not generate index information -g --generic-types Generate generic column types rather than database-specific type -e --example Generate code with examples how to access data -3 --z3c Generate code for use with z3c.sqlalchemy """ HEADER = """\ # -*- coding: %(encoding)s -*- ## File autogenerated by SQLAutoCode ## see http://code.google.com/p/sqlautocode/ from sqlalchemy import * %(dialect)s metadata = MetaData() """ HEADER_Z3C = """\ # -*- coding: %(encoding)s -*- ## File autogenerated by SQLAutoCode ## see http://code.google.com/p/sqlautocode/ ## Export type: z3c.sqlalchemy from sqlalchemy import * %(dialect)s from z3c.sqlalchemy import Model from z3c.sqlalchemy.mapper import MappedClassBase def getModel(metadata): model = Model() """ PG_IMPORT = """\ try: from sqlalchemy.dialects.postgresql import * except ImportError: from sqlalchemy.databases.postgres import * """ FOOTER_Z3C = """ return model """ FOOTER_EXAMPLE = """ # some example usage if __name__ == '__main__': db = create_engine(%(url)r) metadata.bind = db # fetch first 10 items from %(tablename)s s = %(tablename)s.select().limit(10) rs = s.execute() for row in rs: print row """ TABLE = """ Table('%(name)s', metadata, %(columns)s, %(constraints)s %(schema)s ) """ COLUMN = """Column(%(name)r, %(type)s%(constraints)s%(args)s)""" FOREIGN_KEY = """ForeignKeyConstraint(%(names)s, %(specs)s, name=%(name)s)""" INDEX = """Index(%(name)s, %(columns)s, unique=%(unique)s)""" HEADER_DECL = """#autogenerated by sqlautocode from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation engine = create_engine('%s') DeclarativeBase = declarative_base() metadata = DeclarativeBase.metadata metadata.bind = engine """ EXAMPLE_DECL = """#example on how to query your Schema from sqlalchemy.orm import sessionmaker session = sessionmaker(bind=engine)() objs = session.query(%s).all() print 'All %s objects: %%s'%%objs """ INTERACTIVE = """ print 'Trying to start IPython shell...', try: from IPython.Shell import IPShellEmbed print 'Success! Press <ctrl-d> to exit.' print 'Available models:%%s'%%%s print '\\nTry something like: session.query(%s).all()' ipshell = IPShellEmbed() ipshell() except: 'Failed. please easy_install ipython' """
#!/usr/bin/env python # encoding: utf-8 """A ${VISUAL} placeholder that will use the text that was last visually selected and insert it here. If there was no text visually selected, this will be the empty string. """ import re import textwrap from UltiSnips.indent_util import IndentUtil from UltiSnips.text_objects.transformation import TextObjectTransformation from UltiSnips.text_objects.base import NoneditableTextObject _REPLACE_NON_WS = re.compile(r"[^ \t]") class Visual(NoneditableTextObject, TextObjectTransformation): """See module docstring.""" def __init__(self, parent, token): # Find our containing snippet for visual_content snippet = parent while snippet: try: self._text = snippet.visual_content.text self._mode = snippet.visual_content.mode break except AttributeError: snippet = snippet._parent # pylint:disable=protected-access if not self._text: self._text = token.alternative_text self._mode = "v" NoneditableTextObject.__init__(self, parent, token) TextObjectTransformation.__init__(self, token) def _update(self, done, buf): if self._mode == "v": # Normal selection. text = self._text else: # Block selection or line selection. text_before = buf[self.start.line][: self.start.col] indent = _REPLACE_NON_WS.sub(" ", text_before) iu = IndentUtil() indent = iu.indent_to_spaces(indent) indent = iu.spaces_to_indent(indent) text = "" for idx, line in enumerate(textwrap.dedent(self._text).splitlines(True)): if idx != 0: text += indent text += line text = text[:-1] # Strip final '\n' text = self._transform(text) self.overwrite(buf, text) self._parent._del_child(self) # pylint:disable=protected-access return True
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "VariableDepthRiverbed2D.h" template<> InputParameters validParams<VariableDepthRiverbed2D>() { InputParameters params = validParams<Function>(); // Parameters params.addParam<Real>("xmin", 0., "Minimum value"); params.addParam<Real>("xmax", 1., "Maximum value"); params.addParam<Real>("ymin", 0., "Minimum value"); params.addParam<Real>("ymax", 1., "Maximum value"); return params; } VariableDepthRiverbed2D::VariableDepthRiverbed2D(const InputParameters & parameters) : Function(parameters), // parameters _xmin(getParam<Real>("xmin")), _xmax(getParam<Real>("xmax")), _ymin(getParam<Real>("ymin")), _ymax(getParam<Real>("ymax")) {} Real VariableDepthRiverbed2D::value(Real /*t*/, const Point & p) { if ( p(0)<_xmin || p(1)<_ymin ) return 0.; else if ( p(0)>_xmax || p(1)>_ymax ) return 0.; else return std::sin(libMesh::pi*(p(0)-_xmin)/(_xmax-_xmin))*std::sin(libMesh::pi*(p(1)-_ymin)/(_ymax-_ymin)); } RealVectorValue VariableDepthRiverbed2D::gradient(Real /*t*/, const Point & p) { return 0.; }
// <copyright file="DisplaySetting.cs" company="Logikfabrik"> // Copyright (c) 2016-2018 anton(at)logikfabrik.se. Licensed under the MIT license. // </copyright> namespace Logikfabrik.Overseer.WPF { using System; using System.Windows; using JetBrains.Annotations; using Microsoft.Win32; /// <summary> /// The <see cref="DisplaySetting" /> class. /// </summary> // ReSharper disable once InheritdocConsiderUsage public class DisplaySetting : IDisplaySetting { /// <summary> /// Initializes a new instance of the <see cref="DisplaySetting" /> class. /// </summary> [UsedImplicitly] public DisplaySetting() { SystemEvents.DisplaySettingsChanged += (sender, args) => { OnDisplaySettingsChanged(EventArgs.Empty); }; } /// <inheritdoc /> public event EventHandler DisplaySettingsChanged; /// <inheritdoc /> public Rect WorkArea => SystemParameters.WorkArea; /// <summary> /// Raises the <see cref="DisplaySettingsChanged" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected virtual void OnDisplaySettingsChanged(EventArgs e) { DisplaySettingsChanged?.Invoke(this, e); } } }
# This Python file uses the following encoding: cp1252 ''' Created on 11/11/2013 @author: mmpe Use string matching instead ''' from heapq import heappush, heappop import sys import numpy as np from mmpe.cython_compile.cython_compile import cython_compile class Score(object): def __init__(self): pass def get_score(self, a, b): if a == b: return 1 elif a.lower() == b.lower(): return 0.9 else: return 0 class StringDistance(object): def __init__(self, score_function): self.score_function = score_function def get_score(self, A, B): scoreboard = np.zeros((len(A) + 1 , len(B) + 1)) scoreboard[:, 0] = np.arange(len(A) + 1) scoreboard[0, :] = np.arange(len(B) + 1) for i, a in enumerate(A, 1): for j, b in enumerate(B, 1): distance = 1 - self.score_function(a, b) scoreboard[i, j] = min([scoreboard[i - 1, j] + 1, scoreboard[i, j - 1] + 1, scoreboard[i - 1, j - 1] + distance]) #print ("%s[%s], %s[%s]: %.3f" % (A, a, B, b, scoreboard[i, j])) #print ("\n".join([str(["%.3f" % v for v in row]) for row in scoreboard])) #print () return scoreboard[i, j] def score_lst_sorted(self, string, lst, thresshold=0, include_scores=False): score_lst = [] for l in lst: score = self.get_score(string, l) / len(string) if score <= thresshold: heappush(score_lst, (score, l)) if include_scores: return [(-score, string) for score, string in [heappop(score_lst) for _ in range(len(score_lst))]] else: return [string for _, string in [heappop(score_lst) for _ in range(len(score_lst))]] def score_dict(self, string, lst, thresshold=0): score_dict = {} for l in lst: score_dict[l] = self.get_score(string, l) / len(string) return score_dict class SmartDistance(StringDistance): def __init__(self, special_scores=[]): self.special_scores = {} for a, b, score in special_scores: if a > b: a, b = b, a if a not in self.special_scores: self.special_scores[a] = {} self.special_scores[a][b] = score def score_function(a, b): if a == b: return 1 elif a.lower() == b.lower(): return 0.9 try: if a > b: a, b = b, a return self.special_scores[a][b] except KeyError: return .000 StringDistance.__init__(self, score_function) #print (SmartMatch([(u"ø", "o", 1)]).sort_lst("Ford", ["Porche", "ford", "opel", "Opel", "Fo rd", "Førd"], .3))
import pytest import smartsheet @pytest.mark.usefixtures("smart_setup") class TestFavorites: def test_add_favorites(self, smart_setup): smart = smart_setup['smart'] action = smart.Favorites.add_favorites([ smart.models.Favorite({ 'object_id': smart_setup['folder'].id, 'type': 'folder' }), smart.models.Favorite({ 'object_id': smart_setup['sheet'].id, 'type': 'sheet' }) ]) favs = action.result assert action.message == 'SUCCESS' def test_list_favorites(self, smart_setup): smart = smart_setup['smart'] action = smart.Favorites.list_favorites() favs = action.result assert action.request_response.status_code == 200 assert action.total_count > 0 assert isinstance(favs[0], smart.models.favorite.Favorite) def test_remove_favorites(self, smart_setup): smart = smart_setup['smart'] action = smart.Favorites.remove_favorites('sheet', smart_setup['sheet'].id) assert action.message == 'SUCCESS'
# Copyright 2019 Kitti Upariphutthiphong <kittiu@ecosoft.co.th> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class HrExpense(models.Model): _inherit = 'hr.expense' advance = fields.Boolean( string='Employee Advance', default=False, ) @api.multi @api.constrains('advance') def _check_advance(self): for expense in self.filtered('advance'): emp_advance = self.env.ref('hr_expense_advance_clearing.' 'product_emp_advance') if not emp_advance.property_account_expense_id: raise ValidationError( _('Employee advance product has no payable account')) if expense.product_id != emp_advance: raise ValidationError( _('Employee advance, selected product is not valid')) if expense.tax_ids: raise ValidationError( _('Employee advance, all taxes must be removed')) if expense.payment_mode != 'own_account': raise ValidationError( _('Employee advance, paid by must be employee')) return True @api.onchange('advance') def onchange_advance(self): self.tax_ids = False self.payment_mode = 'own_account' if self.advance: self.product_id = self.env.ref( 'hr_expense_advance_clearing.product_emp_advance') else: self.product_id = False @api.multi def _get_account_move_line_values(self): move_line_values_by_expense = super()._get_account_move_line_values() # Only when do the clearing, change cr payable to cr advance emp_advance = self.env.ref('hr_expense_advance_clearing.' 'product_emp_advance') sheets = self.mapped('sheet_id').filtered('advance_sheet_id') sheets_x = sheets.filtered(lambda x: x.advance_sheet_residual <= 0.0) if sheets_x: # Advance Sheets with no clearing residual left raise ValidationError(_('Advance: %s has no amount to clear') % ', '.join(sheets_x.mapped('name'))) for sheet in sheets: advance_to_clear = sheet.advance_sheet_residual for expense_id, move_lines in move_line_values_by_expense.items(): payable_move_line = False for move_line in move_lines: credit = move_line['credit'] if not credit: continue # cr payable -> cr advance remain_payable = 0.0 if credit > advance_to_clear: remain_payable = credit - advance_to_clear move_line['credit'] = advance_to_clear advance_to_clear = 0.0 # extra payable line payable_move_line = move_line.copy() payable_move_line['credit'] = remain_payable else: advance_to_clear -= credit # advance line move_line['account_id'] = \ emp_advance.property_account_expense_id.id if payable_move_line: move_lines.append(payable_move_line) return move_line_values_by_expense
from assnet.storage import Storage from assnet.users import User from unittest import TestCase from tempfile import mkdtemp import shutil class UsersTest(TestCase): def setUp(self): self.root = mkdtemp(prefix='assnet_test_root') self.storage = Storage.create(self.root) def tearDown(self): if self.root: shutil.rmtree(self.root) def test_password(self): u = User(self.storage, 'penguin') assert not u.is_valid_password('hello') self.assertRaises(AssertionError, u.is_valid_password, None) self.assertRaises(AssertionError, u.is_valid_password, False) assert not u.is_valid_password('') u.password = 'hello' assert u.is_valid_password('hello') assert not u.is_valid_password('HELLO') assert not u.is_valid_password('') u.save() assert u.password is True self.assertRaises(AssertionError, u.is_valid_password, True) assert u.is_valid_password('hello') assert not u.is_valid_password('HELLO') assert not u.is_valid_password('') u = User(self.storage, 'penguin') u.read() assert u.password is True assert u.is_valid_password('hello') assert not u.is_valid_password('HELLO') assert not u.is_valid_password('') # Set the password to the same value. # If the salts and hashed passwords are the same, either our hashing # algorithm is weak or it's the end of the word. password1 = u.data['auth']['password'] salt1 = u.data['auth']['salt'] u.password = 'hello' u.save() password2 = u.data['auth']['password'] salt2 = u.data['auth']['salt'] assert password1 != password2 assert salt1 != salt2 def test_key(self): u1 = User(self.storage, 'penguin') u1.read() assert u1.key is None u1.gen_key() u1.save() u2 = User(self.storage, 'penguin') u2.read() assert len(u2.key) u2.gen_key() assert u2.key != u1.key
<!DOCTYPE HTML> <html> <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=1000870 --> <head> <meta charset="utf-8"> <title>Test for Bug 1000870</title> <meta name="author" content="Maksim Lebedev" /> <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script> <script type="text/javascript" src="mochitest_support_external.js"></script> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <script type="text/javascript"> SimpleTest.waitForExplicitFinish(); function startTest() { runTestInNewWindow("pointerevent_pointerleave_does_not_bubble-manual.html"); } function executeTest(int_win) { sendTouchEvent(int_win, "target0", "touchstart"); sendTouchEvent(int_win, "target0", "touchend"); } </script> </head> <body> </body> </html>
import sys import textwrap import pkg_resources import pip.download from pip.basecommand import Command from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from distutils.version import StrictVersion, LooseVersion class SearchCommand(Command): name = 'search' usage = '%prog QUERY' summary = 'Search PyPI' def __init__(self): super(SearchCommand, self).__init__() self.parser.add_option( '--index', dest='index', metavar='URL', default='http://pypi.python.org/pypi', help='Base URL of Python Package Index (default %default)') def run(self, options, args): if not args: logger.warn('ERROR: Missing required argument (search query).') return query = args index_url = options.index pypi_hits = self.search(query, index_url) hits = transform_hits(pypi_hits) terminal_width = None if sys.stdout.isatty(): terminal_width = get_terminal_size()[0] print_results(hits, terminal_width=terminal_width) def search(self, query, index_url): pypi = xmlrpclib.ServerProxy(index_url, pip.download.xmlrpclib_transport) hits = pypi.search({'name': query, 'summary': query}, 'or') return hits def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = {} for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] score = hit['_pypi_ordering'] if name not in packages.keys(): packages[name] = {'name': name, 'summary': summary, 'versions': [version], 'score': score} else: packages[name]['versions'].append(version) # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary packages[name]['score'] = score # each record has a unique name now, so we will convert the dict into a list sorted by score package_list = sorted(packages.values(), key=lambda x: x['score'], reverse=True) return package_list def print_results(hits, name_column_width=25, terminal_width=None): installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' if terminal_width is not None: # wrap and indent summary to fit terminal summary = textwrap.wrap(summary, terminal_width - name_column_width - 5) summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) line = '%s - %s' % (name.ljust(name_column_width), summary) try: logger.notify(line) if name in installed_packages: dist = pkg_resources.get_distribution(name) logger.indent += 2 try: latest = highest_version(hit['versions']) if dist.version == latest: logger.notify('INSTALLED: %s (latest)' % dist.version) else: logger.notify('INSTALLED: %s' % dist.version) logger.notify('LATEST: %s' % latest) finally: logger.indent -= 2 except UnicodeEncodeError: pass def compare_versions(version1, version2): try: return cmp(StrictVersion(version1), StrictVersion(version2)) # in case of abnormal version number, fall back to LooseVersion except ValueError: return cmp(LooseVersion(version1), LooseVersion(version2)) def highest_version(versions): return reduce((lambda v1, v2: compare_versions(v1, v2) == 1 and v1 or v2), versions) SearchCommand()
# -*- 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': 'Time Tracking', 'version': '1.0', 'category': 'Human Resources', 'sequence': 23, 'description': """ This module implements a timesheet system. ========================================== Each employee can encode and track their time spent on the different projects. A project is an analytic account and the time spent on a project generates costs on the analytic account. Lots of reporting on time and employee tracking are provided. It is completely integrated with the cost accounting module. It allows you to set up a management by affair. """, 'author': 'OpenERP SA', 'website': 'https://www.odoo.com/page/employees', 'depends': ['account', 'hr', 'base', 'hr_attendance'], 'data': [ 'security/ir.model.access.csv', 'security/hr_timesheet_security.xml', 'hr_timesheet_view.xml', 'wizard/hr_timesheet_sign_in_out_view.xml', 'report/hr_timesheet_report_view.xml', 'hr_timesheet_installer.xml', 'hr_timesheet_data.xml' ], 'demo': ['hr_timesheet_demo.xml'], 'test': [ 'test/hr_timesheet_users.yml', 'test/test_hr_timesheet.yml', 'test/hr_timesheet_demo.yml', ], 'installable': True, 'auto_install': False, }
#!/usr/bin/env python from telegram import TelegramObject class Document(TelegramObject): def __init__(self, file_id, thumb, file_name=None, mime_type=None, file_size=None): self.file_id = file_id self.thumb = thumb self.file_name = file_name self.mime_type = mime_type self.file_size = file_size @staticmethod def de_json(data): if 'thumb' in data: from telegram import PhotoSize thumb = PhotoSize.de_json(data['thumb']) else: thumb = None return Document(file_id=data.get('file_id', None), thumb=thumb, file_name=data.get('file_name', None), mime_type=data.get('mime_type', None), file_size=data.get('file_size', None)) def to_dict(self): data = {'file_id': self.file_id} if self.thumb: data['thumb'] = self.thumb.to_dict() if self.file_name: data['file_name'] = self.file_name if self.mime_type: data['mime_type'] = self.mime_type if self.file_size: data['file_size'] = self.file_size return data
import pytest from sslyze.cli.json_output import _ServerConnectivityInfoAsJson from sslyze.server_connectivity import ServerConnectivityTester, ClientAuthRequirementEnum from sslyze.server_setting import ServerNetworkLocationViaDirectConnection from tests.markers import can_only_run_on_linux_64 from tests.openssl_server import ModernOpenSslServer, ClientAuthConfigEnum, LegacyOpenSslServer class TestClientAuthentication: def test_optional_client_authentication(self): # Given a server that requires a client certificate server_location = ServerNetworkLocationViaDirectConnection.with_ip_address_lookup( hostname="client.badssl.com", port=443 ) # When testing connectivity against it server_info = ServerConnectivityTester().perform(server_location) # It succeeds assert server_info.tls_probing_result assert server_info.tls_probing_result.highest_tls_version_supported assert server_info.tls_probing_result.cipher_suite_supported # And it detected the client authentication assert server_info.tls_probing_result.client_auth_requirement == ClientAuthRequirementEnum.OPTIONAL # And the result can be converted to JSON server_info_as_json = _ServerConnectivityInfoAsJson.from_orm(server_info) assert server_info_as_json.json() @can_only_run_on_linux_64 class TestClientAuthenticationWithLocalServer: def test_optional_client_auth(self): # Given a server that supports optional client authentication with ModernOpenSslServer(client_auth_config=ClientAuthConfigEnum.OPTIONAL) as server: server_location = ServerNetworkLocationViaDirectConnection( hostname=server.hostname, port=server.port, ip_address=server.ip_address ) server_info = ServerConnectivityTester().perform(server_location) # SSLyze correctly detects that client auth is optional assert server_info.tls_probing_result.client_auth_requirement == ClientAuthRequirementEnum.OPTIONAL def test_required_client_auth_tls_1_2(self): # Given a TLS 1.2 server that requires client authentication with LegacyOpenSslServer(client_auth_config=ClientAuthConfigEnum.REQUIRED) as server: server_location = ServerNetworkLocationViaDirectConnection( hostname=server.hostname, port=server.port, ip_address=server.ip_address ) server_info = ServerConnectivityTester().perform(server_location) # SSLyze correctly detects that client auth is required assert server_info.tls_probing_result.client_auth_requirement == ClientAuthRequirementEnum.REQUIRED @pytest.mark.skip(msg="Client auth config detection with TLS 1.3 is broken; fix me") def test_required_client_auth_tls_1_3(self): # Given a TLS 1.3 server that requires client authentication with ModernOpenSslServer(client_auth_config=ClientAuthConfigEnum.REQUIRED) as server: server_location = ServerNetworkLocationViaDirectConnection( hostname=server.hostname, port=server.port, ip_address=server.ip_address ) server_info = ServerConnectivityTester().perform(server_location) # SSLyze correctly detects that client auth is required assert server_info.tls_probing_result.client_auth_requirement == ClientAuthRequirementEnum.REQUIRED
define(function (require) { 'use strict'; var template = require("../../text!../../../templates/cartModal.html"); var CartModalView = Backbone.View.extend({ template: _.template(template), initialize: function (/*options*/) { // this.main = options.main; }, events: { }, render: function () { $(this.el).html(this.template()); return this; } }); return CartModalView; });
--- layout: default --- <div id="main" role="main"> {% include topnav.html %} <div class="page"> {% if page.title %} <h1 class="page__title">{{ page.title }}</h1> {% endif %} {% if page.subtitle %} <p class="page__subtitle">{{ page.subtitle }}</p> {% endif %} {{ content }} </div> </div>
from django.conf import settings from django.http import HttpResponse from django.utils.translation import ugettext as _ def basic_challenge(realm=None): if realm is None: realm = getattr(settings, 'WWW_AUTHENTICATION_REALM', _('Restricted Access')) # TODO: Make a nice template for a 401 message? response = HttpResponse(_('Authorization Required'), content_type="text/plain") response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm) response.status_code = 401 return response def basic_authenticate(authentication): # Taken from paste.auth (authmeth, auth) = authentication.split(' ',1) if 'basic' != authmeth.lower(): return None auth = auth.strip().decode('base64') username, password = auth.split(':',1) AUTHENTICATION_USERNAME = getattr(settings, 'BASIC_WWW_AUTHENTICATION_USERNAME') AUTHENTICATION_PASSWORD = getattr(settings, 'BASIC_WWW_AUTHENTICATION_PASSWORD') return username == AUTHENTICATION_USERNAME and password == AUTHENTICATION_PASSWORD class BasicAuthenticationMiddleware(object): def process_request(self, request): if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False): return if 'HTTP_AUTHORIZATION' not in request.META: return basic_challenge() authenticated = basic_authenticate(request.META['HTTP_AUTHORIZATION']) if authenticated: return return basic_challenge()
/* ---------------------------------------------------------------------- * Copyright (C) 2013 ARM Limited. All rights reserved. * * $Date: 12. September 2013 * $Revision: V1.00 * * Project: USB Full/Low-Speed Driver Header for ST STM32F10x * -------------------------------------------------------------------- */ #ifndef __USBREG_H #define __USBREG_H #define REG(x) (*((volatile unsigned int *)(x))) #define USB_BASE_ADDR 0x40005C00 /* USB Registers Base Address */ #define USB_PMA_ADDR 0x40006000 /* USB Packet Memory Area Address */ /* Common Registers */ #define CNTR REG(USB_BASE_ADDR + 0x40) /* Control Register */ #define ISTR REG(USB_BASE_ADDR + 0x44) /* Interrupt Status Register */ #define FNR REG(USB_BASE_ADDR + 0x48) /* Frame Number Register */ #define DADDR REG(USB_BASE_ADDR + 0x4C) /* Device Address Register */ #define BTABLE REG(USB_BASE_ADDR + 0x50) /* Buffer Table Address Register */ /* CNTR: Control Register Bit Definitions */ #define CNTR_CTRM 0x8000 /* Correct Transfer Interrupt Mask */ #define CNTR_PMAOVRM 0x4000 /* Packet Memory Aerea Over/underrun Interrupt Mask */ #define CNTR_ERRM 0x2000 /* Error Interrupt Mask */ #define CNTR_WKUPM 0x1000 /* Wake-up Interrupt Mask */ #define CNTR_SUSPM 0x0800 /* Suspend Mode Interrupt Mask */ #define CNTR_RESETM 0x0400 /* USB Reset Interrupt Mask */ #define CNTR_SOFM 0x0200 /* Start of Frame Interrupt Mask */ #define CNTR_ESOFM 0x0100 /* Expected Start of Frame Interrupt Mask */ #define CNTR_RESUME 0x0010 /* Resume Request */ #define CNTR_FSUSP 0x0008 /* Force Suspend */ #define CNTR_LPMODE 0x0004 /* Low-power Mode */ #define CNTR_PDWN 0x0002 /* Power Down */ #define CNTR_FRES 0x0001 /* Force USB Reset */ /* ISTR: Interrupt Status Register Bit Definitions */ #define ISTR_CTR 0x8000 /* Correct Transfer */ #define ISTR_PMAOVR 0x4000 /* Packet Memory Aerea Over/underrun */ #define ISTR_ERR 0x2000 /* Error */ #define ISTR_WKUP 0x1000 /* Wake-up */ #define ISTR_SUSP 0x0800 /* Suspend Mode */ #define ISTR_RESET 0x0400 /* USB Reset */ #define ISTR_SOF 0x0200 /* Start of Frame */ #define ISTR_ESOF 0x0100 /* Expected Start of Frame */ #define ISTR_DIR 0x0010 /* Direction of Transaction */ #define ISTR_EP_ID 0x000F /* EndPoint Identifier */ /* FNR: Frame Number Register Bit Definitions */ #define FNR_RXDP 0x8000 /* D+ Data Line Status */ #define FNR_RXDM 0x4000 /* D- Data Line Status */ #define FNR_LCK 0x2000 /* Locked */ #define FNR_LSOF 0x1800 /* Lost SOF */ #define FNR_FN 0x07FF /* Frame Number */ /* DADDR: Device Address Register Bit Definitions */ #define DADDR_EF 0x0080 /* Enable Function */ #define DADDR_ADD 0x007F /* Device Address */ /* EndPoint Registers */ #define EPxREG(x) REG(USB_BASE_ADDR + 4*(x)) /* EPxREG: EndPoint Registers Bit Definitions */ #define EP_CTR_RX 0x8000 /* Correct RX Transfer */ #define EP_DTOG_RX 0x4000 /* RX Data Toggle */ #define EP_STAT_RX 0x3000 /* RX Status */ #define EP_SETUP 0x0800 /* EndPoint Setup */ #define EP_TYPE 0x0600 /* EndPoint Type */ #define EP_KIND 0x0100 /* EndPoint Kind */ #define EP_CTR_TX 0x0080 /* Correct TX Transfer */ #define EP_DTOG_TX 0x0040 /* TX Data Toggle */ #define EP_STAT_TX 0x0030 /* TX Status */ #define EP_EA 0x000F /* EndPoint Address */ /* EndPoint Register Mask (No Toggle Fields) */ #define EP_MASK (EP_CTR_RX|EP_SETUP|EP_TYPE|EP_KIND|EP_CTR_TX|EP_EA) /* EP_TYPE: EndPoint Types */ #define EP_BULK 0x0000 /* BULK EndPoint */ #define EP_CONTROL 0x0200 /* CONTROL EndPoint */ #define EP_ISOCHRONOUS 0x0400 /* ISOCHRONOUS EndPoint */ #define EP_INTERRUPT 0x0600 /* INTERRUPT EndPoint */ /* EP_KIND: EndPoint Kind */ #define EP_DBL_BUF EP_KIND /* Double Buffer for Bulk Endpoint */ #define EP_STATUS_OUT EP_KIND /* Status Out for Control Endpoint */ /* EP_STAT_TX: TX Status */ #define EP_TX_DIS 0x0000 /* Disabled */ #define EP_TX_STALL 0x0010 /* Stalled */ #define EP_TX_NAK 0x0020 /* NAKed */ #define EP_TX_VALID 0x0030 /* Valid */ /* EP_STAT_RX: RX Status */ #define EP_RX_DIS 0x0000 /* Disabled */ #define EP_RX_STALL 0x1000 /* Stalled */ #define EP_RX_NAK 0x2000 /* NAKed */ #define EP_RX_VALID 0x3000 /* Valid */ /* Endpoint Buffer Descriptor */ typedef struct _EP_BUF_DSCR { unsigned int ADDR_TX; unsigned int COUNT_TX; unsigned int ADDR_RX; unsigned int COUNT_RX; } EP_BUF_DSCR; #define EP_ADDR_MASK 0xFFFE /* Address Mask */ #define EP_COUNT_MASK 0x03FF /* Count Mask */ #endif /* __USBREG_H */
<!doctype html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <meta http-equiv="content-script-type" content="text/javascript"> <meta http-equiv="content-style-type" content="text/css"> <link rel="stylesheet" type="text/css" href="style.css"> <title>Sections</title> </head> <body class="navigation"> <ul class="navigation"> <li><a target="main" href="main.html">Main</a></li> <li><a target="main" href="results.html">Results</a></li> <li><a target="main" href="FAQ.html">FAQ</a></li> <li><a href="manual/sections.html">Manual</a></li> <li><a target="main" href="quality.html">Quality</a></li> <li><a target="main" href="screenshots.html">Screenshots</a></li> <li><a target="main" href="testimonials.html">Testimonials</a></li> <li><a target="main" href="license.html">License</a></li> <li><a target="main" href="downloads.html">Downloads</a></li> <li><a target="main" href="feedback.html">Feedback</a></li> <li><a target="main" href="acknowledgements.html">Ack'ments</a></li> <li><a target="main" href="alternatives.html">Alternatives</a></li> </ul> <p> <center> <small>More Android app protection:</small> <p> <a href="http://www.guardsquare.com/dexguard" target="_top"> <img src="dexguard.png" width="88" height="55" alt="DexGuard" /></a> <p> <small>With support of</small> <p> <a href="http://www.guardsquare.com/" target="_top"> <img src="guardsquare.png" width="88" height="25" alt="GuardSquare" /></a> <p> <a href="http://sourceforge.net/projects/proguard/" target="other"> <img src="sflogo.png" width="88" height="31" alt="SourceForge" /></a> </center> </body> </html>
# -*- coding: utf-8 -*- # $Id$ # # Copyright (c) 2013 # # This file is part of ECSpooler. import os import unittest import tempfile import errno #from lib.util import auth from lib.util import utils class testAuth(unittest.TestCase): """ """ def setUp(self): """ """ def tearDown(self): """ """ class testUtils(unittest.TestCase): """ """ __pid_filename = os.path.join(tempfile.gettempdir(), 'test_utils.pid') def setUp(self): """ """ def tearDown(self): """ """ try: os.remove(self.__pid_filename) except OSError, exc: if exc.errno == errno.ENOENT: pass else: raise def test_write_pid_file(self): """ """ utils.write_pid_file(self.__pid_filename) self.assertTrue(os.path.exists(self.__pid_filename)) def test_read_pid_file_None(self): """ """ pid = utils.read_pid_file(self.__pid_filename) self.assertIsNone(pid) def test_read_pid_file(self): """ """ utils.write_pid_file(self.__pid_filename) pid = utils.read_pid_file(self.__pid_filename) self.assertEqual(pid, os.getpid()) def test_remove_pid_file(self): """ """ utils.write_pid_file(self.__pid_filename) self.assertTrue(os.path.exists(self.__pid_filename)) utils.remove_pid_file(self.__pid_filename) self.assertFalse(os.path.exists(self.__pid_filename)) def test_suite(): """ """ from unittest import TestSuite, makeSuite suite = TestSuite() suite.addTest(makeSuite(testAuth)) suite.addTest(makeSuite(testUtils)) return suite # -- main --------------------------------------------------------------------- if __name__ == '__main__': TestRunner = unittest.TextTestRunner suite = test_suite() TestRunner().run(suite)
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ jstestdriver.plugins.DefaultPlugin = function(fileLoaderPlugin, testRunnerPlugin, assertsPlugin, testCaseManagerPlugin) { this.fileLoaderPlugin_ = fileLoaderPlugin; this.testRunnerPlugin_ = testRunnerPlugin; this.assertsPlugin_ = assertsPlugin; this.testCaseManagerPlugin_ = testCaseManagerPlugin; }; jstestdriver.plugins.DefaultPlugin.prototype.name = 'defaultPlugin'; jstestdriver.plugins.DefaultPlugin.prototype.loadSource = function(file, onSourceLoaded) { return this.fileLoaderPlugin_.loadSource(file, onSourceLoaded); }; jstestdriver.plugins.DefaultPlugin.prototype.runTestConfiguration = function(testRunConfiguration, onTestDone, onTestRunConfigurationComplete) { return this.testRunnerPlugin_.runTestConfiguration(testRunConfiguration, onTestDone, onTestRunConfigurationComplete); }; jstestdriver.plugins.DefaultPlugin.prototype.isFailure = function(exception) { return this.assertsPlugin_.isFailure(exception); }; jstestdriver.plugins.DefaultPlugin.prototype.getTestRunsConfigurationFor = function(testCaseInfos, expressions, testRunsConfiguration) { return this.testCaseManagerPlugin_.getTestRunsConfigurationFor(testCaseInfos, expressions, testRunsConfiguration); }; jstestdriver.plugins.DefaultPlugin.prototype.onTestsStart = jstestdriver.EMPTY_FUNC; jstestdriver.plugins.DefaultPlugin.prototype.onTestsFinish = jstestdriver.EMPTY_FUNC;
/* * Copyright 2004-2009 unitarou <boss@unitarou.org>. * All rights reserved. * * This program and the accompanying materials are made available under the terms of * the Common Public License v1.0 which accompanies this distribution, * and is available at http://opensource.org/licenses/cpl.php * * Contributors: * unitarou - initial API and implementation */ package org.unitarou.sgf.type; import org.unitarou.lang.ArgumentChecker; import org.unitarou.lang.Strings; import org.unitarou.sgf.SgfId; import org.unitarou.sgf.ValueType; /** * @author UNITAROU &lt;boss@unitarou.org&gt; */ public class None implements TypedString<None> { /** —Bˆê‚̃Cƒ“ƒXƒ^ƒ“ƒX‚Å‚·B*/ static public final None INSTANCE = new None(); /** * */ private None() { super(); } /* (non-Javadoc) * @see org.unitarou.sgf.type.Type#getValue() */ public String getString() { return Strings.EMPTY; } /** * @param value * @return ‹ó•¶Žš‚̏ꍇ‚Étrue */ public boolean isValid(String value) { return (Strings.EMPTY.equals(value)); } /* * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(None o) { return 0; } /* * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return this == obj; } /* * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return 0; } /** * {@link SgfId#valueType()}‚ª{@link ValueType#NONE}‚̂ݎ󂯕t‚¯‚Ü‚·B * * @see org.unitarou.sgf.type.TypedString#acceptable(org.unitarou.sgf.SgfId) */ public boolean acceptable(SgfId sgfId) { ArgumentChecker.throwIfNull(sgfId); return ValueType.NONE.equals(sgfId.valueType()); } }
#!/usr/bin/env python # encoding: utf-8 """ Test script for generating a set of isochrones and plotting them. History ------- 2011-12-29 - Created by Jonathan Sick """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from pysps import fsps from pysps import splib def main(): imf, imf1, imf2, imf3, vdmc, mdave, dell, delt, sbss, fbhb, pagb = \ 0,1.3,2.3,2.3,0.08,0.5,0.,0.,0.,0.,1. fsps.driver.setup(1, 0) fsps.driver.setup_all_ssp(imf, imf1, imf2, imf3, vdmc, mdave, dell, delt, sbss, fbhb, pagb) tt = 40 isocSet = [] # for zz in range(1,23,4): #for zz in range(19,20): T, Z, isocData = compute_isochrone(tt, zz) isocSet.append((T, Z, isocData)) print T, Z plot_isochrone_set_weights(isocSet, 5, 7, r"$J-K_s$", r"$K_s$", "isoc_test_jk", dist=24.5, xlim=(0.,2.),ylim=(24,12)) plot_isochrone_set_weights(isocSet, 9,11, r"$g-i$", r"$i$", "isoc_test_gi", dist=24.5,xlim=(-1,5),ylim=(24,12)) def compute_isochrone(tt, zz): """Compute and package outputs for isochrone of age and metallicity indices tt and zz.""" nBands = fsps.driver.get_n_bands() nMass = fsps.driver.get_n_masses_isochrone(zz, tt) # n masses for this isoc time, Z, massInit, logL, logT, logg, ffco, phase, wght, isocMags = \ fsps.driver.get_isochrone(zz, tt, nMass, nBands) isocData = package_isochrone(massInit, logL, logT, logg, ffco, phase, wght, isocMags) return time, Z, isocData def package_isochrone(massInit, logL, logT, logg, ffco, phase, wght, isocMags): """Repackage isochrone outputs into record arrays where the long dimension is mass.""" nMass, nBands = isocMags.shape bandNames = [] for bandSet in splib.FILTER_LIST: bandNames.append(bandSet[1]) colDefs = np.dtype([('mass_init',np.float),('logL',np.float), ('logT',np.float),('logg',np.float),('ffco',np.float), ('phase',np.int),('wght',np.float),('mag',np.float,nBands)]) isocData = np.empty(nMass, dtype=colDefs) isocData['mass_init'] = massInit isocData['logL'] = logL isocData['logT'] = logT isocData['logg'] = logg isocData['ffco'] = ffco isocData['phase'] = phase isocData['wght'] = wght isocData['mag'] = isocMags print "isocMags.shape", isocMags.shape print "isocData['mag'].shape", isocData['mag'].shape return isocData def plot_isochrone_set(isocList, mag1Index, mag2Index, xLabel, yLabel, plotPath, dist=0., xlim=None, ylim=None): """Plot a mag1 - mag2 vs mag2 CMD for the set of isochrones.""" Z = [] T = [] colour = [] mag = [] for zz, tt, isocData in isocList: Z.append(zz) T.append(tt) colour.append(isocData['mag'][:,mag1Index] - isocData['mag'][:,mag2Index]) mag.append(isocData['mag'][:,mag2Index]) fig = plt.figure(figsize=(6,6)) ax = fig.add_axes((0.2,0.2,0.75,0.75)) for i in xrange(len(Z)): ax.plot(colour[i], mag[i]+dist, ls='-', lw=0.5, marker='o', ms=0.5) # , color='k' if xlim is not None: ax.set_xlim(xlim[0],xlim[1]) if ylim is not None: ax.set_ylim(ylim[0],ylim[1]) else: ylim = ax.get_ylim() ax.set_ylim(ylim[1],ylim[0]) ax.set_xlabel(xLabel) ax.set_ylabel(yLabel) fig.savefig(plotPath+".pdf", format='pdf') def plot_isochrone_set_weights(isocList, mag1Index, mag2Index, xLabel, yLabel, plotPath, dist=0., xlim=None, ylim=None): """Plot a mag1 - mag2 vs mag2 CMD for the set of isochrones.""" Z = [] T = [] colour = [] mag = [] weights = [] masses = [] phases = [] for zz, tt, isocData in isocList: Z.append(zz) T.append(tt) colour.append(isocData['mag'][:,mag1Index] - isocData['mag'][:,mag2Index]) mag.append(isocData['mag'][:,mag2Index]) weights.append(isocData['wght']) masses.append(isocData['mass_init']) phases.append(isocData['phase']) print "mag length", len(isocData['mag'][:,mag2Index]) print "masses length", len(isocData['mass_init']) fig = plt.figure(figsize=(6,6)) ax = fig.add_axes((0.2,0.2,0.75,0.75)) for i in xrange(len(Z)): for j in xrange(len(weights[i])): print masses[i][j], mag[i][j]+dist, weights[i][j], phases[i][j] ax.plot(colour[i], mag[i]+dist, ls='-', lw=2, marker='None', ms=0., alpha=0.25) # , color='k' ax.scatter(colour[i], mag[i]+dist, s=10., c=weights[i], marker='o', cmap=mpl.cm.jet, norm=mpl.colors.Normalize(), zorder=10) if xlim is not None: ax.set_xlim(xlim[0],xlim[1]) if ylim is not None: ax.set_ylim(ylim[0],ylim[1]) else: ylim = ax.get_ylim() ax.set_ylim(ylim[1],ylim[0]) ax.set_xlabel(xLabel) ax.set_ylabel(yLabel) fig.savefig(plotPath+".pdf", format='pdf') if __name__ == '__main__': main()
# # 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. # """ An example of how to use DataFrame for ML. Run with:: bin/spark-submit examples/src/main/python/ml/dataframe_example.py <input_path> """ from __future__ import print_function import os import sys import tempfile import shutil from pyspark.sql import SparkSession from pyspark.mllib.stat import Statistics from pyspark.mllib.util import MLUtils if __name__ == "__main__": if len(sys.argv) > 2: print("Usage: dataframe_example.py <libsvm file>", file=sys.stderr) sys.exit(-1) elif len(sys.argv) == 2: input_path = sys.argv[1] else: input_path = "data/mllib/sample_libsvm_data.txt" spark = SparkSession \ .builder \ .appName("DataFrameExample") \ .getOrCreate() # Load an input file print("Loading LIBSVM file with UDT from " + input_path + ".") df = spark.read.format("libsvm").load(input_path).cache() print("Schema from LIBSVM:") df.printSchema() print("Loaded training data as a DataFrame with " + str(df.count()) + " records.") # Show statistical summary of labels. labelSummary = df.describe("label") labelSummary.show() # Convert features column to an RDD of vectors. features = MLUtils.convertVectorColumnsFromML(df, "features") \ .select("features").rdd.map(lambda r: r.features) summary = Statistics.colStats(features) print("Selected features column with average values:\n" + str(summary.mean())) # Save the records in a parquet file. tempdir = tempfile.NamedTemporaryFile(delete=False).name os.unlink(tempdir) print("Saving to " + tempdir + " as Parquet file.") df.write.parquet(tempdir) # Load the records back. print("Loading Parquet file with UDT from " + tempdir) newDF = spark.read.parquet(tempdir) print("Schema from Parquet:") newDF.printSchema() shutil.rmtree(tempdir) spark.stop()
# Copyright 2010 Bastian Bowe # # This file is part of JayDeBeApi. # JayDeBeApi 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. # # JayDeBeApi 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 JayDeBeApi. If not, see # <http://www.gnu.org/licenses/>. # import sys from setuptools import setup install_requires = [] if not sys.platform.lower().startswith('java'): install_requires.append('JPype1') setup( #basic package data name = 'JayDeBeApi', version = '0.2.0', author = 'Bastian Bowe', author_email = 'bastian.dev@gmail.com', license = 'GNU LGPL', url='https://github.com/baztian/jaydebeapi', description=('Use JDBC database drivers from Python 2/3 or Jython with a DB-API.'), long_description=open('README.rst').read(), keywords = ('db api java jdbc bridge connect sql jpype jython'), classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Java', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Database', 'Topic :: Software Development :: Libraries :: Java Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=['jaydebeapi'], install_requires=install_requires, )
#!/usr/bin/python import argparse import os from subprocess import Popen, PIPE import sys def getHashedPassword(password): p1 = Popen(['openssl', 'passwd', '-1', password], stdout = PIPE) return p1.communicate()[0].decode('UTF-8').strip() if __name__ == '__main__': parser = argparse.ArgumentParser(description=''' This script will set the user's password ''') parser.add_argument('-f', '--filename', default='/etc/shadow', help='Filename to edit') parser.add_argument('-u', '--username', help='Username for password change', required=True) parser.add_argument('-p', '--password', help='New password', required=True) parser.add_argument('-i', '--inplace', action='store_true', help='Edit the file in place') args = parser.parse_args() with file(args.filename) as f: lines = f.readlines() for line, index in zip(lines, range(len(lines))): splitLine = line.split(':') if splitLine[0] == args.username: splitLine[1] = getHashedPassword(args.password) lines[index] = ':'.join(splitLine) if args.inplace: with open(args.filename, 'w') as f: for line in lines: f.write(line) else: for line in lines: print line.strip()
# coding: utf-8 # In this part of the exercise, we now need to put the data which we have procured about the funding levels of the different universities that are located in different cantons onto a canton map. We will do so using Folio and take the example TopoJSON mapping which they use. # In[15]: import folium import pandas as pd # In[1]: # Test seeing Switzerland ch_map = folium.Map(location=[47.3769, 8.5417], tiles='Stamen Toner', zoom_start=13) ch_map.save('stamen_toner.html') ch_map # Now do the TopoJSON overlay # In[61]: # Import the Switzerland map (from the folio pylib notebook) topo_path = r'ch-cantons.topojson.json' # Import our csv file with all of the values for the amounts of the grants data = 'P3_GrantExport.csv' # Insert coordinates that are for Switzerland (i.e. 9.594226,47.525058) ch_map = folium.Map(location=[46.8769, 8.6017], tiles='Mapbox Bright', zoom_start=7) ch_map.choropleth(geo_path=topo_path, topojson='objects.ch-cantons') ch_map.save('ch_map.html') ch_map # In[ ]: # Need to use colors wisely - becaue this is continuous and not descrete, we will be using different shades of green # In[ ]: #Catarina's test import folium import pandas as pd topo_path = r'ch-cantons.topojson.json' grants_data = pd.read_csv(state_unemployment) #Let Folium determine the scale map = folium.Map(location=[47.3769, 8.5417], zoom_start=13) map.choropleth(geo_path=state_geo, data=grants_data, columns=['Canton Shortname', 'Total Sum'], key_on='feature.id', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, legend_name='Total Grants Received (CHF)') map.save('swiss_grants.html')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Crawler for retreiving tweets by ids. File: tweet_crawler.py Author: SpaceLis Email: Wen.Li@tudelft.nl GitHub: http://github.com/spacelis Description: Retreiving tweets by ids. """ #from gevent import monkey #monkey.patch_all() import sys import yaml import time import tweepy as tw #from crawler.actors import Controller #from crawler.readers import CSVReader #from crawler.writers import FileWriter #from crawler import IgnorableError #from crawler import RecoverableError from crawler.utils.tweepy_patch import iter_scoll from examples.utils.tweepy_patch import patchStatus patchStatus() import logging logging.basicConfig(level=logging.INFO) _logger = logging.getLogger(__name__) class Worker(object): """ A worker. """ def __init__(self, cred): """@todo: to be defined1. :args: @todo """ self._oauthhl = tw.OAuthHandler(cred['consumer_key'], cred['consumer_secret']) self._oauthhl.set_access_token(cred['access_token_key'], cred['access_token_secret']) self._client = tw.API(self._oauthhl) assert self._client.verify_credentials(), cred def work_on(self, param): """@todo: Docstring for work_on. :tid: @todo :returns: @todo """ try: for s in iter_scoll(self._client.search, 1000, q=param['hashtag']): yield s._raw except tw.TweepError as e: if e.response.status == 429: nxwin = float(e.response.getheader('X-Rate-Limit-Reset')) retry_in = nxwin + 5 - time.time() time.sleep(retry_in) #_logger.warn('Failed at %s', param) #raise IgnorableError(e) #def console(): #""" running in console #:returns: @todo #""" #if len(sys.argv) != 3: #print >> sys.stderr, 'Usage: tweet_crawler.py <input> <output>' #sys.exit() #with open('cred.yaml') as fin: #cred = yaml.load(fin) #controller = Controller.start(Worker, cred, #CSVReader(sys.argv[1]), #FileWriter(sys.argv[2])) #controller.actor_stopped.wait() def simple(): """ A simple version of crawler. """ if len(sys.argv) != 3: print >> sys.stderr, 'Usage: tweet_crawler.py <input> <output>' sys.exit() with open('cred.yaml') as fin: w = Worker(yaml.load(fin)[0]) with open(sys.argv[1]) as fin: with open(sys.argv[2], 'a') as fout: for line in fin: for s in w.work_on({'hashtag': line.strip()}): fout.write(s) fout.write('\n') if __name__ == '__main__': simple()
package de.bitub.step.p21.di; import org.eclipse.emf.ecore.EPackage; import com.google.inject.Inject; import com.google.inject.Provider; import de.bitub.step.p21.AllP21Entities; import de.bitub.step.p21.mapper.NameToClassifierMapImpl; import de.bitub.step.p21.parser.P21EntityListener; import de.bitub.step.p21.parser.util.IndexUtil; public class P21ParserFactoryImpl implements P21ParserFactory { private final Provider<AllP21Entities> p21IndexProvider; private final Provider<IndexUtil> indexProvider; @Inject public P21ParserFactoryImpl(Provider<AllP21Entities> p21IndexProvider, Provider<IndexUtil> indexProvider) { this.p21IndexProvider = p21IndexProvider; this.indexProvider = indexProvider; } @Override public P21EntityListener createWith(EPackage ePackage) { return new P21EntityListener(p21IndexProvider.get(), indexProvider.get(), new NameToClassifierMapImpl(ePackage)); } }
import sys sys.path.append("../lib") import os import numpy as np from netCDF4 import Dataset from bingrid import NumpyGrid # Open the change file def get_ncdf_mine(nc4path, variable): rootgrp = Dataset(nc4path, "r") latitude = rootgrp.variables['latitude'][:] longitude = rootgrp.variables['longitude'][:] array = rootgrp.variables[variable][:, :] return NumpyGrid.from_regular_axes(array, latitude, longitude) def get_ncdf_cfsr(nc4path, variable): rootgrp = Dataset(nc4path, "r") latitude = rootgrp.variables['Latitude'][:] longitude = rootgrp.variables['Longitude'][:] array = rootgrp.variables[variable][:, :, :] return latitude, longitude, array def write_ncdf(nc4path, variable, units, array, lats, lons): rootgrp = Dataset(nc4path, 'w', format="NETCDF4") day = rootgrp.createDimension('Time', array.shape[0]) lat = rootgrp.createDimension('Latitude', array.shape[1]) lon = rootgrp.createDimension('Longitude', array.shape[2]) latitudes = rootgrp.createVariable("Latitude","f4",("Latitude",)) latitudes.units = "degrees North" longitudes = rootgrp.createVariable("Longitude","f4",("Longitude",)) longitudes.units = "degrees East" values = rootgrp.createVariable(variable, "f4", ("Latitude", "Longitude", "Time")) values.units = units latitudes[:] = lats longitudes[:] = lons values[:, :, :] = array rootgrp.close() def adjust_dailies(variable, units, callback): for year in range(1979, 2010): for month in range(1, 13): print year, month lats, lons, values = get_ncdf_cfsr("/srv/ftp/cfsr/%s-global/%s-%d%02d.nc4" % (variable, variable, year, month), variable) newvalues = np.zeros((values.shape[0], sum((lats > -30) & (lats < 30)), len(lons))) r0 = np.where(lats == max(lats[lats < 30]))[0] for rr in range(newvalues.shape[1]): for cc in range(newvalues.shape[2]): newvalues[:, rr, cc] = callback(values[:, r0 + rr, cc].flatten(), lats[r0 + rr], lons[cc] if lons[cc] < 180 else lons[cc] - 360) write_ncdf("/srv/ftp/cfsr/%s-tropics-2050/%s-%d%02d.nc4" % (variable, variable, year, month), variable, units, newvalues, lats[(lats > -30) & (lats < 30)], lons) tdiff = get_ncdf_mine("outputs/bio-1.nc4", 'change') adjust_dailies('tmin', 'degrees C', lambda base, lat, lon: base + tdiff.getll_raw(lat, lon)) adjust_dailies('tmax', 'degrees C', lambda base, lat, lon: base + tdiff.getll_raw(lat, lon)) pfact = get_ncdf_mine("outputs/bio-12.nc4", 'change') adjust_dailies('prate', 'kg/m^2/s', lambda base, lat, lon: base * (1 + tdiff.getll_raw(lat, lon) / 100.0))
import unittest import math from skypyblue.core import ConstraintSystem from skypyblue.models import Constraint, Strength, Method, Variable from point import Point class ExtendedMidpointTest(unittest.TestCase): __name__ = "ExtendedMidpointTest" def setUp(self): self.constraint_system = ConstraintSystem() self.point1 = Variable("Point 1", Point(4, 10), self.constraint_system) self.point2 = Variable("Point 2", Point(10, 30), self.constraint_system) self.point3 = Variable("Point 3", Point(50, 20), self.constraint_system) self.point4 = Variable("Point 4", Point(100, 30), self.constraint_system) self.midpoint = Variable("midpoint", Point(0, 0), self.constraint_system) mpmp3p4 = Method([self.midpoint, self.point3, self.point4], [self.point1, self.point2], lambda pm, p3, p4: ( Point( pm.X - (p4.X - p3.X), pm.Y - (p4.Y - p3.Y) ), Point( pm.X + (p4.X - p3.X), pm.Y + (p4.Y - p3.Y) ) ) ) mp1pmp3 = Method([self.point1, self.midpoint, self.point3], [self.point2, self.point4], lambda p1, pm, p3: ( Point( 2 * pm.X - p1.X, 2 * pm.Y - p1.Y ), Point( p3.X + (pm.X - p1.X), p3.Y + (pm.Y - p1.Y) ) ) ) mpmp2p4 = Method([self.midpoint, self.point2, self.point4], [self.point1, self.point3], lambda pm, p2, p4: ( Point( 2 * pm.X - p2.X, 2 * pm.Y - p2.Y ), Point( p4.X + (pm.X - p2.X), p4.Y + (pm.Y - p2.Y) ) ) ) constraint = Constraint( lambda p1, p2, p3, p4, pm: pm.is_midpoint(p1, p2) and p1.distance(pm) == p3.distance(p4), Strength.STRONG, [self.point1, self.point2, self.point3, self.point4, self.midpoint], [mpmp3p4, mp1pmp3, mpmp2p4]) self.constraint_system.add_constraint(constraint) self.point3.stay() self.point4.stay() def test_contraint(self): pm = self.midpoint.get_value() p1 = self.point1.get_value() p2 = self.point2.get_value() p3 = self.point3.get_value() p4 = self.point4.get_value() self.assertTrue(pm.is_midpoint(p1,p2)) self.assertTrue(p1.distance(pm) == p3.distance(p4)) def test_change_point1(self): pm_old = self.midpoint.get_value() self.point1.set_value(Point(0, 0)) self.test_contraint() self.assertTrue(self.point1.get_value().equals(Point(0,0))) self.assertTrue(self.midpoint.get_value().equals(pm_old)) def test_change_midpoint(self): self.midpoint.set_value(Point(0, 0)) midpoint = self.midpoint.get_value() self.test_contraint() self.assertTrue(self.midpoint.get_value(), Point(0,0)) def test_change_point3(self): pm_old = self.midpoint.get_value() self.point3.set_value(Point(0, 0)) self.test_contraint() self.assertTrue(self.point3.get_value().equals(Point(0,0))) self.assertTrue(self.midpoint.get_value().equals(pm_old))
# 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 typing from cloudevents.sdk import exceptions, types from cloudevents.sdk.converters import base from cloudevents.sdk.converters.util import has_binary_headers from cloudevents.sdk.event import base as event_base from cloudevents.sdk.event import v1, v03 class BinaryHTTPCloudEventConverter(base.Converter): TYPE = "binary" SUPPORTED_VERSIONS = [v03.Event, v1.Event] def can_read( self, content_type: str = None, headers: typing.Dict[str, str] = {"ce-specversion": None}, ) -> bool: return has_binary_headers(headers) def event_supported(self, event: object) -> bool: return type(event) in self.SUPPORTED_VERSIONS def read( self, event: event_base.BaseEvent, headers: dict, body: typing.IO, data_unmarshaller: types.UnmarshallerType, ) -> event_base.BaseEvent: if type(event) not in self.SUPPORTED_VERSIONS: raise exceptions.UnsupportedEvent(type(event)) event.UnmarshalBinary(headers, body, data_unmarshaller) return event def write( self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType ) -> (dict, bytes): return event.MarshalBinary(data_marshaller) def NewBinaryHTTPCloudEventConverter() -> BinaryHTTPCloudEventConverter: return BinaryHTTPCloudEventConverter()
"""Support for Vera binary sensors.""" import logging from homeassistant.components.binary_sensor import ( ENTITY_ID_FORMAT, BinarySensorDevice) from . import VERA_CONTROLLER, VERA_DEVICES, VeraDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Vera controller devices.""" add_entities( [VeraBinarySensor(device, hass.data[VERA_CONTROLLER]) for device in hass.data[VERA_DEVICES]['binary_sensor']], True) class VeraBinarySensor(VeraDevice, BinarySensorDevice): """Representation of a Vera Binary Sensor.""" def __init__(self, vera_device, controller): """Initialize the binary_sensor.""" self._state = False VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def is_on(self): """Return true if sensor is on.""" return self._state def update(self): """Get the latest data and update the state.""" self._state = self.vera_device.is_tripped
from django.conf import settings from django.conf.urls import url, include from django.urls import reverse from .feeds import BlogPageFeed from .views import EntryPageServe, EntryPageUpdateCommentsView from .utils import strip_prefix_and_ending_slash urlpatterns = [ url( regex=r'^entry_page/(?P<entry_page_id>\d+)/update_comments/$', view=EntryPageUpdateCommentsView.as_view(), name='entry_page_update_comments' ), url( regex=r'^(?P<blog_path>[-\w\/]+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', view=EntryPageServe.as_view(), name='entry_page_serve_slug' ), url( regex=r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', view=EntryPageServe.as_view(), name='entry_page_serve' ), url( regex=r'^(?P<blog_path>[-\w\/]+)/feed/$', view=BlogPageFeed(), name='blog_page_feed_slug' ), url( regex=r'^feed/$', view=BlogPageFeed(), name='blog_page_feed' ) ] if not getattr(settings, 'PUPUT_AS_PLUGIN', False): from wagtail.core import urls as wagtail_urls from wagtail.admin import urls as wagtailadmin_urls from wagtail.documents import urls as wagtaildocs_urls from wagtail.search import urls as wagtailsearch_urls from wagtail.contrib.sitemaps.views import sitemap urlpatterns.extend([ url( regex=r'^blog_admin/', view=include(wagtailadmin_urls) ), url( regex=r'', view=include(wagtail_urls) ), url( regex=r'^search/', view=include(wagtailsearch_urls) ), url( regex=r'^documents/', view=include(wagtaildocs_urls) ), url( regex='^sitemap\.xml$', view=sitemap ) ]) def get_entry_url(entry, blog_page, root_page): """ Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page. """ if root_page == blog_page: return reverse('entry_page_serve', kwargs={ 'year': entry.date.strftime('%Y'), 'month': entry.date.strftime('%m'), 'day': entry.date.strftime('%d'), 'slug': entry.slug }) else: # The method get_url_parts provides a tuple with a custom URL routing # scheme. In the last position it finds the subdomain of the blog, which # it is used to construct the entry url. # Using the stripped subdomain it allows Puput to generate the urls for # every sitemap level blog_path = strip_prefix_and_ending_slash(blog_page.specific.last_url_part) return reverse('entry_page_serve_slug', kwargs={ 'blog_path': blog_path, 'year': entry.date.strftime('%Y'), 'month': entry.date.strftime('%m'), 'day': entry.date.strftime('%d'), 'slug': entry.slug }) def get_feeds_url(blog_page, root_page): """ Get the feeds urls a blog page instance. It will use an url or another depending if blog_page is the root page. """ if root_page == blog_page: return reverse('blog_page_feed') else: blog_path = strip_prefix_and_ending_slash(blog_page.specific.last_url_part) return reverse('blog_page_feed_slug', kwargs={'blog_path': blog_path})
"use strict"; var constants = require("./constants"); function formatAuth(urlObj, options) { if (urlObj.auth && !options.removeAuth && (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE)) { return urlObj.auth + "@"; } return ""; } function formatHash(urlObj, options) { return urlObj.hash ? urlObj.hash : ""; } function formatHost(urlObj, options) { if (urlObj.host.full && (urlObj.extra.relation.maximumAuth || options.output===constants.ABSOLUTE)) { return urlObj.host.full; } return ""; } function formatPath(urlObj, options) { var str = ""; var absolutePath = urlObj.path.absolute.string; var relativePath = urlObj.path.relative.string; var resource = showResource(urlObj, options); if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE) { str = absolutePath; } else if (relativePath.length<=absolutePath.length && options.output===constants.SHORTEST || options.output===constants.PATH_RELATIVE) { str = relativePath; if (str === "") { var query = showQuery(urlObj,options) && !!getQuery(urlObj,options); if (urlObj.extra.relation.maximumPath && !resource) { str = "./"; } else if (urlObj.extra.relation.overridesQuery && !resource && !query) { str = "./"; } } } else { str = absolutePath; } if ( str==="/" && !resource && options.removeRootTrailingSlash && (!urlObj.extra.relation.minimumPort || options.output===constants.ABSOLUTE) ) { str = ""; } return str; } function formatPort(urlObj, options) { if (urlObj.port && !urlObj.extra.portIsDefault && urlObj.extra.relation.maximumHost) { return ":" + urlObj.port; } return ""; } function formatQuery(urlObj, options) { return showQuery(urlObj,options) ? getQuery(urlObj, options) : ""; } function formatResource(urlObj, options) { return showResource(urlObj,options) ? urlObj.resource : ""; } function formatScheme(urlObj, options) { var str = ""; if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE) { if (!urlObj.extra.relation.minimumScheme || !options.schemeRelative || options.output===constants.ABSOLUTE) { str += urlObj.scheme + "://"; } else { str += "//"; } } return str; } function formatUrl(urlObj, options) { var url = ""; url += formatScheme(urlObj, options); url += formatAuth(urlObj, options); url += formatHost(urlObj, options); url += formatPort(urlObj, options); url += formatPath(urlObj, options); url += formatResource(urlObj, options); url += formatQuery(urlObj, options); url += formatHash(urlObj, options); return url; } function getQuery(urlObj, options) { var stripQuery = options.removeEmptyQueries && urlObj.extra.relation.minimumPort; return urlObj.query.string[ stripQuery ? "stripped" : "full" ]; } function showQuery(urlObj, options) { return !urlObj.extra.relation.minimumQuery || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE; } function showResource(urlObj, options) { var removeIndex = options.removeDirectoryIndexes && urlObj.extra.resourceIsIndex; var removeMatchingResource = urlObj.extra.relation.minimumResource && options.output!==constants.ABSOLUTE && options.output!==constants.ROOT_RELATIVE; return !!urlObj.resource && !removeMatchingResource && !removeIndex; } module.exports = formatUrl;
# # Copyright (c) 2008-2015 Citrix Systems, 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. # class systementitydata_args : ur""" Provides additional arguments required for fetching the systementitydata resource. """ def __init__(self) : self._type = "" self._name = "" self._counters = "" self._starttime = "" self._endtime = "" self._last = 0 self._unit = "" self._datasource = "" self._core = 0 @property def type(self) : ur"""Specify the entity type. """ try : return self._type except Exception as e: raise e @type.setter def type(self, type) : ur"""Specify the entity type. """ try : self._type = type except Exception as e: raise e @property def name(self) : ur"""Specify the entity name. """ try : return self._name except Exception as e: raise e @name.setter def name(self, name) : ur"""Specify the entity name. """ try : self._name = name except Exception as e: raise e @property def counters(self) : ur"""Specify the counters to be collected. """ try : return self._counters except Exception as e: raise e @counters.setter def counters(self, counters) : ur"""Specify the counters to be collected. """ try : self._counters = counters except Exception as e: raise e @property def starttime(self) : ur"""Specify start time in mmddyyyyhhmm to start collecting values from that timestamp. """ try : return self._starttime except Exception as e: raise e @starttime.setter def starttime(self, starttime) : ur"""Specify start time in mmddyyyyhhmm to start collecting values from that timestamp. """ try : self._starttime = starttime except Exception as e: raise e @property def endtime(self) : ur"""Specify end time in mmddyyyyhhmm upto which values have to be collected. """ try : return self._endtime except Exception as e: raise e @endtime.setter def endtime(self, endtime) : ur"""Specify end time in mmddyyyyhhmm upto which values have to be collected. """ try : self._endtime = endtime except Exception as e: raise e @property def last(self) : ur"""Last is literal way of saying a certain time period from the current moment. Example: -last 1 hour, -last 1 day, et cetera.<br/>Default value: 1. """ try : return self._last except Exception as e: raise e @last.setter def last(self, last) : ur"""Last is literal way of saying a certain time period from the current moment. Example: -last 1 hour, -last 1 day, et cetera.<br/>Default value: 1 """ try : self._last = last except Exception as e: raise e @property def unit(self) : ur"""Specify the time period from current moment. Example 1 x where x = hours/ days/ years.<br/>Possible values = HOURS, DAYS, MONTHS. """ try : return self._unit except Exception as e: raise e @unit.setter def unit(self, unit) : ur"""Specify the time period from current moment. Example 1 x where x = hours/ days/ years.<br/>Possible values = HOURS, DAYS, MONTHS """ try : self._unit = unit except Exception as e: raise e @property def datasource(self) : ur"""Specifies the source which contains all the stored counter values. """ try : return self._datasource except Exception as e: raise e @datasource.setter def datasource(self, datasource) : ur"""Specifies the source which contains all the stored counter values. """ try : self._datasource = datasource except Exception as e: raise e @property def core(self) : ur"""Specify core ID of the PE in nCore. """ try : return self._core except Exception as e: raise e @core.setter def core(self, core) : ur"""Specify core ID of the PE in nCore. """ try : self._core = core except Exception as e: raise e class Unit: HOURS = "HOURS" DAYS = "DAYS" MONTHS = "MONTHS"
package cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.operators.reproduction; import cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.GenotypeRepresentation; import cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.Individual; import cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.individuals.SimpleIndividual; import cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.representations.genotype.SimpleBinaryGenomeDescriptor; import cz.cvut.felk.cig.jcool.benchmark.method.evolutionary.representations.genotype.SimpleBinaryRepresentation; import cz.cvut.felk.cig.jcool.benchmark.util.EmptyRandomGenerator; import cz.cvut.felk.cig.jcool.core.RandomGenerator; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; /** * Created by IntelliJ IDEA. * User: miklamar * Date: 27.3.2011 * Time: 20:04 * Tests reproduceInternal method. */ public class GenotypeNPointCrossoverReproductionOperatorTest extends TestCase { protected GenotypeNPointCrossoverReproductionOperator operator; protected RandomGenerator randomGenerator; protected boolean[] genome1; protected boolean[] genome2; protected boolean[] expectedGenome1; protected boolean[] expectedGenome2; @Before public void setUp(){ this.operator = new GenotypeNPointCrossoverReproductionOperator(); this.operator.setRandomGenerator(new EmptyRandomGenerator(){ protected int[] ints = new int[]{8, 12, 7, 2}; protected int intIdx = 0; @Override public int nextInt(int minInclusive, int maxExclusive) { return this.ints[intIdx++]; } }); // 0 1 2 3 4 5 6 7 8 this.genome1 = new boolean[]{false, true, false, false, true, true, false, true, true, true, false, true, false, false, true, true, false, false}; this.genome2 = new boolean[]{true, true, false, false, false, false, true, false, true, false, false, false, true, false, false, true, false, true}; this.expectedGenome1 = new boolean[] {false, true, false, false, false, false, true, true, true, false, false, false, false, false, true, true, false, false}; this.expectedGenome2 = new boolean[] {true, true, false, false, true, true, false, false, true, true, false, true, true, false, false, true, false, true}; } @Test public void testReproduceInternal1() throws Exception { this.operator.setCreateBothChildren(true); this.operator.setCrossPointCount(4); SimpleBinaryRepresentation repr1 = new SimpleBinaryRepresentation(new SimpleBinaryGenomeDescriptor()){ @Override public int getTotalLength() { this.genome = genome1; return super.getTotalLength(); } }; repr1.getTotalLength(); Individual first = new SimpleIndividual(1, 0.0, repr1); SimpleBinaryRepresentation repr2 = new SimpleBinaryRepresentation(new SimpleBinaryGenomeDescriptor()){ @Override public int getTotalLength() { this.genome = genome2; return super.getTotalLength(); } }; repr2.getTotalLength(); Individual second = new SimpleIndividual(1, 0.0, repr2); this.operator.reproduceInternal(new Individual[]{first}, new Individual[]{second}); GenotypeRepresentation result1 = ((GenotypeRepresentation)first.getRepresentation()); GenotypeRepresentation result2 = ((GenotypeRepresentation)second.getRepresentation()); assertEquals(this.expectedGenome1.length, result1.getTotalLength()); assertEquals(this.expectedGenome2.length, result2.getTotalLength()); for (int i = 0; i < this.expectedGenome1.length; i++){ assertEquals("at index " + i, expectedGenome1[i], result1.getGeneAt(i)); } for (int i = 0; i < this.expectedGenome2.length; i++){ assertEquals("at index " + i, expectedGenome2[i], result2.getGeneAt(i)); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sv.com.mined.sieni; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import sv.com.mined.sieni.model.SieniTipoComponente; /** * * @author Laptop */ @Stateless public class SieniTipoComponenteFacade extends AbstractFacade<SieniTipoComponente> implements sv.com.mined.sieni.SieniTipoComponenteFacadeRemote { @PersistenceContext(unitName = "sieni_PU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public SieniTipoComponenteFacade() { super(SieniTipoComponente.class); } }
var app = angular.module('TimingApp', []); /** * Represents a stopwatch that counts down time from its creation * @param {number} counter - The time from the object's creation * @param {number} speed - The interval between tick function calls * @param {number} increment - The number added to the counter each tick * @param {boolean} started - The object's start state (influences UI buttons) * @param {boolean} paused - The object's pause state (influences UI buttons) */ app.controller('StopwatchController', function($scope, $timeout) { "use strict"; $scope.counter = 0; $scope.speed = 1; $scope.increment = 1; $scope.started = false; $scope.paused = false; /** * Called each tick. Repeatedly sets a timeout on itself. */ $scope.onTick = function () { $scope.counter += $scope.increment; ticker = $timeout($scope.onTick, $scope.speed); }; /** * Promise to be set to a timeout on the tick function */ var ticker; /** * Starts the stopwatch, setting the promise */ $scope.start = function() { ticker = $timeout($scope.onTick, $scope.speed); $scope.started = true; }; /** * Pauses the stopwatch without resetting the counter */ $scope.pause = function () { $timeout.cancel(ticker); $scope.paused = true; }; /** * Unpauses the stopwatch if it's paused */ $scope.unpause = function () { $timeout.cancel(ticker); $scope.paused = false; ticker = $timeout($scope.onTick, $scope.speed); }; /** * Restarts the stopwatch, resetting the counter */ $scope.restart = function () { $timeout.cancel(ticker); $scope.counter = 0; $scope.paused = false; ticker = $timeout($scope.onTick, $scope.speed); } }); /** * Represents a timer that accepts a value and decrements it until it reaches zero * @param {number} countdown - The initial value to be decremented * @param {number} counter - The time from the object's creation * @param {number} speed - The interval between tick function calls * @param {number} increment - The number substracted from the counter each tick * @param {boolean} started - The object's start state (influences UI buttons) * @param {boolean} paused - The object's pause state (influences UI buttons) */ app.controller('TimerController', function($scope, $timeout) { "use strict"; $scope.countdown = 1000; $scope.counter = $scope.countdown; $scope.speed = 1; $scope.decrement = 1; $scope.paused = false; $scope.started = false; /** * Called each tick. Repeatedly sets a timeout on itself (until the counter reaches zero) */ $scope.onTick = function() { if ($scope.counter <= 0) { $timeout.cancel(ticker); } else { $scope.counter -= $scope.decrement; ticker = $timeout($scope.onTick, $scope.speed); } }; /** * Promise initially set to a timeout on the tick function */ var ticker; /** * Starts the timer, setting the promise */ $scope.start = function() { ticker = $timeout($scope.onTick, $scope.speed); $scope.started = true; }; /** * Pauses the timer without resetting the counter */ $scope.pause = function () { $timeout.cancel(ticker); $scope.paused = true; }; /** * Unpauses the timer if it's paused */ $scope.unpause = function () { $timeout.cancel(ticker); $scope.paused = false; ticker = $timeout($scope.onTick, $scope.speed); }; /** * Restarts the timer, resetting the counter to its initial value */ $scope.restart = function () { $timeout.cancel(ticker); $scope.counter = $scope.countdown; $scope.paused = false; ticker = $timeout($scope.onTick, $scope.speed); } });
import theano as _th import numpy as _np def create_param(shape, init, fan=None, name=None, type=_th.config.floatX): return _th.shared(init(shape, fan).astype(type), name=name) def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX): val = init(shape, fan).astype(type) param = _th.shared(val, name=name) grad_name = 'grad_' + name if name is not None else None grad_param = _th.shared(_np.zeros_like(val), name=grad_name) return param, grad_param def create_param_state_as(other, initial_value=0, prefix='state_for_'): return _th.shared(other.get_value()*0 + initial_value, broadcastable=other.broadcastable, name=prefix + str(other.name) ) def count_params(module): params, _ = module.parameters() return sum(p.get_value().size for p in params) def save_params(module, where, compress=False): params, _ = module.parameters() savefn = _np.savez_compressed if compress else _np.savez savefn(where, params=[p.get_value() for p in params]) def load_params(module, fromwhere): params, _ = module.parameters() with _np.load(fromwhere) as f: for p, v in zip(params, f['params']): p.set_value(v)
import * as express from 'express'; const git = require('git-last-commit'); module.exports = async (req: express.Request, res: express.Response) => { // Get commit info git.getLastCommit((err, commit) => { res.send({ commit: commit }); }, { dst: `${__dirname}/../../misskey-web` }); };
package com.cidic.equipment.dao; import java.util.List; import java.util.Map; import java.util.Optional; import com.cidic.equipment.model.Brand; public interface BrandDao { public void createBrand(Brand brand); public void updateBrand(Brand brand); public void deleteBrand(int id); public List<Brand> getBrandByPage(int offset, int limit); public Map<Integer,String> getBrandMap(); public int getCountBrand(); public List<Brand> getAllBrand(); public Optional<Brand> getDataByBrandId(int id); }
from troubleshooting.framework.remote.SSHLibrary import SSHLibrary from troubleshooting.framework.libraries.library import singleton import sys @singleton class client(object): def __init__(self): super(self.__class__,self).__init__() self._connection_cache = {} def open_connection(self,host,port,user,password): if self._connection_cache.has_key(host): return self._connection_cache[host] else: ssh = SSHLibrary() ssh.open_connection(host=host,port=port,username=user,password=password) self._connection_cache.update({host:ssh}) # print self._connection_cache return ssh def test_connection(self,host,port,user,password): status = None try: sys.stdout.write("Framework: connecting to remote machine..") sys.stdout.flush() ssh = SSHLibrary() ssh.open_connection(host=host, port=port, username=user, password=password) except Exception,e: sys.stdout.write("\t[Failed]\n") sys.stdout.flush() print e return False else: sys.stdout.write("\t[OK]\n") sys.stdout.flush() return True finally: ssh.close_connection()
#!/usr/bin/python ############################################################################# ## ## Copyright (C) 2016 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the test suite of PySide2. ## ## $QT_BEGIN_LICENSE:GPL-EXCEPT$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3 as published by the Free Software ## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# import unittest, os from PySide2.QtCore import * from PySide2.QtWidgets import * from PySide2.QtSvg import * class QSvgWidgetTest(unittest.TestCase): def testLoad(self): tigerPath = os.path.join(os.path.dirname(__file__), 'tiger.svg') app = QApplication([]) fromFile = QSvgWidget() fromFile.load(tigerPath) self.assertTrue(fromFile.renderer().isValid()) tigerFile = QFile(tigerPath) tigerFile.open(QFile.ReadOnly) tigerData = tigerFile.readAll() fromContents = QSvgWidget() fromContents.load(tigerData) self.assertTrue(fromContents.renderer().isValid()) if __name__ == '__main__': unittest.main()