prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
class WordDictionary(object): def __init__(self): """ initialize your data structure here. """ self.root = {} def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ node = self.root ...
e['#'] = '#' def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """
def find(word, node): if not word: return '#' in node c, word = word[0], word[1:] if c != '.': return c in node and find(word, node[c]) return any(find(word, d) for d in node.values() if d != '#') return find(word, self.root...
from fastapi.testclient import TestClient from docs_src.metadata.tutorial001 import app client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": { "title": "ChimichangApp", "description": "\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**....
"url": "https://www.apache.org/licenses/LICENSE-2.0.html", }, "version": "0.0.1", }, "paths": { "/items/": { "get": { "summary"
: "Read Items", "operationId": "read_items_items__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, ...
import sys from numpy import * from scipy import signal import scipy.io.wavfile from matplotlib import pyplot import sklearn.decomposition def main(): # First load the audio data, the audio data on this
example is obtained from http://www.ism.ac.jp/~shiro/research/blindsep.html rate, source = scipy.io.wavfile.read('/Use
rs/nareshshah/blind_source_data/X_rsm2.wav') # The 2 sources are stored in left and right channels of the audio source_1, source_2 = source[:, 0], source[:, 1] data = c_[source_1, source_2] # Normalize the audio from int16 range to [-1, 1] data = data / 2.0 ** 15 # Perform Fast ICA on the data to obtained sepa...
#!/usr/bin/env python #coding=utf-8 from twisted.python import log from toughradius.radiusd.settings import * import logging import datetime def process(req=None,user=None,radiusd=None,**kwargs): if not req.get_acct_status_type() == STATUS_TYPE_STOP: return runstat=radiusd.runstat store = ra...
ticket.start_source= STATUS_TYPE_STOP ticket.stop_source = STATUS_TYPE_STOP store.add_ticket(ticket)
else: store.del_online(ticket.nas_addr,ticket.acct_session_id) ticket.acct_start_time = online['acct_start_time'] ticket.acct_stop_time= _datetime.strftime( "%Y-%m-%d %H:%M:%S") ticket.start_source = online['start_source'] ticket.stop_source = STATUS_TYPE_STOP store.ad...
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission i
s hereby granted, free of charge, to any person obtaining # a copy of this software and associat
ed documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the follo...
ne_candidate['we_vote_id'] if 'we_vote_id' in one_candidate else '' google_civic_election_id = \ one_candidate['google_civic_election_id'] if 'google_civic_election_id' in one_candidate else '' contest_office_we_vote_id = \ one_candidate['contest_office_we_vote_id'] if 'contest_o...
candidate_twitter_handle'] if 'candidate_twitter_handle' in one_candidate else '', 'twitter_name': one_candidate['twitter_name'] if 'twitter_nam
e' in one_candidate else '', 'twitter_location': one_candidate['twitter_location'] if 'twitter_location' in one_candidate else '', 'twitter_followers_count': one_candidate['twitter_followers_count'] if 'twitter_followers_count' in one_candidate else '', ...
view() self.selection_change_handler = self.thumb_view.connect('selection-changed', self.on_selection_changed) # Initialization of panorama viewer: # Since it takes significant amount of memory, we load it only # once we encounter a panorama image (see on_selection_changed). ...
a_viewer_loaded = True def image_to_base64(self, filepath): """Read an image file and returm its content as base64 encoded string. Args: filepath: an image file to read Returns: a string of the base64 encoded image """ with open(filepath, 'rb') as ...
ef get_image_mimetype(self, filepath): ext = os.path.splitext(filepath)[1].lower() eog_mimetypes = { '.bmp': 'image/x-bmp', '.jpg': 'image/jpg', '.jpeg': 'image/jpg', '.png': 'image/png', '.tif': 'image/tiff', '.tiff': 'image/ti...
import sublime import sublime_plugin from ..core import oa_syntax, decorate_pkg_name from ..core import ReportGenerationThread from ...lib.packages import PackageList ###---------------------------------------------------------------------------- class PackageReportThread(ReportGenerationThread): """ Genera...
_sep] for pkg_name, pkg_info in pkg_list: packages[pkg_name] = pkg_info.status(detailed=False) result.append( "| {:<40} | [{:1}] | [{:1}] | [{:1}] |".format( decorate_pkg_name(pkg_info, name_only=True), "S" if pkg_info.shipped_path...
None else " ")) result.extend([r_sep, ""]) self._set_content("OverrideAudit: Package Report", result, ":packages", oa_syntax("OA-PkgReport"), { "override_audit_report_packages": packages, "context_menu": "OverrideAuditRep...
#!/usr/bin/python2 # -*- coding: utf-8 -*- # # Copyright 2014 Peerchemist # # This file is part of NuBerryPi project. # # 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 Li...
ave received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. __author__ = "Peerchemist" __license__ = "GPL" __version__ = "0.23" import os, sys import sh import ar
gparse import json import urllib import platform from datetime import timedelta from datetime import datetime as dt from colored import fore, back, style ## Class that pulls and parses data class pbinfo: def system(self): def uptime(): with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from reportlab.pdfbase import ttfonts from odoo import api, fields, models from odoo.report.render.rml2pdf import customfonts """This module allows the mapping of some system-available TTF fonts to the r...
found_fonts.append((font.familyName, font.name, font_path, font.styleName)) except Exception, ex: _logger.warning("Could not register Font %s: %s", font_pa
th, ex) for family, name, path, mode in found_fonts: if not self.search([('family', '=', family), ('name', '=', name)]): self.create({'family': family, 'name': name, 'path': path, 'mode': mode}) # remove fonts not present on the disk anymore existing_font_names = [n...
import sys import os from distutils.core import setup if sys.version_info.major >= 3: print 'Sorry, currently only supports Python 2. Patches welcome!' sys.exit(1) setup( name='browser-cookie', version='0.6', packages=['browser_cookie'], package_dir={'browser_cookie' : '.'}, # look for packag...
url='https://bitbucket.org/richardpenman/
browser_cookie', install_requires=['pycrypto', 'keyring'], license='lgpl' )
import logging from ask import alexa import car_accidents import expected_population logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler
(request_obj, context=None): return alexa.route_request(request_obj) @alexa.default def default_handler(request): logger
.info('default_handler') return alexa.respond("Sorry, I don't understand.", end_session=True) @alexa.request("LaunchRequest") def launch_request_handler(request): logger.info('launch_request_handler') return alexa.respond('Ask me about any public data about Sweden.', end_session=True) @alexa.request("Se...
051b8200, # predict_proba returned SAMME.R values for SAMME. clf_samme.algorithm = "SAMME.R" assert_array_less(0, np.abs(clf_samme.predict_proba(iris.data) - prob_samme)) def test_boston(): """Check consistency on dataset boston house prices.""" clf = AdaBoostRegressor(random...
ises(ValueError, clf.fit, X, y_regr) def test_sparse_classification(): """Check classification with sparse input.""" class CustomSVC(SVC): """SVC variant that records
the nature of the training set.""" def fit(self, X, y, sample_weight=None): """Modification on fit caries data type for later verification.""" super(CustomSVC, self).fit(X, y, sample_weight=sample_weight) self.data_type_ = type(X) return self X, y = dataset...
# -*- coding: utf-8 -*- """ Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd.  All rights reserved. The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without res...
of file :type hackathon_name: str | unicode :param hackathon_name: name of hackathon related to this file :rtype str :return a random file name which includes hackathon_name and time as parts """ if not hackathon_name: hackathon_name = "" extension =...
" % ( hackathon_name, time.strftime("%Y%m%d"), str(uuid.uuid1())[0:8], extension ) return new_name.strip('-')
from layer import * class TanhLayer(Layer): def __init__(self, *args, **kwargs): super(TanhLayer, self).__init__(*args, **kwargs) @classmethod def IsLayerType(cls, proto): return proto.hyperparams.activation == deepnet_pb2.Hyperparams.TANH def ApplyActivation(self): cm.tanh(self.state) def Sam...
= error if get_deriv: self.ComputeDeriv() else: raise Exception('Unknown loss function for tanh units.') return perf def GetSparsi
tyDivisor(self): self.means_temp2.assign(1) self.means_temp2.subtract(self.means, target=self.means_temp) self.means_temp2.add(self.means) self.means_temp2.mult(self.means_temp) return self.means_temp2
from mock import patch, call import mock from lxml import etree from kiwi.sol
ver.repository.rpm_md import SolverRepositoryRpmMd from kiwi.solver.repository.base import SolverRepositoryBase class TestSolverRepositoryRpmMd: def setup(self): self.xml_data = etree.parse('../data/repomd.xml') self.uri = mock.Mock() self.solver = SolverRepositoryRpmMd(self.uri) @pat...
temporary_metadata_dir') @patch.object(SolverRepositoryBase, '_get_repomd_xml') def test__setup_repository_metadata( self, mock_xml, mock_mkdtemp, mock_create_solvables, mock_download_from_repository ): mock_mkdtemp.return_value = 'metadata_dir.XX' mock_xml.return_value = sel...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ter # GNU MP: Cannot allocate memory (size=2305843009206983184)
args.extend([ '--enable-gmp', 'CFLAGS=-O0' ]) else: args.append('--disable-gmp') return args
''' Test the sslheaders plugin. ''' # 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, Ver...
ap_config.AddLine( 'map http://bar.com http://127.0.0.1:{0}'.format(server.Variables.Port) ) ts.Disk.remap_config.AddLine( 'map https://bar.com http://127.0.0.1:{0}'.format(server.Variables.Port) ) ts.Disk.ssl_server_name_yaml.AddLines([ '- fqdn: "*bar.com"', ' verify_client: STRICT', ]) ts.Disk.plug...
onfig.AddLine( 'sslheaders.so SSL-Client-ID=client.subject' ) tr = Test.AddTestRun() tr.Processes.Default.StartBefore(server) tr.Processes.Default.StartBefore(Test.Processes.ts, ready=When.PortOpen(ts.Variables.ssl_port)) tr.Processes.Default.Command = ( 'curl -H "SSL-Client-ID: My Fake Client ID" --verbose --...
def __init__(self, recid): self.recid = recid def _lookup(self, component, path): # after /<CFG_SITE_RECORD>/<recid>/files/ every part is used as the file # name filename = component def getfile(req, form): args = wash_urlargd(form, bibdocfile_templates.files_...
docformat = args['format'] if args['subformat']: docformat +=
';%s' % args['subformat'] if not version: version = args['version'] ## Download as attachment is_download = False if args['download']: is_download = True # version could be either empty, or all or an integer try: ...
ount: ' + str( from_satoshi( amount )) + ', max: ' + str( max_currency_value )) btc_fee=response_dict['fee'][0] if float(btc_fee)<0 or float( from_satoshi(btc_fee))>max_currency_value: return (None, 'Invalid fee: ' + str( from_satoshi( amount )) + ', max: ' + str( max_currency_value )) currency=resp...
return (None, 'Invalid currency') marker_addr=None try: marker=response_dict['marker'][0] if marker.lower(
)=='true': marker_addr=exodus_address except KeyError: # if no marker, marker_addr stays None pass if pubkey == None: tx_to_sign_dict={'transaction':'','sourceScript':''} l=len(from_addr) if l == 66 or l == 130: # probably pubkey if is_pubkey_vali...
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal from PyQt5.Qt import QSystemTrayIcon, QIcon class TrayIcon(QSystemTrayIcon): ActivationReason = ['Unknown', 'Context', 'DoubleClick', 'Trigger', 'MiddleClick'] onactivate = pyqtSignal(int, str) onmessageclick = pyqtSignal() def __init__(self, p...
uper(TrayIcon, self).isVisible() # 获取是否支持消息弹泡 @pyqtSlot(result = bool) def supportsMessages(self): return super(TrayIcon, self).supportsMessages() # 获取是否支持系统托盘图标 @pyqtSlot(result = bool) def isSystemTrayAvailable(self): return super(TrayIcon, self).isSystemTrayAvailable() # 显示托盘消息 # showMess...
reason])
b+n,a+1,\frac{1-x}{2}\right). Note that this definition generalizes to nonintegral values of `n`. When `n` is an integer, the hypergeometric series terminates after a finite number of terms, giving a polynomial in `x`. **Evaluation of Jacobi polynomials** A special evaluation is `P_n^{(a,b)}(1) = {n+a \choose n}`:: ...
: ... nprint(chop(taylor(lambda x: legendre(n, x), 0, n))) ... [1.0] [0.0, 1.0] [-0.5, 0.0, 1.5] [0.0, -1.5, 0.0, 2.5] [0.375, 0.0, -3.75, 0.0, 4.375] The roots of Legendre polynomials are located symmetrically on the interval `[-1, 1]`:: >>> for n in range(5): ... nprint(p...
35, 0.57735] [-0.774597, 0.0, 0.774597] [-0.861136, -0.339981, 0.339981, 0.861136] An example of an evaluation for arbitrary `n`:: >>> legendre(0.75, 2+4j) (1.94952805264875 + 2.1071073099422j) **Orthogonality** The Legendre polynomials are orthogonal on `[-1, 1]` with respect to the trivial weight ...
# -*- coding: utf-8 -*- from gensim.models import word2vec from gensim import models import jieba import codecs import io from collections import Counter import operator import numpy f = codecs.open("target_article.txt",'r','utf8') content = f.readlines() article = [] jieba.set_dictionary('jieba_dict/dict.txt.big')...
d_list: if friend_1 == friend_2: continue value += model.similarity(friend_1, friend_2) leng = len(friend_list) related_word[words[i]] = value/float(leng*leng) s_imp_words = sorted(related_word.items(), key=operator.itemgetter(1), reverse=True) for i in s_imp_words[:20]: print i[0] print "---------------...
-----------------------" keywords = [] fg = numpy.zeros(len(s_imp_words)) for i in range(len(s_imp_words)): if fg[i] == 1: continue for j in range(i+1,len(s_imp_words)): if fg[j] != 1: if model.similarity(s_imp_words[i][0], s_imp_words[j][0]) >= 0.7: fg[j] = 1 keywords.append(s_imp_words[i]) #print s...
self.height, self.width = self.win.getmaxyx() self.name = name self.help = [_("+/- to Increase and decrease volume"), _("./, to Increase and decrease right volume"), _("</> to Increase and decrease left volume"), _("m to Mute"), ...
(app_name, app_pid, volume_left, mute) = stream line = '[%s] M:%i%% (%s)' % (app_name, volume_left, app_pid) if mute: line = '%s [M]' % (line) if self.selected_item == line_number: self.win.add...
ne_number + 1, 1, line) self.max_item = line_number if self.info_window_data: draw_info_window(self.win, self.info_window_data) self.win.refresh() class TabPlayback(GenericStream): def __init__(self, win): GenericStream.__init__(self, win, 'Playback', _('Playback')) ...
ue; values that are commented out # serve to show the default value. import sys import os # pip install sphinx_rtd_theme # import sphinx_rtd_theme # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # If your extensions are in another directory, add it here. If the directory # is relative to the documentati...
. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. # html_style = 'solar.css' # The name for this set of Sphinx documents.
If None, it defaults to # "<project> v<release> documentation". html_title = 'Ansible Documentation' # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. # html_logo = None #...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2016 Satpy developers # # This file is part of satpy. # # satpy is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or...
alues with data np.put(grid, ids, values) # Correct for bottom left origin in LI row/column indices. rotgrid = np.flipud(grid) # Rotate the grid by 90 degree clockwise rotgrid = np.rot90(rotgrid, 3) logger.warning("LI data has been rotated to fit to reference grid. \ ...
# Create dataset object out.data[:] = np.ma.getdata(ds) out.mask[:] = np.ma.getmask(ds) out.info.update(key.to_dict()) return out def get_area_def(self, key, info=None): """Create AreaDefinition for specified product. Projection information are hard coded for 0 de...
#!/usr/bin/env python3 import unittest import tempfile from lofar.common.dbcredentials import * def setUpModule(): pass def tearDownModule(): pass class TestCredentials(unittest.TestCase): def test_default_values(self): c = Credentials() self.assertEqual(c.type, "postgres") self.assertEqual(c.hos...
ig dbc = DBCredentials(filepatterns=[f.name]) c_out = dbc.get("DATABASE") # test if the free-form config options got through self.assertEqual(c_out.config["foo"], "bar") self.assertEqual(c_out.config
["test"], "word word") def main(argv): unittest.main() if __name__ == "__main__": # run all tests import sys main(sys.argv[1:])
ex
ec(open("tmp<caret>.txt").re
ad())
# Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
ing permissions and limitations # under the License. # The maximum value a signed INT type may have DB_MAX_INT = 0x7FFFFFFF # The cinder services binaries and topics' names API_BINARY = "cinder-api" SCHEDULER_BINARY = "cinder-scheduler" VOLUME_BINARY = "cinder-volume" BACKUP_BINARY = "cinder-backup" SCHEDULER_TOP...
(SCHEDULER_BINARY, VOLUME_BINARY, BACKUP_BINARY, API_BINARY) # The encryption key ID used by the legacy fixed-key ConfKeyMgr FIXED_KEY_ID = '00000000-0000-0000-0000-000000000000'
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. from __future__ import absolute_import from testutil.dott import feature, sh, testtmp # noqa: F401 # Load extensions ( sh % "cat" << r"""...
sh that I've injected into # the commit list returned from our mocked phabricator; it is present to # assert that we order the commits co
nsistently based on the time field. sh % "cat" << r""" [{"data": {"query": [{"results": {"nodes": [{ "number": 1, "diff_status_name": "Needs Review", "latest_active_diff": { "local_commit_info": { "nodes": [ {"property_value": "{\"lolwut\": {\"time\": 0, \"commit\": \"88dd5a13bf28b99853a24bddfc...
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer ...
"""Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() d...
elf): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.lose...
# Time: O(n) ~ O(n^2) # Space: O(1) from random import randint class Solution: # @param {integer[]} nums # @param {integer} k # @return {integer} def findKthLargest(self, nums, k): left, right = 0, len(nums) - 1 while left <= right: pivot_idx = randint(left, right) ...
return nums[new_pivot_idx] elif new_pivot_idx > k - 1: right = new_pivot_idx - 1 else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 def PartitionAroundPivot(self, left, right, pivot_idx, nums): pivot_value = nums[pivot_idx] ne...
] for i in xrange(left, right): if nums[i] > pivot_value: nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] new_pivot_idx += 1 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] return new_pivot_idx
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, traceback, Ice, threading, time, os import IceStorm # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Qt interface from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSvg import * # Check that RoboComp has been ...
ma' self.commandTopic = commandTopic def newText
(self, text, current=None): print 'Nos ha llegado', text command = RoboCompASRCommand.Command() partes = text.split() if len(partes) > 0: command.action = partes[0] if len(partes) > 1: command.complements = partes[1:] print 'Action', command.action, '(', command.complements,')' else: print ...
# 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 t...
der_ret) def cinder_volume_delete(self, volume_id): try: cinder_ret = self.cinderclient.volumes.delete(volume_id) except Exception as
e: return (404, e.message, []) return (200, "success", cinder_ret)
''' Created on 30-07-2014 @author: mateusz ''' from threading import Thread import gumtreeofferparser as Parser from injectdependency import Injec
t, InjectDependency @InjectDependency('urlfetcher') class OfferFetcher(Thread): urlfetcher = Inject def __init__(self, inQueue, outQueue): Thread.__init__(self, name="OfferFetcher") self.inQueue = inQueue self.outQueue = outQueue def run(self): while (True...
self.inQueue.task_done() def getOffer(self, url): html = self.urlfetcher.fetchDocument(url) offer = Parser.extractOffer(html) offer["url"] = url return offer
from syslog import syslog module_name = "Syslog" config = { "prefix": "Default Prefix" } def handle_alert(message): syslog("{} - {}".format(config["prefix"], me
ssage))
# -*- coding: utf-8 -*- """ Created on Wed Jan 20 20:42:20 2016 @author: haell """ def dicho(f, a, b, epsilon): assert f(a) * f(b) <= 0 and epsilon > 0 g, d = a, b fg, fd = f(g), f(d) n = 0 while d - g > 2 * epsilon:
n += 1 m = (g + d) / 2. fm = f(m) if fg * fm <= 0: d, fd = m, fm else: g, fg = m, fm print(d, g, fd, fg) return (g + d) / 2., n print(dicho(lambda x : x*x*10**(-8) - 4*x / 5 + 10**(-8), 7*10**7, 9*10**
7, 10**-8))
# 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 u...
ssions and limitations # under the License. import pyarrow as pa import pyarrow.types as types def test_is_boolean(): assert types.is_boolean(pa.bool_()) assert not types.is_boolean(pa.int8()) def test_is_integer(): signed_ints = [pa.int8(), pa.int16(), pa.int32(), pa.int64()] unsigned_ints = [pa.u...
assert types.is_signed_integer(t) assert not types.is_unsigned_integer(t) for t in unsigned_ints: assert types.is_unsigned_integer(t) assert not types.is_signed_integer(t) assert not types.is_integer(pa.float32()) assert not types.is_signed_integer(pa.float32()) def test...
import unittest from word_treasure import * class WordTreasureTestCase(unittest.TestCase): """Test for functions in word treasure. The major aim is to check if there is any unexpected crash. Doesnot check the validity of the response""" def test_definition_call(self): word1 = "
hello" word2 = "somenonexistantword" self.assertEqual(display_definitions(word1), True) self.assertEqual(display_definitions(word2), None)
def test_random_words(self): limit = 10 self.assertEqual(display_random_words(limit), True) def test_display_examples(self): limit = 10 word1 = "hello" word2 = "somenonexistantword" self.assertEqual(display_examples(word1, limit), True) self.assertEq...
# Copyright 2014 OpenStack Foundation # # 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 ...
ength=255), nullable=True, index=True), sa.PrimaryKeyConstraint('id')) op.create_table( 'ml2_brocadeports', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_id', sa.
String(length=36), nullable=False), sa.Column('admin_state_up', sa.Boolean(), nullable=False), sa.Column('physical_interface', sa.String(length=36), nullable=True), sa.Column('vlan_id', sa.String(length=36), nullable=True), sa.Column('tenant_id', sa.String(length=255), nullable=True, ...
# -*- encoding: utf8 -*- # A daemon to keep SSH forwarding connected from __future__ import print_function, absolute_import import os import sys import time import socket import logging class Daemon(object): def __init__(self): self.heartbeat = 50 def run(self): logging.basicConfig(filename=...
return True except socket.error: return False def daemonize(self): pid = os.fork() if pid: os.waitpid(pid, os.WNOHANG)
sys.exit(0) return def reconnect(self): pid = os.fork() if pid == 0: # child err = os.execlp('/usr/bin/ssh', 'ssh', '-i', '/home/xu/.ssh/id_rsa', '-L', '3366:127.0.0.1:3306', '-p', '42022', 'xu@abc.com') ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Search through the su
bfolders of the current folder. For each subfolder found, chdir() to it, then run all executable scripts ending in .SH in that folder. Does not exhaustively search for subfolders of subfolders, or subfolders of subfolders
of subfolders, etc.; it only does exactly what was described in that first sentence, without recursion. Note that this calls scripts in an insecure way: subprocess.call(script_name, shell=True) so it should only be called on scripts that are trusted completely. This script is copyright 2017-20 by Patrick Moone...
#!/usr/bin/python ############################################## ###Python template ###Author: Elizabeth Lee ###Date: 4/26/14 ###Function: Incidence per 100,000 vs. week number for flu weeks (wks 40-20). Incidence is per 100,000 for the US population in the second calendar year of the flu season. ###Import data: SQL_...
zed by total population by second calendar year of
the flu season ### packages/modules ### import csv import matplotlib.pyplot as plt ## local modules ## import functions as fxn ### data structures ### ### functions ### ### data files ### incidin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/SQL_export/OR_allweeks_outpatient.csv','r') incid = cs...
from functools import wraps from threading import RLock import traceback def Synchronized(lock=None): """ :param lock: if None - global lock will used, unique for each function :return: """ if n
ot lock: lock=RLock() def decorator(fn): @wraps(fn) de
f wrapped(*args, **kwargs): lock.acquire() try: return fn(*args, **kwargs) finally: lock.release() return wrapped return decorator
import json from django import temp
late register = template.Library(
) @register.filter def jsonify(value): return json.dumps(value)
from PIL import Image from math import ceil, floor def load_img(src): return Image.open(src) def create_master(width, height): return Image.new("RGBA", (width, height)) def closest_power_two(num): result = 2 while result < num: result = result * 2 return result def create_matrix(cols, ro...
ad_img("img/png/1x/{0}/{1}{2}.png".format(name, action, position))] imgs = list(reduce(lambda a, b: a + b, [generator(name, action, pos, frames) for pos in ["Back", "F
ront", "Left", "Right"]], [])) return imgs if __name__ == "__main__": matrix = create_matrix(4, 4, hero_sprites("hero1", "Dead", 3)) matrix.save("img/hero1_dead.png", "PNG")
# # 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 l
icenses 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 distr...
he # specific language governing permissions and limitations # under the License. """ This module is deprecated. Please use :mod:`airflow.providers.amazon.aws.transfers.redshift_to_s3`. """ import warnings from airflow.providers.amazon.aws.transfers.redshift_to_s3 import RedshiftToS3Operator warnings.warn( "This...
from django.db import models from .bleachfield import BleachField class BleachCharField(BleachField, models.CharField): def pre_save(self, model_inst
ance, add): new_value = getattr(model_instance, self.attname) clean_value = self.clean_text(new_value) setattr(model_instance, self.attname, clean_value) return super(BleachCharField, self).pre_sa
ve(model_instance, add)
# Copyright 2012 OpenStack, LLC # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
reate(context, image_id, tag_value) @utils.mutating def delete(self, req, image_id, tag_value): try: self.db_api.image_tag_delete(req.context, image_id, tag_value) except exception.NotFound:
raise webob.exc.HTTPNotFound() class ResponseSerializer(wsgi.JSONResponseSerializer): def update(self, response, result): response.status_int = 204 def delete(self, response, result): response.status_int = 204 def create_resource(): """Images resource factory method""" se...
self._http.post(self._url_resource_path, self._id, 'action', data=utils.get_json_body("unrescue")) def shelve(self): """ Shelve a running server @rtype: None """ self._http.post(self._url_resource_path, self._id, 'action', dat...
isk copy @keyword host: Destination host @type host: str @keyword password: new admin
istrator password @type password: str @keyword shared: whether the vm is on the shared storage @type shared: bool @rtype: None """ self._http.post(self._url_resource_path, self._id, 'action', data=utils.get_json_body( "ev...
from django.db import models from
jsonfield import JSONField class Sensor(models.Model): name = models.CharField(max_length=25) activated = models.BooleanField(default=False) type = models.CharField(max_length=10) meta = JSONFiel
d()
import functools from . import ( constants, utils, ) class Card(): def __init__(self, kind=None, strength=None, value=None, verbose=None, **kwargs): if kind is None: raise(TypeError("Missing required 'kind' argument.")) self.kind = kind self.strength = strength ...
return self.colour < value.colour return False def __eq__(self, value): if not self._valid_comparision(value): return False if (self.strength == value.strength) and (self.colour == value.colour):
return True def __str__(self): return self.kind + self.colour[0] class MahJongg(Card): def __init__(self): super().__init__(kind='1', strength=1) class Dragon(Card): def __init__(self): super().__init__(kind='R', value=25, verbose="Dragon") class Pheonix(Card): def __init__(...
d((field_proto.name, field_proto, field_name)) for node_name, field_proto, field_name in fields: node.add_children([ProtobufNode._from_spec(field_proto, node_name, path, field_name)]) return node @staticmethod def _from_brain_spec(spec, name, parent_p...
check_data(data, self.proto, self.path, check_spec_class) return {self.name: mapper(data, self.path)} def _feeler_to_proto_nest(self, da
ta, mapper, check_spec_class, options): """Wrap a feeler data proto in a nest. Args:
# coding=utf-8 """ The NetworkCollector class collects metrics on network interface usage using /proc/net/dev. #### Dependencies * /proc/net/dev """ import diamond.collector from diamond.collector import str_to_bool import diamond.convertor import os import re try: import psutil except ImportError: psuti...
""" config = super(NetworkCollector, self).get_default_config() config.update({ 'path': 'network', 'interfaces': ['eth', 'bond', 'em', 'p1p', 'eno', 'enp', 'ens',
'enx'], 'byte_unit': ['bit', 'byte'], 'greedy': 'true', }) return config def collect(self): """ Collect network interface stats. """ # Initialize results results = {} if os.access(self.PROC, os.R...
ry import get_additional_costs from erpnext.manufacturing.doctype.manufacturing_settings.manufacturing_settings import get_mins_between_operations from erpnext.stock.stock_balance import get_planned_qty, update_bin_qty from frappe.utils.csvutils import getlink from erpnext.stock.utils import get_bin, validate_warehouse...
nned_operating_cost = flt(d.hour_rate) * (flt(d.time_in_mins) / 60.0) d.actual_operating_cost = flt(d.hour_rate) * (flt(d.actual_operation_time) / 60.0) self.planned_operating_cost
+= flt(d.planned_operating_cost) self.actual_operating_cost += flt(d.actual_operating_cost) variable_cost = self.actual_operating_cost if self.actual_operating_cost \ else self.planned_operating_cost self.total_operating_cost = flt(self.additional_operating_cost) + flt(variable_cost) def validate_work_orde...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
self._Regio
ns: x.Region = None for y in value: y._Region = self self._Regions = value Regions = property(getRegions, setRegions) def addRegions(self, *Regions): for obj in Regions: obj.Region = self def removeRegions(self, *Regions): for obj in Reg...
import argparse from pdnssync.database import Database from pdnssync.parse import Parser from pdnssync.error import get_warn, get_err parser = Parser() def validate(): domains = parser.get_domains() for d in sorted(domains): domains[d].validate(domains) def sync(db): all_db_domains = db.get_dom...
for j in records[i]: print('C %s %s' % (i[0], j.data)) if i[1] == 'SRV': for j in records[i]: print('S %s %s %s' % (i[0], j.prio, j.data)) if i[1] == 'TXT': for j in records[i]: print('X %s %s'...
aparser = argparse.ArgumentParser() aparser.add_argument("-v", "--verbose", action="count", default=0, help="increase output verbosity") aparser.add_argument("-w", "--werror", action="store_true", help="also break on warnings") aparser.add_argument('files', metavar='file', nargs='+', help='the files to ...
from __future__ impo
rt absolute_import from .base import * from bundle_config import config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['postgres']['database'], 'USER': config['postgres']['username'], 'PASSWORD': config['postgres']['password'], ...
onfig['postgres']['host'], } } CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '{host}:{port}'.format( host=config['redis']['host'], port=config['redis']['port']), 'OPTIONS': { 'PASSWORD': config['redis']['password'], ...
import numpy as np import canal as canal from .util import NumpyTestCase class FromJSONTestCase(NumpyTestCase): class Measurement(canal.Measurement): int_field = canal.IntegerField() alternate_db_name = canal.IntegerField(db_name="something_else") float_field = canal.FloatField() ...
sertndArrayEqual( test_series.tag_2, np.array(10*["2"]) ) def test_from_json_bad_input(self): with self.assertRaises(ValueError): list(self.Measurement.from_json({"bad": "input"})) def test_empty_json(self): content = dict() with self.assertR...
sults=[dict( series=[dict( name="SomeOtherMeasurement", columns=[ "time", "int_field", "float_field", "bool_field", "string_field", ...
import os import sys def main(args): if len(args) != 2: print("Usage: python project-diff.py [path-to-project-1] [path-to-project-2]") return dir1 = args[0] dir2 = args[1] project1 = collect_text_files(dir1) project2 = collect_text_files(dir2) files_only_in_1 = [] files_only_in_2 = [] files_...
ving all # lines from lines 1 and adding all lines from lines 2. for x in range(length_2 + 1): grid[x][0] = (x, 'left') for y in range(length_1 + 1): grid[0][y] = (y, 'up') grid[0][0] = (0, 'diag') # Populate the grid. Figure out the minimum diff to get to each point. for y in range(1, length_1 + 1...
y] = (grid[x - 1][y - 1][0], 'diag') elif (grid[x - 1][y][0] <= grid[x][y - 1][0]): grid[x][y] = (grid[x - 1][y][0] + 1, 'left') else: grid[x][y] = (grid[x][y - 1][0] + 1, 'up') # Start from the bottom right corner and walk backwards to the origin x = length_2 y = length_1 diff_chai...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
import experiments.ud_xilinx.server as UdXilinxExperiment import weblab.data.server_type as ServerType import weblab.experiment.util as ExperimentUtil module_directory = os.path.join(*__name__.split('.')[:-1]) class UdDemoXilinxExperiment(UdXilinxExperiment.UdXilinxExperiment): FILES = { 'PLD' : '...
super(UdDemoXilinxExperiment,self).__init__(coord_address, locator, cfg_manager, *args, **kwargs) file_path = data_filename(os.path.join(module_directory, self.FILES[self._xilinx_device])) self.file_content = ExperimentUtil.serialize(open(file_path, "rb").read()) @Override(UdXilinxExperiment....
__author__ = 'roman' from django.utils.functional import SimpleLazyObject from . import get_card as _get_card def get_card(request):
if not hasattr(request, '_cached_card'): request._cached_card = _get_card(request) return request._cached_card class CardAuthMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( "The Card authentication middleware requires session middleware...
"'card.middleware.CardAuthMiddleware'." ) request.card = SimpleLazyObject(lambda: get_card(request))
# Step 1: Make all the "turtle" commands available to
us. import turtle # Step 2: create a new turtle, we'll call him simon simon = turtle.Turtle() # Lets draw a square! for loop in range(4): simon.forward(200) si
mon.left(90)
#!/usr/bin/env python3 import os import shutil import subprocess import gettext version = '4.4.0' builds = [ { 'language': 'de', 'paper': 'a4paper', 'babel': 'ngerman' }, { 'language': 'en', 'paper': 'letterpaper', 'babel': 'USenglish' }, { 'language': 'es', 'paper': 'a4paper', 'babel': 'spanish' },
{ 'language': 'fr', 'paper': 'a4paper', 'babel': 'french' }, { 'language': 'hu', 'paper': 'a4paper', 'babel': 'magyar' }, { 'language': 'it', 'paper': 'a4paper', 'babel': 'italian' }, { 'language': 'sl', 'paper': 'a4paper', 'babel': 'slovene' }, { 'language': 'uk', 'paper': 'a4paper', 'babel': 'ukrainian' }, ] fo...
ng for language "%s"' % ( language ) ) subprocess.Popen( ['msgfmt', 'locale/%s/LC_MESSAGES/%s.po' % ( language, manual ), '-o', 'locale/%s/LC_MESSAGES/%s.mo' % ( language, manual ) ] ).wait() env = os.environ.copy() with open('%s/index.rst' % (manual)) as f: title = f.readline().rstrip() title = gettext....
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', 'flag=ceph'], [TestAction.create_volume, 'volume1', 'flag=ceph,scsi'], [TestAction.attach_volume, 'vm1...
me3'], [TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot1'], [TestAction.clone_vm, 'vm1', 'vm2'], [TestAction.create_volume_backup, 'volume2', 'volume2-backup1'], [TestAction.stop_vm, 'vm1'], [TestAction.use_volume_backup, 'volume2-backup1'], [TestAction.start_vm, 'vm1'], [TestAction.create_vm_snapshot...
'vm1-snapshot1'], [TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot9'], [TestAction.clone_vm, 'vm1', 'vm3', 'full'], [TestAction.delete_volume_snapshot, 'vm1-snapshot5'], [TestAction.stop_vm, 'vm2'], [TestAction.change_vm_image, 'vm2'], [TestAction.delete_vm_snapshot, 'vm2-snapshot9'], ]) ''' The fina...
# -*- codin
g: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 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 ve...
uted 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 no...
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class STARInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing STAR 2.4.0g1 on %s" % (node.alias)) node.ssh.execute('wget -c -P /opt/software/star https://g...
>> /usr/local/Modules/applications/star/2.4.0g1') node.ssh.execute('echo "set root /opt/software/star/STAR-STAR_2.4.0g1" >> /usr/local/Modules/applications/s
tar/2.4.0g1') node.ssh.execute('echo -e "prepend-path\tPATH\t\$root/bin/Linux_x86_64" >> /usr/local/Modules/applications/star/2.4.0g1')
#! /bin/python2 import numpy import cv2 import os import struct BLACK = (0,) WHITE = (255,) DIR_OUT = "./img/" SIZE_CANVAS = 50 SIZE_FEATURE = 28 SIZE_BLOCK = 32 DIGITS = tuple([chr(ord("0") + i) for i in range(10)] + [""]) FONTS = (cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_DUPLEX, c...
NTS)) thickness = numpy.random.randint(1, 3) base_line = cv2.getTextSize(DIGITS[id_digit], FONTS[id_font], 1.0, thickness)[1] + 1 scale_font = float(numpy.random.randint(40, 60)) / 100.0 scale = float(SIZE_BLOCK) * 0.5 * scale_font / float(base_line) shift = float(SIZE_CANVAS) / ...
K) * 0.5 * scale_font cv2.putText(copy, DIGITS[id_digit], (0, 2 * base_line + 1), FONTS[id_font], 1.0, BLACK, thickness) copy = cv2.warpAffine(copy, numpy.matrix([[scale, 0.0, shift], [0.0, scale, shift]]), copy.shape, borderValue = WHITE) # draw lines t...
from django.conf.urls import url, include from django.contrib import admin from rest_framework import
routers, serializers, viewsets from .views import Ho
mePageView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^admin/', admin.site.urls), url(r'^', include('slackdata.urls')), ]
from django.apps import
AppConfig class BugReportsConfig(AppConfig):
name = "bug_reports"
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
# # # # 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. # # ...
param['pb'] = param['pe'] label = 'BSC pe={pe} m={m} n={n}'.format(**param) else: label = 'GBMM pe={pe} pb={pb} m={m} n={n}'.format(**param) pmf = errpmf(**param) ober = ber_out(param['pe'], param['pb'], pmf) if 'label' not in plotargs: plotargs[...
param['pb'] = param['pe'] label = 'BSC pe={pe} m={m} n={n}'.forma
t(**param) else: label = 'GBMM pe={pe} pb={pb} m={m} n={n}'.format(**param) pmf = errpmf(**param) ober = ber_out(param['pe'], param['pb'], pmf) if 'label' not in plotargs: plotargs['label'] = label n = param['n'] frac_t = 100 * t / n k =...
from __future__ import print_function from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GObject class ImageMenu(Gtk.EventBox): def __init__ (self, image, child): GObject.GObject.__init__(self) self.add(image) self.subwindow = Gtk.Window()...
orated(False) self.subwindow.set
_resizable(False) self.subwindow.set_type_hint(Gdk.WindowTypeHint.DIALOG) self.subwindow.add(child) self.subwindow.connect_after("draw", self.__sub_onExpose) self.subwindow.connect("button_press_event", self.__sub_onPress) self.subwindow.connect("motion_notify_event", sel...
# -*- coding: utf-8 -*- """ test_sphinx ~~~~~~~~~~~ General Sphinx test and check o
utput. """ import sys import pytest import sphinx from ipypublish.sphinx.tests import get_test_source_dir from ipypublish.tests.utils import HTML2JSONParser @pytest.mark.sphinx(buildername="html", srcdir=get_test_source_dir("bibgloss_basic")) def test_basic(app, status, warning, get_sphinx_app_output, data_regressi...
atus.getvalue() # Build succeeded warnings = warning.getvalue().strip() assert warnings == "" output = get_sphinx_app_output(app, buildername="html") parser = HTML2JSONParser() parser.feed(output) if sphinx.version_info >= (2,): data_regression.check(parser.parsed, basename="test_basi...
#! /usr/bin/env python # -*- coding: UTF8 -*- # Este arquivo é parte do programa Carinhas # Copyright 2013-2014 Carlo Oliveira <carlo@nce.ufrj.br>, # `Labase <http://labase.selfip.org/>`__; `GPL <http://is.gd/3Udt>`__. # # Carinhas é um software livre; você pode redistribuí-lo e/ou # modificá-lo dentro dos termos da Li...
er = main("')[1].split('e0cb4e39e071")')[0] + 'e0cb4e39e071' expected_record = "{'module': 'projeto2222', 'user': 'pr
ojeto2222-lastcodename', 'idade': '00015'," received_record = cs.DRECORD.get(rec_id) assert expected_record in str(received_record),\ "{}: {}".format(rec_id, received_record) def _get_id(self, ref_id='e0cb4e39e071', url='/static/register?doc_id="10000001"&module=projeto2222'): "...
from tim
e import time fr
om pychess.Utils.lutils.lmovegen import genAllMoves from pychess.Utils.lutils.lmove import toLAN def do_perft(board, depth, root): nodes = 0 if depth == 0: return 1 for move in genAllMoves(board): board.applyMove(move) if board.opIsChecked(): board.popMove() ...
#!/usr/bin/python from __future__ import
print_functio
n import weather, time a = time.time(); weather.hourly.load("ottawa"); print time.time() - a raw_input()
def test_expressions_requires_index_name(self): msg = 'An index must be named to use expressions.' with self.assertRaisesMessage(ValueError, msg): models.Index(Lower('field')) def test_expressions_with_opclasses(self): msg = ( 'Index.opclasses cannot be used with exp...
f): index = models.Index(fields=['title'], db_tablespace='idx_tbls') index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.db.models.Index') self.assertEqual(args, ()) self.assertEqual( kwargs, {'fi...
index = models.Index( name='big_book_index', fields=['title'], condition=models.Q(pages__gt=400), ) index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.db.models.Index') self.assertEqual(args,...
# -*- coding: utf-8 -*- # # pynest_api_template.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 Lic...
ublic License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """[[ This template demonstrates how to create
a docstring for the PyNEST API. If you have modified an API, please ensure you update the docstring! The format is based on `NumPy style docstring <https://numpydoc.readthedocs.io/en/latest/format.html>`_ and uses reStructuredText markup. Please review the syntax rules if you are unfamiliar with either...
# Copyright 2019 - Nokia # # 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, sof...
NY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from vitrage.evaluator.template_functions import function_resolver from vitrage.evaluator.template_functions import GET_PARAM from vitrage.evaluator.template_functions.v2.functions...
_custom_fault_result from vitrage.evaluator.template_validation.base import ValidationError from vitrage.evaluator.template_validation.content.base import \ get_content_correct_result class GetParamValidator(object): @classmethod def validate(cls, template, actual_params): try: functi...
# # 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 l...
anguage governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from ...
exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class lldpparam(base_resource) : """ Configuration for lldp params resource. """ def __init__(self) : self._holdtimetxmult = 0 self._timer = 0 self._mode = "" @property def holdtimetxmult(self) : """A...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from gakkgakk.app import create_app from gakkgakk.models impo
rt User from gakkgakk.settings import DevConfig, ProdConfig from gakkgakk.database import db reload(sys) sys.setdefaultencoding('utf-8') app = create_app(ProdConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return ...
r model by default. """ return {'app': app, 'db': db, 'User': User} @manager.command def test(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server(host='0.0.0.0', threaded=True)) manager.add_command('she...
from fnmatch import fnmatchcase from trac.config import Option from trac.core import * from trac.perm import IPermissionPolicy revision = "$Rev: 11490 $" url = "$URL: https://svn.edgewall.org/repos/trac/tags/trac-1.0.1/sample-plugins/permissions/public_wiki_policy.py $" class PublicWikiPolicy(Component): """Allo...
s a resource if action == 'WIKI_VIEW': # (think 'VIEW' here) pattern = self.view else: pattern = self.modify if fnmatchcase(resource.id, pattern): return True else: # ... i...
return True # this policy ''may'' grant permissions on some wiki pages else: # coarse-grained permission check # # support for the legacy permission checks: no resource specified # and realm information in the action name itself. # ...
#!/usr/bin/env python from settings import Settings from scan import Scanner from logger import Logg
er def main(): try: #Read config file settings=Setting
s() #Set up logger logger=Logger(settings) #Create scanner scanner=Scanner(settings,logger) #Begin scanning scanner.StartScanning() except KeyboardInterrupt: scanner.StopScanning() if __name__ == "__main__": main()
aise a """ return (expectation, variance) def _ftl_jump(self, y, K, **kwargs): r""" Jump to a totally new mixture of K number of gaussians. """ logger.debug("Re-initializing with K-means++ at K = {}".format(K)) # Initialize new centroids by k-means++ ...
raise UnsureError mixtures.append
(mixture) mls.append(meta["message_length"]) print(np.std(mls)) index = np.argmin(mls) mixture = mixtures[index] #slogdet = np.sum(np.log(np.linalg.det(mixture.covariance))) slogdet = np.sum(_slogdet(mixture.covariance, mixture.covariance_type)) self._propos...
from constants import constants, callback_name_list from controller import plan_controller, navigable_list_controller, navigable_inline_keyboard_controller, settings_controller from telepot.namedtuple import ReplyKeyboardRemove from bot import bot from decorators.callback import callback_dict as callback_list """ call...
sg['message']['message_id'] for callback in callback_list: if callback_data.startswith(callback): answer = callback_list[callback](callback_query_id, callback_data, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if answer == None: act
ion_prefix[chat_id] = " " else: action_prefix[chat_id] = answer break else: bot.sendMessage(chat_id, constants["callbackNotFound"], reply_markup=ReplyKeyboardRemove()) action_prefix[chat_id] = " " bot.answerCallbackQuery(callback_query_id)
f _GetSelectedLineNumbers(self): # used for the comment/uncomment machinery from ActiveGrid selStart, selEnd = self._GetPositionsBoundingSelectedLines() start = self.LineFromPosition(selStart) end = self.LineFromPosition(selEnd) if selEnd == self.GetTextLength(): end ...
dataObj = wx.TextDataObject() clip = wx.Clipboard().Get() clip.Open() success = clip.GetData(dataObj) clip.Close() if success: txt = dataObj.GetText() # dealing with unicode error in wx3 for Mac if parse_version(wx.__version__) >= pa
rse_version('3') and sys.platform == 'darwin' and not PY3: try: # if we can decode from utf-8 then all is good txt.decode('utf-8') except Exception as e: logging.error(str(e)) # if not then wx conversion brok...
""" Created on 05/12/13 @author: zw606 simple example assumes images and labels files are named the same but in different folders (one folder for images, one folder for labels) """ import glob from os.path import join, basename from spatch.image import spatialcontext from spatch.image.
mask import get_boundary_mask from spatch.segmentation.patchbased import SAPS from spatch.utilities.io import open_image, get_affine, save_3d_labels_data from spatch.image.spatialcontext import COORDINATES, GDT INITIAL_SPATIAL_INFO = COORDINATES REFINEMENT_SPATIAL_INFO = GDT def get_subject_id(fileName): namePar...
esPath, labelsPath, patchSize, k, spatialWeight, spatialInfoType=INITIAL_SPATIAL_INFO, maskData=None, numProcessors=21): targetImage = open_image(join(imagesPath, targetFile)) # Ensure target subject is not included in atlases targetId = get_subject_id(targetFile) trainingSet =...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from random import random from math import floor from .common import InfoExtractor from ..utils import ( ExtractorError, remove_end, sanitized_Request, ) class IPrimaIE(InfoExtractor): _WORKING = False _VALID_URL = r'https...
eGEO') if zoneGEO != '0': base_url = base_url.replace('token', 'token_' + zoneGEO) formats = [] for format_id in ['lq', 'hq', 'hd']: filename = self._html_search_regex( r'"%s_id":(.+?),' % format_id, webpage, 'filename') if filename == 'null'...
0-9]{10}|WEB)-([0-9]+)[-_]', filename, 'real video id') if format_id == 'lq': quality = 0 elif format_id == 'hq': quality = 1 elif format_id == 'hd': quality = 2 filename = 'hq/' + filename ...
# -*- coding: utf-8 -*- # # This file is covered by the GNU Public Licence v3 licence. See http://www.gnu.org/licenses/gpl.txt # ''' List of controllers, with indirections to object loaded by Spring ''' import springpython.context from django.http import HttpResponse from django.template import loader, Context from o...
elif isinstance(self.prehandler, PreHandler): tpl = self.prehandler.handle(request) return tpl def posthandle(self, request, tpl): if isinstance(self.posthandler, list): for ph in self.posthandler: if isinstanc
e(ph, PostHandler): ph.handle(request, tpl) elif isinstance(self.posthandler, PostHandler): self.posthandler.handle(request, tpl) class PreHandler(object): def handle(self, request): pass class PostHandler(object): def handle(self, request, tpl): pass # Templates loading class TemplatesContainer(ob...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url # from django.conf import settings urlpatterns = patterns('www.sight.views', url(r'^$', 'sight_map'), url(r'^(?P<sight_id>\d+)$', 'sight_detail')
,
)
# -*- coding: UTF-8 -*- # Copyright 2016-2017 Rumma & Ko Ltd # License: BSD (see file COPYING for details) from lino_xl.lib.tickets.models import * from lino.api import _ Ticket.hide_elements('closed') # class Ticket(Ticket): # class Meta(Ticket.Meta): # app_label = 'tickets' # verbose_name = _(...
tickets.Ticket', 'state', default=TicketStates.todo.as_callable) class T
icketDetail(TicketDetail): main = "general history_tab more" general = dd.Panel(""" general1:60 votes.VotesByVotable:20 uploads.UploadsByController description:30 comments.CommentsByRFC:30 skills.DemandsByDemander #working.SessionsByTicket:20 """, label=_("General")) general1 = """ summary...
#Key, dictionary[key, int], int --> dictionary[key, int] #Given a key, dictionary and increment, set the dictionary value at #key to dictionary[key] + inc. If there is no old value, set to inc
def incrementDict(dictKey, dictionary, inc=1): if(dictKey in dictionary): dictionary[dictKey] += inc else: dictionary[dictKey] = inc return dictionary #dictionary[key, int] -> boolean #Given a dictionary of counts return true if at least one is non zero #and false otherwise def nonZeroCount(dictionary)
: for k,v in dictionary.iteritems(): assert(v >= 0) if(v > 0): return True return False
_helper import os import stat import sys import uu import io plaintext = b"The symbols on top of your keyboard are !@#$%^&*()_+|~\n" encodedtext = b"""\ M5&AE('-Y;6)O;',@;VX@=&]P(&]F('EO=7(@:V5Y8F]A<F0@87)E("% (R0E *7B8J*"E?*WQ^"@ """ # Stolen from io.py class FakeIO(io.TextIOWrapper): """Text I/O implementati...
dtextwrapped(0o666, "t1").decode("ascii")) sys.stdout = FakeIO() uu.decode("-", "-") stdout = sys.stdout sys.stdout = self.stdout sys.stdin = self.stdin self.assertEqual(stdout.getvalue(), plaintext.decode("ascii")) class UUFileTest(unittest.TestCase): def setUp(sel...
leanup(os_helper.unlink, self.tmpin) self.addCleanup(os_helper.unlink, self.tmpout) def test_encode(self): with open(self.tmpin, 'wb') as fin: fin.write(plaintext) with open(self.tmpin, 'rb') as fin: with open(self.tmpout, 'wb') as fout: uu.encode(fi...
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import Gl...
ontext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the e...
ample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing...
from django.co
nf.urls import patterns, include, url from cover.views import CoverView urlpatterns = patterns('cover.views', url(
r'^$', CoverView.as_view(), name='cover'), )
SID specification. # pylint: disable=no-init # Abstract classes do not define __init__. # pylint: disable=too-few-public-methods # Some interfaces are specified as 'markers' and include no methods. # pylint: disable=too-many-public-methods # Number of methods are defined in specification # pylint: disable=t...
type book_search_record_type: ``osid.type.Type`` :return: the book search record :rtype: ``osid.commenting.records.BookSearchRecord`` :raise:
``NullArgument`` -- ``book_search_record_type`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unsupported`` -- ``has_record_type(book_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # ...
on'] } elif location in self.location_not_found: # Don't call the API. pass else: url = 'https://maps.googleapis.com/maps/api/geocode/json' params = {'sensor': 'false', 'address': location} r = self.requests.get(url, params=params...
item = hit['_source'] cache[item[_key]] = item _from += res_size r = self.requests.get(url+"&from=%i" % _from) type_items =
r.json() if 'hits' not in type_items: break return cache def geo_locations_from_es(self): return self.get_github_cache("geolocations", "location") def geo_locations_to_es(self): max_items = self.elastic.max_items_bulk current = 0 bu...
from django.core.management.base import BaseCommand from candidates.models import OrganizationExtra class Command(BaseCommand): def handle(self, *args, **options): for party_extra in OrganizationExtra.objects \ .filter(base__classification='Party') \
.select_related('base') \ .prefetch_related('images'): images = list(party_extra.images.all()) if len(images) < 2: continue print "=====================================================" party = party_extra.base print...
' ' + image.source.encode('utf-8') print ' ' + image.image.url
''' Created on Dec 23, 2013 @author: Chris ''' import sys import wx from gooey.gui.lang import i18n from gooey.gui.message_event import EVT_MSG class MessagePump(object): def __init__(self): # self.queue = queue self.stdout = sys.stdout # Overrides stdout's write method def write(self, text): ...
dout = MessagePump() sys.stdout.write = self.WriteToDisplayBox def AppendText(self, txt)
: self.cmd_textbox.AppendText(txt) def WriteToDisplayBox(self, txt): if txt is not '': self.AppendText(txt) def OnMsg(self, evt): pass