prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# -*- coding: utf-8 -*- import sys, os, time from Tools.HardwareInfo import HardwareInfo def getVersionString(): return getImageVersionString() def getImageVersionString(): try: if os.path.isfile('/var/lib/opkg/status'): st = os.stat('/var/lib/opkg/status') else: st = os.stat('/usr/lib/ipkg/status') tm ...
ver.split("-") #return driver[:4] + "-"
+ driver[4:6] + "-" + driver[6:] return driver[5] except: return "unknown" # For modules that do "from About import about" about = sys.modules[__name__]
row in channelRows: print row centered = False weightXYFilledOut = False if len(channelRows) > 0: volume = '' compositeId = '' channels = [] for row in channelRows: compositeId = row[config.colCompositesCompositeId] fileId = row[config.colCompositesFil...
# vgInpaint.vgInpaint(filterVolum
e, '', optionOverwrite=False, directCall=False) # make folder lib.mkdir(outputSubfolder) # read small dbs into memory compositingInfo = lib.readCsv(config.dbCompositing) # when to turn centering on/off retargetingInfo = lib.readCsv(config.dbRetargeting) # remapping listed targets # ope...
import os import sys import unittest2 import mitogen import mitogen.ssh import mitogen.utils import testlib import plain_old_module def get_sys_executable(): return sys.executable def get_os_environ(): return dict(os.environ) class LocalTest(testlib.RouterMixin, unittest2.TestCase): stream_
class = mitogen.ssh.Stream def test_stream_name(self): context = self.router.local() pid = context.call(os.getpid) self.assertEquals('local.%d' % (pid,), context.name) class PythonPathTest(testlib.RouterMixin, unittest2.TestCase): stream_class = mitogen.ssh.Stream def test_inheri...
lf): os.environ['PYTHON'] = sys.executable context = self.router.local( python_path=testlib.data_path('env_wrapper.sh'), ) self.assertEquals(sys.executable, context.call(get_sys_executable)) env = context.call(get_os_environ) self.assertEquals('1', env['EXECUT...
# # Copyright 2020 University of Washington # # 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 WARR...
CHANTABILITY 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 # # Au...
: # Parameters for 11ax nA = np.linspace(5, 50, 10) CWmin = 15 CWmax = 1023 L_DATA = 1500 * 8 # data size in bits L_ACK = 14 * 8 # ACK size in bits #B = 1/(CWmin+1) B=0 EP = L_DATA/(1-B) T_GI = 800e-9 # guard interval in seconds T_SYMBOL_ACK = 4e-6 ...
from django.co
nf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^', include('ebets.urls')), url(r'^admin
/', include(admin.site.urls)), )
# vpnr 48 run_trial(hori2, duration=4.000, speed=300) run_trial(rws[2], duration=8.0) run_trial(rbs[12], duration=8.0) run_trial(rws[6], duration=8.0) run_trial(rbs[22], duration=8.0) run_trial(cm200, duration=8.0, speed=150) run_trial(cm200, duration=8.0, speed=800) run_trial(rbs[6], duration=8.0) run_trial(msm0, dura...
) run_trial(cm400, duration=8.0, speed=150) run_trial(hori0, duration=4.000, speed=300) run_trial(cm400, duration=8.0, speed=800) show(u'Machen Sie eine kurze Pause.\n\nWeiter mit Leertaste.', wait_keys=('space',)) run_trial(msm1, duration=5.000, speed=300) run_trial(msm2, du
ration=5.000, speed=300) run_trial(msm0, duration=2.500, speed=800) run_trial(mem2, duration=4.000, speed=400) run_trial(cm200, duration=8.0, speed=600) run_trial(hori1, duration=1.500, speed=800) run_trial(msm0, duration=9.000, speed=150) run_trial(hori0, duration=1.500, speed=800) run_trial(mem2, duration=2.500, spee...
from django.test import TestCase from api.helpers import user_service from api.factories import UserFactory, PostFactory class UserServiceTest(TestCase): POSTS_PER_USER = 10 def setUp(self): self.main_user = UserFactory() self.follower = UserFactory() self.test_user = UserFactory() ...
l(len(posts), self.POSTS_PER_USER * 2) for post in posts: self.assertIn(pos
t.creator_id, [self.main_user.id, self.follower.id]) def test_user_feed_returns_posts_ordered_correctly(self): posts = user_service.get_user_feed(self.follower.id, 0, 20) for i in range(0, len(posts) - 1): self.assertGreater(posts[i].created_at, posts[i + 1].created_at) def test_u...
Joris Jensen <jjensen@techfak.uni-bielefeld.de> # # License: BSD 3 clause from __future__ import division import numpy as np from scipy.optimize import minimize from sklearn.utils import validation from .rslvq import RslvqModel class LmrslvqModel(RslvqModel): """Localized Matrix Robust Soft Learning Vector Qua...
t += np.math.log(s1 / s2) return -out def _optimize(self, x, y, random_state): nb_prototypes, nb_features = self.w_.shape nb_classes = len(self.classes_) if not isinstance(self.classwise, bool): raise ValueError("classwise must be a boolean") if self.initialdim i...
self.classwise: self.dim_ = nb_features * np.ones(nb_classes, dtype=np.int) else:
""" Windows Process Control winprocess.run launches a child process and returns the exit code. Optionally, it can: redirect stdin, stdout & stderr to files run the command as another user limit the process's running time control the process window (location, size, window state, desktop) Works on Windows NT, 20...
andles def wait(self, mSec=None): """ Wait for process to finish or for specified number of milliseconds to elapse. """ if mSec is None: mSec = win32event.INFINITE return win32event.WaitFo
rSingleObject(self.hProcess, mSec) def kill(self, gracePeriod=5000): """ Kill process. Try for an orderly shutdown via WM_CLOSE. If still running after gracePeriod (5 sec. default), terminate. """ win32gui.EnumWindows(self.__close__, 0) if self.wait(gracePeriod) != ...
f
rom __future__ import print_function from twython import Twython import util class TwitterBot(util.SocialMediaBot): """ Social Media Bot for posting updates to Tumblr """
NAME = "twitter" def __init__(self, **kwargs): super(TwitterBot, self).__init__(**kwargs) self.client = Twython(*self.oauth_config) def post_update(self): text = self.generate_text(limit_characters=140) self.client.update_status(status=text) if __name__ == "__main__": ...
:type cm: :class:`ClassManager` """ def __init__(self, buff, cm) : self.CM = cm self.field_idx_diff = readuleb128( buff ) self.access_flags = readuleb128( buff ) self.field_idx = 0 self.name = None self.proto = None self.class_name = None self....
Setup the init value object of the field :param value: the init value :type value: :class:`EncodedValue` """ self.init_value = value def get_init_value(self) : """ Return the init value object of the field :rtype: :class:`En...
f + val def get_field_idx_diff(self) : """ Return the index into the field_ids list for the identity of this field (includes the name and descriptor), represented as a difference from the index of previous element in the list :rtype: int """ return sel...
from gateway import Gateway, ge
t_gateway from integration import Integration, get_inte
gration from utils.credit_card import CreditCard
# -*- coding: utf-8 -*- from datetime import datetime from django.db import models from django.core.urlresolvers import reverse from ..core.models import TimeStampedModel class TipoDiagnosticos(TimeStampedModel): nombre = models.CharField(max_length=150, blank=False, null=False, verbose_name=u'Diagnóstico') ...
help_text=u'Formato: dd/mm/yyyy
', default=datetime.now()) hora = models.TimeField(blank=False, null=False, help_text=u'Formato: hh:mm', default=datetime.now())
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-13 11:16 from __future__ import unicode_literals from django.db import mig
rations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('restaurant', '0014_remove_menuimage_menu_name'), ] operations = [ migrations.AlterModelOptions( name='menuimage', options={'verbose_name': 'MenuImage', 'verb...
l': 'MenuImages'}, ), migrations.AlterField( model_name='menuimage', name='restaurant', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='menu_image', to='restaurant.Restaurant'), ), ]
#!/usr/bin/env python from Auth import * keyId = plc_api.GetKeys(auth,
{'person_id': 249241}, ['key_id', 'key']) for key in keyId: print "A new key:" print "Key value ->", key['key'] print "K
ey id ->",key['key_id']
### # Copyright (c) 2012, Valentin Lorentz # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditi...
XX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.unknown # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = {} # This is a url where the most recent plugin package can be downloaded. __url__ = '' # 'http://supybot....
) # In case we're being reloaded. # Add more reloads here if you add third-party modules and want them to be # reloaded when this plugin is reloaded. Don't forget to import them as well! if world.testing: from . import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 tabstop=4 expa...
# -*- coding: utf-8 -*- """ Read Tweetworks API users from XML responses. Nicolas Ward @ultranurd ultranurd@yahoo.com http://www.ultranurd.net/code/tweetworks/ 2009.06.19 """ """ This file is part of the Tweetworks Python API. Copyright © 2009 Nicolas Ward Tweetworks Python API is free software: you can redistribut...
er numeric user ID """ # Initialize an empty user if no XML was provided if xml == None: self.id = None self.username = "" self.avatar_url = "" self.twitter_id = None return # User ID
self.id = int(xml.xpath("/user/id/text()")[0]) # User's Twitter username self.username = unicode(xml.xpath("/user/username/text()")[0]) # User avatar URL (loaded from Amazon S3, obtained from Twitter) self.avatar_url = unicode(xml.xpath("/user/avatar_url/text()")[0]) # User's...
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
sion = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.md', encoding='utf-8') as f: readme = f.read() with open('CHANGELOG.md', encoding='utf-8') as f: changel...
g_description=readme + '\n\n' + changelog, long_description_content_type='text/markdown', license='MIT License', author='Microsoft Corporation', author_email='azpysdkhelp@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python', keywords="azure, azure sdk", # update with search keywo...
''' Created on 5/02/2010 @author: henry@henryjenkins.name ''' import datetime class user(object): ''' classdocs ''' dataUp = None dataDown = None macAddress = "" name = "" def __init__(self, mac="", name=""): ''' Constructor ''' self.name = name ...
data = se
lf.dataUp[date]['on'][type] + self.dataUp[date]['off'][type] return data def __getTotalUpData(self, type, peak='other'): dataTotal = 0 for date, data in self.dataUp.items(): if peak == 'on' or peak == 'off': dataTotal += data[peak][type] else: ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 Zadara Storage Inc. # Copyright (c) 2011 OpenStack Foundation # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2011...
pache.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, e
ither express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Built-in volume type properties.""" from oslo.config import cfg from cinder import context from cinder import db from cinder import exception from cinder.openstack.common.db impo...
import unittest import pystache from pystache import Renderer from examples.nested_context import NestedContext from examples.complex import Complex from examples.lambdas import Lambdas from examples.template_partial import TemplatePartial from examples.simple import Simple from pystache.tests.common import EXAMPLES_...
actual = renderer.render(view) self.assertString(actual, u"one and foo and two") def test_looping_and_negation_context(self): template = '{{#item}}{{header}}: {{name}} {{/item}}{{^item}} Shouldnt see me{{/item}}' context = Complex() renderer = Renderer() actual = ren...
ors: blue ") def test_empty_context(self): template = '{{#empty_list}}Shouldnt see me {{/empty_list}}{{^empty_list}}Should see me{{/empty_list}}' self.assertEqual(pystache.Renderer().render(template), "Should see me") def test_callables(self): view = Lambdas() view.template = '...
""" Read graphs in LEDA format. See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html """ # Original author: D. Eppstein, UC Irvine, August 12, 2003. # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain. __author__ = """Aric Hagberg (hagberg@lanl.gov)""...
ip().strip('|{}| ') if symbol=="": symbol=str(i) # use int if no label - could be trouble node[i]=symbol G.add_nodes_from([s for i,s in node.items()]) # Edges m = int(lines.next()) # number of edges for i in range(m): try: s,t,reversal,label=lines.next().split() ...
d_edge(node[int(s)],node[int(t)],label=label[2:-2]) return G
from model.contact import Contact from model.group import Group from fixture.orm import ORMFixture import random def test_del_contact_from_group(app): orm = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="") # check for existing any group if len(orm.get_group_list()) == 0: a...
up.id, group.id) old_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id)) contact_in_group = random.choice(old_contacts_in_group) # choose random contact from list app
.contact.delete_contact_from_group_by_id(contact_in_group.id, group.id) new_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id)) old_contacts_in_group.remove(contact_in_group) assert sorted(old_contacts_in_group, key=Contact.id_or_max) == sorted(new_contacts_in_group, key=Contact.id_or_max)
-------------------------------------------- # jsonrpc - jsonrpc interface for XBMC-compatible remotes # ----------------------------------------------------------------------- # $Id$ # # JSONRPC and XBMC eventserver to be used for XBMC-compatible # remotes. Only tested with Yatse so far. If something is not working, #...
yield open(filename).read(), None, None log.error('no file: %s' % filename) yield None else: yield None def Application_GetProperties(self, properties): """ JsonRPC Callback Application
.GetProperties """ result = {} for prop in properties: if prop == 'version': result[prop] = {"major": 16,"minor": 0,"revision": "a5f3a99", "tag": "stable"} elif prop == 'volume': result[prop] = 100 elif prop == 'muted': ...
#!/usr/bin/env python # # Copyright (C) 2011 Andy Aschwanden # # This file is part of PISM. # # PISM 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 l...
# Fill value fill_value = -9999 bed_valid_min = -5000.0 thk_valid_
min = 0.0 bed = np.flipud(zBase) dem = np.flipud(zSurf) # ignored by bootstrapping thk = np.flipud(zSurf-zBase) # used for bootstrapping # Replace NaNs with zeros thk = np.nan_to_num(thk) # There are some negative thickness values # Quick and dirty: set to zero # some inconsistencies in the original data still needs ...
#!/usr/bin/python """This script lists classes and optionally attributes from UML model created with Gaphor.""" import optparse import sys from gaphor import UML from gaphor.application import Session # Setup command line options. usage = "usage: %prog [options] file.gaphor" def main(): parser = optparse.Opti...
(options, args) = parser.parse_args() if len(args) != 1: parser.print_help() sys.exit(1) # The model file to load. model = args[0] # Create the Gaphor application object. ses
sion = Session() # Get services we need. element_factory = session.get_service("element_factory") file_manager = session.get_service("file_manager") # Load model from file. file_manager.load(model) # Find all classes using factory select. for cls in element_factory.select(UML.Class): ...
from .rest import RestClient class Rules(object): """Rules endpoint implementation. Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' token (str): Management API v2 Token telemetry (bool, optional): Enable or disable Telemetry (defaults to True) t...
(str): The id of the rule to delete. See: https://auth0.com/docs/api/management/v2#!/Rules/delete_rules_by_id """ return self.client.delete(self._url(id)) def update(self, id, body): """Update an existing rule Args: id (str): The id of the rule to modify. ...
See: https://auth0.com/docs/api/v2#!/Rules/patch_rules_by_id """ return self.client.patch(self._url(id), data=body)
import unittest import os from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase from katello.tests.core.organization import organization_data from katello.tests.core.template import template_data import katello.client.core.template from katello.client.core.template import Delete from k...
lowed_options = [ ('--org=ACME', '--name=template_1'), ('--org=ACME', '--environment=dev', '--name=template_1'), ] class TemplateInfoTest(CLIActionTestCase): ORG = organization_data.ORGS[0] ENV = organization_data.ENVS[0] TPL = template_data.TEMPLATES[0] OPTIONS = { 'org...
tUp(self): self.set_action(Delete()) self.set_module(katello.client.core.template) self.mock_printer() self.mock_options(self.OPTIONS) self.mock(self.module, 'get_template', self.TPL) self.mock(self.action.api, 'delete') def test_it_finds_the_template(self): ...
from datetime imp
ort datetime from flask import Blueprint, jsonify, request from app.dao.fact_notification_status_dao import ( get_total_notifications_for_date_range, ) from app.dao.fact_processing_time_dao import ( get_processing_time_percentage_for_date_range, ) from app.dao.services_dao import get_live_services_with_organi...
app.errors import register_errors from app.performance_dashboard.performance_dashboard_schema import ( performance_dashboard_request, ) from app.schema_validation import validate performance_dashboard_blueprint = Blueprint('performance_dashboard', __name__, url_prefix='/performance-dashboard') register_errors(per...
# This file is part of Korman. # # Korman is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Korman is distributed i...
hat case. Multi modifiers should accept any SceneObject, however node.get_key(exporter, so) else: exporter.node_trees_exported.add(i.node_tree.name) i.node_tree.export(exporter, bo, so) def harvest_actors(self): actors = set() ...
st_actors()) return actors class PlasmaSpawnPoint(PlasmaModifierProperties): pl_id = "spawnpoint" bl_category = "Logic" bl_label = "Spawn Point" bl_description = "Point at which avatars link into the Age" def export(self, exporter, bo, so): # Not much to this modifier... It's bas...
__author__ = 'ganeshchand' import re def regex_search(pattern_string, string_source): if re.search(pattern_string,string_source): print("%s matched %s" % (pattern_string, string_source)) else: print("%s did n
ot match %s" % (pattern_string, string_source)) # matching a pattern in one string mystring_anchors = 'aaaaa!@#$!@#$aaaaaadefg' pattern_withoutanchors = r'@#\$!' # $ sign needs escaping if it doesn't represen
t need to represent its special meaning. # It is an anchor reserved character - it marks the end of the string # that means, if you say aab$ , you are looking for a string that that ends with pattern aab # there sh...
#!/usr/bin/env python # This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) 2012-2015, Michigan State University. # Copyright (C) 2015, The Regents of the University of California. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
efault is "infile".sweep2') parser.add_argument('-q', '--quiet') parser.add_argument('input_filename') parser.add_argument('read_filename') args = parser.parse_args() inp = args.input_filename readsfile = args.read_filename outfile = os.path.basename(readsfile) + '.sweep2' if args.out...
outfile, 'w') # create a nodegraph data structure ht = khmer_args.create_countgraph(args) # load contigs, connect into N partitions print('loading input reads from', inp) ht.consume_seqfile(inp) print('starting sweep.') m = 0 K = ht.ksize() instream = screed.open(readsfile) f...
#!/usr/bin/env python # encoding: utf-8 # ------------------------------------------------------------------------------- # version: ?? # author: fernando # license: MIT License # contact: iw518@163.com # purpose: views # date: 2016-12-14 # copyright: copyright 2016 Xu, Aiwu # ----...
------------------------------------------------- from flask import redirect, url_for, render_template from app.model.models import Team from . import hr from .forms import RegisterForm @h
r.route('/team_manage', methods=['POST', 'GET']) def team_manage(): form = RegisterForm() if form.validate_on_submit(): Team(job_id=form.job_selections.data, user_id=form.user_selections.data) return redirect(url_for('order.employee')) return render_template('hr/team_manage.html', form=form)...
#!/usr/bin/env python # encoding: utf-8 'A simple client for accessing api.ly.g0v.tw.' import json import unittest try: import urllib.request as request import urllib.parse as urlparse except: import urllib2 as request import urllib as urlparse def assert_args(func, *args): def inner(*args): required_arg = ar...
t_args def fetch_bill(self, bill_id): 'Fetch metadata of a specific bill.' return self._fetch_data('collections/bills/' + str(bill_id)) @assert_args def fetch_bill_data(self, bill
_id): 'Fetch data of a specific bill.' assert(len(bill_id) > 0) return self._fetch_data('collections/bills/' + str(bill_id) + '/data') @assert_args def fetch_motions_related_with_bill(self, bill_id): 'Fetch motions related with a specific bill.' query = json.dumps({'bill_ref': bill_id}) query = urlparse....
import redis class BetaRedis(redis.StrictRedis): def georadius(self, name, *values): return self.execute_command('GEORADIUS', name, *values) def geoadd(self, name, *values): return self.execute_command('GEOADD', name, *values) def geopos(self, name, *values): return self.execute_...
_init__(self, host='localhost', port=6379, db=0): self.r = BetaRedis(host=host, port=port, db=db) self.r.flushdb() def gen(self, data, distance=200000, min_sum=1): for point in data: try: res = self.r.georadius(self.REDIS_KEY_GEO, point['lng'], point['lat'], dist...
t['key'], 1) else: self.r.hincrby(self.REDIS_KEY_HASH, res[0]) except redis.exceptions.ResponseError as e: pass for key in self.r.hscan_iter(self.REDIS_KEY_HASH): lng, lat = map(lambda x: x.decode(), self.r.geopos(self.REDIS_KEY_GEO, k...
import copy from corehq.pillows.case import CasePillow from corehq.pillows.mappings.reportcase_mapping import REPORT_CASE_MAPPING, REPORT_CASE_INDEX from django.conf import settings from .base import convert_property_dict class ReportCasePillow(CasePillow): """ Simple/Common
Case properties Indexer an extension to CasePillow that provides for indexing of custom case properties """ es_alias = "report_cases" es_type = "report_case" es_index = REPORT_CASE_INDEX default_mapping = REPORT_CASE_MAPPING def get_unique_id(self): return self.calc_meta() def ...
_domain(doc_dict) not in getattr(settings, 'ES_CASE_FULL_INDEX_DOMAINS', []): #full indexing is only enabled for select domains on an opt-in basis return None doc_ret = copy.deepcopy(doc_dict) convert_property_dict(doc_ret, self.default_mapping, override_root_keys=['_id', 'doc_ty...
from django.urls import include, path from django.contrib import admin urlpatterns = [ path('', include('orcamentos
.core.urls', namespace='core')), path('crm/', include('orcamentos.crm.urls', namespace='crm')), path('proposal/', include('orcamentos.proposal.urls', names
pace='proposal')), path('admin/', admin.site.urls), ]
import imghdr from wsgiref.util import FileWrapper from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.http import ( HttpResponse, HttpResponsePermanentRedirect, StreamingHttpResponse, ) from django.shortcuts import get_object_or_404 from django.urls import reverse from dj...
(image.id, filter_spec, key) url = reverse(viewname, args=(signature, image.id, filter_spec)) url += image.file.name[len("original_images/") :] return url class ServeView(View): model = get_image_model() action = "serve" key = None @classonlymethod def as_view(cls, **initkwargs): ...
red( "ServeView action must be either 'serve' or 'redirect'" ) return super(ServeView, cls).as_view(**initkwargs) def get(self, request, signature, image_id, filter_spec, filename=None): if not verify_signature( signature.encode(), image_id, filter_s...
d/svgdatashapes # Copyright 2016-8 Stephen C. Grubb stevegrubb@gmail.com MIT License # # This module provides date / time support for svgdatashapes # import svgdatashapes from svgdatashapes import p_dtformat import collections import datetime as d import time import calendar class AppDt_Error(Exception)...
x = dtmax.replace( year=yr+1, month=1, day=1, hour=0 ) elif nearest == "3month": newmon = ((dtmin.month / 4) * 3) + 1 dtmin = dtmin.replace( month=newmon, day=1, hour=0 ) newmon = (((dtmax.month / 4)+1) * 3) + 1 yr = dtmax.year if newmon >= 12: newmon = 1; yr += 1; d...
if mon == 12: dtmax = dtmax.replace( year=yr+1, month=1, day=1, hour=0 ) else: dtmax = dtmax.replace( month=mon+1, day=1, hour=0 ) elif nearest == "week" or nearest[:8] == "week_day": # week = Monday-based week; or week_dayN where N=1 for Tues; N=6 for Sun, etc wday = time.gmtime( d...
"""tictactoe URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add a
n import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from d...
.contrib import admin from django.urls import path, include from django.conf.urls.static import static from tictactoe import settings urlpatterns = [ path('admin/', admin.site.urls), path('tictactoe/', include('tictactoe.game.urls'), name='game'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_...
# testing/schema.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import exclusions from .. import schema, event from . import config __all_...
ecific tweaks.""" te
st_opts = dict([(k, kw.pop(k)) for k in list(kw) if k.startswith('test_')]) if not config.requirements.foreign_key_ddl.enabled_for_config(config): args = [arg for arg in args if not isinstance(arg, schema.ForeignKey)] col = schema.Column(*args, **kw) if test_opts.get('test_ne...
# -*- encoding: utf-8 -*- import argparse import sys import traceback from hashlib import md5 import mailchimp_marketing as MailchimpMarketing import requests from consolemsg import step, error, success from erppeek import Client import time import configdb ERP_CLIENT = Client(**configdb.erppeek) MAILCHIMP_CLIENT =...
ubscriber_hash}".format( list_id=list_id, subscriber_hash=get_subscriber_hash(email) ), "operation_id": email, } operations.append(operation) payload = { "operations": operations } try: response = MAILCHIMP_CLIENT.batche...
d) except ApiClientError as error: msg = "An error occurred an archiving batch request, reason: {}" error(msg.format(error.text)) else: batch_id = response['id'] while response['status'] != 'finished': time.sleep(2) response = MAILCHIMP_CLIENT.batches.stat...
# -*- coding: utf-8 -*- """ *************************************************************************** EditScriptDialog.py --------------------- Date : December 2012 Copyright : (C) 2012 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******...
on 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** ""
" from processing.modeler.ModelerUtils import ModelerUtils __author__ = 'Alexander Bruy' __date__ = 'December 2012' __copyright__ = '(C) 2012, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import codecs import sys import json from PyQt4.QtCore impor...
return Choice(msg + ' (y/n)', 'ny') def SaveToFile(msg, scriptname, tmpname): if not YesNoQuestion('%s Save script to file?' % msg): return scriptname = os.path.join(os.getcwd(), scriptname) sys.stdout.write('Enter filename (default %s):' % scriptname) filename = sys....
filename = scriptname scriptdata = open(tmpname).read() open(filename, 'w').write(scriptdata) res, scripts = sieve.listscripts() if res != 'OK': return res for name, active in scripts: if name == scriptname: res, scriptdata = sieve.getscript(scriptname) ...
ript not on server. Create new?'): return 'OK' # else: script will be created when saving scriptdata = '' import tempfile filename = tempfile.mktemp('.siv') open(filename, 'w').write(scriptdata) editor = os.environ.get('EDITOR', 'vi') while 1: res = os.s...
er knots. def getinttex(self): """ Same as above, but we include the extremal points "once". """ return self.t[(self.k):-(self.k)].copy() def knotstats(self): """ Returns a string describing the knot spacing """ knots = self.getinttex() spacings = knots[1:] - knots[:-1] return " ".join(["%.1f"...
one, nostab = True): """ Evaluates the spline at jds, and returns the corresponding mags-like vector. By default,
we exclude the stabilization points ! If jds is not None, we use them instead of our own jds (in this case excludestab makes no sense) """ if jds is None: if nostab: jds = self.datapoints.jds[self.datapoints.mask] else: jds = self.datapoints.jds else: # A minimal check for non-extrapolation co...
# -*- coding: utf-8 -*- """ *************************************************************************** FixedDistanceBuffer.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *******************...
* ****************************
*********************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4.QtCore import * from qgis.core import * from processing.core.Ge...
yield self.get_teams_async() @ndb.toplevel def prepTeam
sMatches(self): yield self.get_matches_async(), self.get_teams_async() @property def matchstats(self): if self.details is None: return None else: return self.details
.matchstats @property def rankings(self): if self.details is None: return None else: return self.details.rankings @property def location(self): if self._location is None: split_location = [] if self.city: split_loc...
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.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/lice...
he 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 limi
tations # under the License. from oslo_utils import uuidutils from urllib.parse import parse_qs from urllib.parse import urlparse from designateclient import exceptions def resolve_by_name(func, name, *args): """ Helper to resolve a "name" a'la foo.com to it's ID by using REST api's query support and fi...
from .. import tool def test_keygen(): def get_keyring(): WheelKeys, keyring = tool.get_keyring() class WheelKeysTest(WheelKeys): def save(self): pass class keyringTest:
backend = keyring.backend @classmethod def get_keyring(cls): class keyringTest2: pw = None def set_password(self, a, b, c): self.pw = c def get_password(self, a, b): ...
return keyringTest2() return WheelKeysTest, keyringTest tool.keygen(get_keyring=get_keyring)
# -*- test-case-name: foolscap.test.test_crypto -*- available = False # hack to deal with half-broken imports in python <2.4 from OpenSSL import SSL # we try to use ssl support classes from Twisted, if it is new enough. If # not, we pull them from a local copy of sslverify. The funny '_ssl' import # stuff is used to...
ontain these names _ssl = ssl CertificateOptions = ssl.CertificateOptions else: # but it hasn't been released yet (as of 16-Sep-2006). Without them, we # cannot use any encrypted Tubs. We fall back to using a private copy of # sslverify
.py, copied from the Divmod tree. import sslverify _ssl = sslverify from sslverify import OpenSSLCertificateOptions as CertificateOptions DistinguishedName = _ssl.DistinguishedName KeyPair = _ssl.KeyPair Certificate = _ssl.Certificate PrivateCertificate = _ssl.PrivateCertificate from twisted.internet impor...
# 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 by...
OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # vim: tabstop=4 sh
iftwidth=4 softtabstop=4 import unittest from quantumclient.common import exceptions from quantumclient.quantum import v2_0 as quantumV20 class CLITestArgs(unittest.TestCase): def test_empty(self): _mydict = quantumV20.parse_args_to_dict([]) self.assertEqual({}, _mydict) def test_default_b...
from kvmagent import kvmagent from zstacklib.utils import jsonobject from zstacklib.utils import http from zstacklib.utils import log from zstacklib.utils.bash import * from zstacklib.utils import linux from zstacklib.utils import thread from jinja2 import Template import os.path import re import time import traceback ...
rue else: with open(conf_path, 'w') as fd: fd.write(conf) need_restart_collectd = True pid = linux.find_process_by_cmdline(['collectd', conf_path]) if not pid: bash_errorout('collectd -C %s' % conf_path) else: if need_resta...
_by_cmdline([cmd.binaryPath]) if not pid: EXPORTER_PATH = cmd.binaryPath LOG_FILE = os.path.join(os.path.dirname(EXPORTER_PATH), cmd.binaryPath + '.log') ARGUMENTS = cmd.startupArguments if not ARGUMENTS: ARGUMENTS = "" bash_errorout('...
import pytest from tests.support.asserts import assert_error, assert_success def perform_actions(session, actions): return session.transport.send( "POST", "/session/{session_id}/actions".format(session_id=session.session_id), {"actions": actions}) @pytest.mark.parametrize("action_type",...
"type": "pause", "duration": invalid_type }] }] response = perform_actions(session, actions) assert_error(response, "invalid argument") @pytest.mark.parametrize("action_type", ["none", "key", "pointer"]) def test_pause_without_duration(session, action_type)...
{ "type": "pause", }] }] response = perform_actions(session, actions) assert_success(response) @pytest.mark.parametrize("action_type", ["none", "key", "pointer"]) def test_action_without_id(session, action_type): actions = [{ "type": action_type, "actions": [{ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time from geopy.distance import great_circle from s2sphere import Cell, CellId, LatLng from pokemongo_bot import inventory from pokemongo_bot.base_task import BaseTask from pokemongo_bot.item_list import Item from pokemongo_bot.walkers.polyline_w...
ation)
self.no_log_until = now + 60 if self.destination["s2_cell_id"] != self.search_cell_id: self.search_points = self.get_search_points(self.destination["s2_cell_id"]) self.walker = PolylineWalker(self.bot, self.search_points[0][0], self.search_points[0][1]...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine
(xbmcmegapack@gmail.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 3 of the License, or (at your option) any later version. This program is distributed in th...
TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html """ class Languages_Persian(): '''Class that manages thi...
radius of the circular aperture in terms of the FWHM. cube_ref : array_like, 3d, optional Reference library cube. For Reference Star Differential Imaging. svd_mode : {'lapack', 'randsvd', 'eigen', 'arpack'}, str optional Switch for different ways of computing the SVD and selected PCs. scalin...
s of the circular aperture in terms of the FWHM. cube_ref : array_like, 3d, optional Reference library cube. For Reference Star Differential Imaging. svd_mode : {'lapack', 'randsvd', 'eigen', 'arpack'}, str optional Switch for different ways of computing the SVD and selected PCs. scaling : {...
n is done and with "temp-standard" temporal mean centering plus scaling to unit variance is done. fmerit : {'sum', 'stddev'}, string optional Chooses the figure of merit to be used. stddev works better for close in companions sitting on top of speckle noise. collapse : {'media...
import os.path import logging _logger = logging.getLogger(__name__) from operator import itemgetter from tornado.web import Application, RequestHandler, StaticFileHandler from tornado.ioloop import IOLoop config = { 'DEBUG': True, 'PORT' : 5000 } HANDLERS = [] ROOT_DIR = os.path.abspath(os.path.join(os.pa...
= os.path.join(ROOT_DIR, "node_modules", "gfxtablet") if os.path.exists(GFXTABLET_DIR): import sys sys.path.insert(0, GFXTABLET_DIR) from GfxTablet import GfxTabletHandler HANDLERS.append((r'/gfxtablet', GfxTabletHandler)) class MainHandler(RequestHandler): def get(self): self.render("in...
', StaticFileHandler, {'path': ROOT_DIR}), (r'/', MainHandler)] app = Application(HANDLERS, debug=config.get('DEBUG', False), static_path=ROOT_DIR) _logger.info("app.settings:\n%s" % '\n'.join(['%s: %s' % (k, str(v)) for k...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### # Author: Quincey Sun # Mail: zeroonegit@gmail.com # Created Time: 2016-06-21 23:14:26 ############################################################################### ## This programs asks a u...
mented this way. name = input("What is your name? ") password = input("What is the password? ") if name == "Josh" and password == "Friday": print ("Welcome Josh") elif name == "Fred" and passw
ord == "Rock": print ("Welcome Fred") else: print ("I don't know you.")
import os from unittest import TestCase import mock from marvel.iterables import BaseIterable class FooIterable(BaseIterable): def __init__(self): self.total_pages = 20 super(FooIterable, self).__init__() def get_items(self): if self.total_pages == 0: raise StopIteration...
self.total_pages - 1 return [self.total_pages] class TestBaseIterable(TestCase): def test_limit_pages_not_defined(self): count = 0 for _ in FooIterable(): count = count + 1 assert count == 20 @mock.patch.dict(os.environ, {'TC_LIMIT_PAGES': '3'}) def test_li...
= 0 for _ in FooIterable(): count = count + 1 assert count == 3
from mqttsqlite.orm.models import Topic import json from mqttsqlite.settings.private_settings import MANAGEMENT_PASSWORD, QUERY_PASSWORD from .utils import Payload, Utils class TopicsController (object): def add_topic(self, msg): received_data = json.loads(msg.payload) payload = Utils().validate_...
d.result = 'KO' payload.error = 'Topic not found'
saved_topics = [] for topic in Topic.select(): saved_topics.append(topic.name) payload.topics = saved_topics return payload.get_json() def list_topics(self, msg): received_data = json.loads(msg.payload) payload = Utils().validate_data(rec...
ist()) self.assertEqual([], index.get_shape())
p1 = array_ops.placeholder(dtypes.float32, shape=[None, None]) p2 = array_ops.placeholder(dtypes.float32, shape=[N
one, None]) m, index = control_flow_ops.merge([p1, p2]) self.assertEqual([None, None], m.get_shape().as_list()) self.assertEqual([], index.get_shape()) def testRefSelect(self): index = array_ops.placeholder(dtypes.int32) # All inputs unknown. p1 = array_ops.placeholder(dtypes.float32) p2...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ity, in the form of a GUID with no decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. :type client_request_id: str :param return_client_request_id: Whether the server should return the client-request-id in the response. Default value: False . :type return_client_reque...
you are calling the REST API directly. :type ocp_date: datetime :param if_match: An ETag value associated with the version of the resource known to the client. The operation will be performed only if the resource's current ETag on the service exactly matches the value specified by the client. ...
" been successfully aligned.", default=False) parser.add_option("--rootOutgroupDists", dest="rootOutgroupDists", help="root outgroup distance (--rootOutgroupPaths must " + "be given as well)", default=None) parser.add_option("...
ath(): path = os.path.dirname(sys.argv[0]) envFile = os.path.join(path, '..', 'environment') assert os.path.isfile(envFile) return envFile # If specified with the risky --autoAbortOnDeadlock option, we call this to # force an abort if
the jobStatusMonitor thinks it's hopeless. # We delete the jobTreePath to get rid of kyoto tycoons. def abortFunction(jtPath, options): def afClosure(): sys.stderr.write('\nAborting due to deadlock (prevent with' + '--noAutoAbort' + ' option), and running r...
# profiling_late.py # # Copyright (C) 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # # ''' Module to enable profiling timepoints. This module is loaded only if the configuration file exists, see profiling.py for more information ''' import os import sys imp...
logger.error('Path to "{}" probably does not exist
'.format(ct['python']['statfile'])) else: logger.error('dump_stats IOError: errno:{0}: {1} '.format(e.errno, e.strerror)) else: logger.error('No statfile entry in profiling conf file "{}"'.format(CONF...
#!/usr/bin/env python # encoding: utf-8 import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="cubehelix",
vers
ion="0.1.0", author="James Davenport", # author_email="", description="Cubehelix colormaps for matplotlib", long_description=read('README.md'), # license="BSD", py_modules=['cubehelix'], classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Scientific/Engineering :: Visu...
alizer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config @distribu...
dates a Sql pool data masking rule. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param sql_pool_name: SQL pool name. :...
he name of the data masking rule. :type data_masking_rule_name: str :param parameters: The required parameters for creating or updating a data masking rule. :type parameters: ~azure.mgmt.synapse.models.DataMaskingRule :keyword callable cls: A custom type or function that will be passed t...
import os import socket import sys input_host = '127.0.0.1' input_port = 65000 batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0')) if batch_enabled: # Since latest Python 2 has `builtins`and `input`, # we cannot detect Python 2 with the existence of them. if sys.version_info.major > 2: ...
) as sock: try: sock.connect((input_host, input_port)) userdata = sock.recv(1024) except ConnectionRefusedError: userdata = b'<user-input-unavailable>' return userdata.decode() builtins._input = input # type...
modules other than __main__. # Thus, we have to explicitly import __builtin__ module in Python 2. import __builtin__ builtins = __builtin__ def _raw_input(prompt=''): sys.stdout.write(prompt) sys.stdout.flush() try: sock = socket.socke...
from collections import OrderedDict from django.contrib import admin from edc_export.actions import export_as_csv_action from edc_base.modeladmin.admin import BaseTabularInline from ..forms import MaternalArvPostForm, MaternalArvPostMedForm, MaternalArvPostAdhForm from ..models import MaternalVisit, MaternalArvPost,...
of Maternal ARV Post with list", fields=[], delimiter=',', exclude=['created', 'modified', 'user_created', 'user_modified', 'revision', 'id', 'hostname_created', 'hostname_modified'], extra_fields=OrderedDict( {'subject_identifier': ...
aternal_arv_post__maternal_visit__appointment__registered_subject__subject_identifier', 'gender': 'maternal_arv_post__maternal_visit__appointment__registered_subject__gender', 'dob': 'maternal_arv_post__maternal_visit__appointment__registered_subject__dob', 'on_arv_sin...
#!/usr/bin/env python ######################
################################################## # File : dir
ac-admin-sync-users-from-file # Author : Adrian Casajus ######################################################################## """ Sync users in Configuration with the cfg contents. Usage: dirac-admin-sync-users-from-file [options] ... UserCfg Arguments: UserCfg: Cfg FileName with Users as sections containing...
# -*- coding: utf-8 -*- from hangulize import * class Finnish(Language): """For transcribing Finnish.""" __iso639__ = {1: 'fi', 2: 'fin', 3: 'fin'} __tmp__ = ',;%' vowels = 'aAeioOuy' ob = 'bdfgkpstT' notation = Notation([ # Convention: A = ä, O = ö ('å', 'o'), ('ä', ...
), ('n', 'n,'), ('N', 'N,'), (',,', ','), (',;', None), (',l,', 'l,'), (',m,', 'm,'), (',n,', 'n,'), (',N,', 'N,'), ('l{m;|n;}', 'l,'), (';', None), ('b', Choseong(B)), ('d', Choseong(D)), ('f', Choseong(P)), ...
('{,|-}l', Choseong(L)), ('-', None), ('l,', Jongseong(L)), ('l', Jongseong(L), Choseong(L)), ('m,', Jongseong(M)), ('m', Choseong(M)), ('n,', Jongseong(N)), ('n', Choseong(N)), ('N', Jongseong(NG)), ('p,', Jongseong(B)), ('p', Choseong(P...
#!/usr/bin/python import os.path import subprocess import sys import urllib KEY_FILE = "submit.token" def main(filename): # Prompt for key if missing if not os.path.exists(KEY_FILE): print "Please visit http://css.csail.mit.edu/6.858/2014/labs/handin.html" print "and enter your API key." ...
"Key: ").strip() wi
th open(KEY_FILE, "w") as f: f.write(key + "\n") print "API key written to %s" % KEY_FILE # Read the key. with open(KEY_FILE) as f: key = f.read().strip() # Shell out to curl. urllib2 doesn't deal with multipart attachments. Throw # away the output; you just get a random HT...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors # # This file is part of Alignak. # # Alignak 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 So...
l 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 Shinken. If not, see <http://www.gnu.org/licenses/>. # # This file is used to test reading and processing of ...
"""Misc helper
functions for extracting morphological info from CLTK data structures. """ from typing import List, Optional, Tuple, Union from cltk.core.data_types import Word from cltk.core.exceptions import CLTKException from cltk.morphology.universal_dependencies_features import ( NOMINAL_FEA
TURES, VERBAL_FEATURES, MorphosyntacticFeature, ) ALL_POSSIBLE_FEATURES = NOMINAL_FEATURES + VERBAL_FEATURES def get_pos(word: Optional[Word]) -> Union[str, None]: """Take word, return structured info.""" if not word: return None return word.pos.name def get_features( word: Optional...
"""A client for the REST API of imeji instances.""" import logging from collections import OrderedDict import requests from six import string_types from pyimeji import resource from pyimeji.config import Config log = logging.getLogger(__name__) class ImejiError(Exception): def __init__(self, message, error): ...
be treated as JSON. :param assert_status: Expected HTTP response status of a successful request. :param kw: Additional keyword parameters will be handed through to the \ appropriate function of the requests library. :return: The return value of the function of the requests library or a d...
lf.session, method.lower()) res = method(self.service_url + '/rest' + path, **kw) status_code = res.status_code if json: try: res = res.json() except ValueError: # pragma: no cover log.error(res.text[:1000]) raise i...
# -*- coding: utf-8 -*- import pytest f
rom flask import url_for def test_config(app): assert app.debug, 'App is in debug mode' assert not app.config.get('MINIFY_HTML'), 'App does minify html' assert app.config.get('ASSETS_DEBUG'), 'App does build assets' assert app.config.get('YARR_URL'), 'App doesn\'t have Yarr! URL specified' def t...
for('search')).status_code == 302, 'Empty query should throw redirect'
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import time mimetools = test_support.import_module("mimetools", deprecated=True) def _open_with_retry(func, host, *args, **kwargs): # Connecting to remote hosts is flaky. Make it...
# urllib.urlopen, "http://www.sadflkjsasadf.com/")
urllib.urlopen, "http://sadflkjsasf.i.nvali.d/") class urlretrieveNetworkTests(unittest.TestCase): """Tests urllib.urlretrieve using the network.""" def urlretrieve(self, *args): return _open_with_retry(urllib.urlretrieve, *args) def test_basic(self): # Test basic functi...
from setuptools import find_packages, setup from auspost_pac import __version__ as version setup( name='python-auspost-pac', version=version, license='BSD', author='Sam Kingston', author_email='sam@sjkwi.com.au', description='Python API for Australia Post\'s Postage Assessment Calculator (pac)...
install_requires=[ 'cached_property', 'frozendict', 'requests', ], packages=find_packag
es(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Programming Lan...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def dfs(root): if root is None: return N...
dfs(root.left) right, r
d = dfs(root.right) if ld < rd: return right, rd + 1 elif ld > rd: return left, ld + 1 else: return root, ld + 1 return dfs(root)[0]
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.utils import simplejson from django.core.serializers.json import DateTimeAwareJSONEncoder from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode EMITTERS = {} def g...
r(name=None, content_type='text/plain'): '''Decorator to register an emitter. Parameters:: - ``name``: name of emitter ('json', 'xml', ...) - ``content_type``: conte
nt type to serve response as ''' def inner(func): EMITTERS[name or func.__name__] = (func, content_type) return inner @register_emitter(content_type='application/json; charset=utf-8') def json(request, data): cb = request.GET.get('callback') data = simplejson.dumps(data, cls=DateTimeAwareJ...
"""Virtual environment relocatable mixin.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import shutil class RelocateMixin(object): """Mixin which adds the ability to relocate a virtual environmen...
ce.write(content) def move(self, destination): """Reconfigure and move the virtual environment to another path. Args: destination (str): The target path of the virtual environment. Note: Unlike `relocate`, this method *will* move the virtual to the give...
""" self.relocate(destination) shutil.move(self.path, destination) self._path = destination
from direct.distributed.ClockDelta import * from direct.interval.IntervalGlobal import * from pandac.PandaModules import * from DistributedNPCToonBase import * from toontown.chat.ChatGlobals import * from toontown.estate import BankGUI, BankGlobals from toontown.nametag.NametagGlobals import * from toontown.toonbase i...
ANK_MOVIE_DEPOSIT: if isLocalToon: self.cleanupBankingGUI() self.freeAvatar() self.setChatAbsolute(TTLocalizer.STOREOWNER_GOODBYE, CFSpeech | CFTimeout) elif mode == BankGlobals.BANK_MO
VIE_GUI: av = base.cr.doId2do.get(avId) if av: self.setupAvatars(av) if isLocalToon: self.hideNametag2d() base.camera.wrtReparentTo(render) seq = Sequence((base.camera.posQuatInterval(1, Vec3(-5, 9, self.getHeight() - 0....
from . import common import hglib class test_branches(common.basetest): def test_empty(self): self.assertEquals(self.client.branches(), []) def test_basic(self): self.append('a', 'a') rev0 = self.client.commit('first', addremove=True) self.client.branch('foo') self.appe...
r
= self.client.log(r)[0] expected.append((r.branch, int(r.rev), r.node[:12])) self.assertEquals(branches, expected) def test_active_closed(self): pass
from django.conf.urls import patterns, include, url urlpatterns = [ url(r'^$', 'clientes.views.cliente
s', name='clientes'), url(r'^edit/(\d+)$', 'clientes.views.clientes_edit', name='editCliente'), url(r'^delete/
(\d+)$', 'clientes.views.clientes_delete', name='deleteCliente'), ]
from miasm2.core.asmb
lock import disasmEngine from miasm2.arch.msp430.arch import mn_msp430 class dis_msp430(disasmEngine): def _
_init__(self, bs=None, **kwargs): super(dis_msp430, self).__init__(mn_msp430, None, bs, **kwargs)
# This file is part of Supysonic. # Supysonic is a Python implementation of the Subsonic server API. # # Copyright (C) 2020 Alban 'spl0k' Féron # # Distributed under terms of the GNU AGPLv3 license. from flask import request from ..db import RadioStation from . import get_entity, api_routing from .exceptions import ...
= get_entity(RadioStation) stream_url, name, homepage_url = map( request.values.get, ("streamUrl", "name", "homepageUrl") ) if stream_url and
name: res.stream_url = stream_url res.name = name if homepage_url: res.homepage_url = homepage_url else: raise MissingParameter("streamUrl or name") return request.formatter.empty @api_routing("/deleteInternetRadioStation") def delete_radio_station(): if not r...
# -*- coding: UTF-8 -*- # Syntax definition automatically generated by hljs2xt.py # source: sml.js name = 'SML' file_patterns = ['*.sml', '*.ml'] built_in = """ array bool char exn int list option order real ref string substring vector unit word """.split() keyword = """ abstype and andalso as case da...
of op open orelse raise rec sharing sig signature struct structure then type val with withtype where while """.split() literal = ['true', 'false', 'NONE', 'SOME', 'LESS', 'EQUAL', 'GREATER', 'nil'] class comment: default_text_color = DELIMITER rules = [ # ignore {'begin': {'pattern': "\\b(...
uch|will|you|your|like)\\b", 'type': 'RegExp'}}, ('doctag', [RE(r"(?:TODO|FIXME|NOTE|BUG|XXX):")]), ] operator_escape = ('operator.escape', [RE(r"\\[\s\S]")]) class string: default_text_color = DELIMITER rules = [operator_escape] number = [ RE(r"\b(?:0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]...
return '0.0.0.0' except IOError as e: print(nic_name + 'is unacceptable !') return '0.0.0.0' finally: return '0.0.0.0' if nic_name != '': bind_ip = bind_nic() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((bi...
00\x28\x00') or data.startswith('\x07' + chr(svr_num) + '\x28\x00'): break elif data[0] == '\x07' and data[2] == '\x10': log('[keep-alive2] recv file, resending..') svr_num = svr_num + 1 packet = keep_alive_package_builder(svr_num,dump(ran),'\x00'*4,1, False) ...
'[keep-alive2] recv1/unexpected',data.encode('hex')) #log('[keep-alive2] recv1',data.encode('hex')) ran += random.randint(1,10) packet = keep_alive_package_builder(svr_num, dump(ran),'\x00'*4,1,False) log('[keep-alive2] send2',packet.encode('hex')) s.sendto(packet, (svr, 61440)) while Tr...
# Copyright 2012 IBM 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 app...
services = [] for service in all_services: service = { 'id': service['id'],
'binary': service['binary'], 'host': service['host'], 'zone': service['availability_zone']['name'], 'status': 'disabled' if service['disabled'] else 'enabled', 'state': 'up' if utils.service_is_up(service) else 'down', 'updated_at': ser...
applescript="\'tell application \"Finder\" to quit\'" shellCmd = 'osascript -e '+applescript os.system(shellCmd) demo=False respDeadline = 100 if autopilot: respDeadline = 0.1 timeAndDateStr = time.strftime("%d%b%Y_%H-%M", time.localtime()) if os.path.isdir('.'+os.sep+'data'): dataDir='data' else: ...
ng data in present working directory') dataDir='.' fileName = os.path.join(dataDir, participant+'_spatiotopicMotion_
'+timeAndDateStr) dataFile = open(fileName+'.txt', 'w') # sys.stdout #StringIO.StringIO() saveCodeCmd = 'cp \'' + sys.argv[0] + '\' '+ fileName + '.py' os.system(saveCodeCmd) #save a copy of the code as it was when that subject was run logFname = fileName+'.log' ppLogF = logging.LogFile(logFname, filemode='w',...
""" Support for RFXtrx switches. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.rfxtrx/ """ import logging import homeassistant.components.rfxtrx as rfxtrx from homeassistant.components.rfxtrx import ( ATTR_FIREEVENT, ATTR_NAME, ATTR_PACKETID...
if rfxtrx.RFX_DEVICES[device_id].should_fire_event: rfxtrx.RFX_DEVICES[device_id].hass.bus.fire( EVENT_BUTTON_PRESSED, { ATTR_ENTITY_ID: rfxtrx.RFX_DEVICES[device_id].entity_id, ATTR_S
TATE: event.values['Command'].lower() } ) # Subscribe to main rfxtrx events if switch_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(switch_update) class RfxtrxSwitch(SwitchDevice): """Representation of a RFXtrx sw...
from __future__ import print_function from scipy.ndimage import gaussian_filter import numpy as np from PIL import Image img = np.asarray(Image.open('../Klimt/Klimt.ppm')) img_gray = np.asarray(Image.open('../Klimt/Klimt.pgm')) print('img:', img.shape) sigmas = [0.5, 2, 5, 7] for sigma in sigmas: print('sigma:', ...
n.py#L12-L126 img_blur = Image.fromarray(gaussian_filter(img, sigma=(sigma, sigma, 0), mode = 'nearest')) img_blur.save('Klimt_RGB_Gaussian_blur_sigma={:.1f}.png'.format(sigma)) img_blur = Imag
e.fromarray(gaussian_filter(img_gray, sigma=sigma, mode = 'nearest')) img_blur.save('Klimt_gray_Gaussian_blur_sigma={:.1f}.png'.format(sigma))
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # # 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, m...
ss Ctrl-C to quit.') while True: current_touched = cap.touched() print(current_touched) # # Check each pin's last and current state to see if it was pressed or released. # for i in range(12): # # Each pin is represented by a bit in the touched value. A value of 1 # # means the pin is be...
means it is not being touched. # pin_bit = 1 << i # # First check if transitioned from not touched to touched. # if current_touched & pin_bit and not last_touched & pin_bit: # print('{0} touched!'.format(i)) # # Next check if transitioned from touched to not touched. # if...
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # 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...
_1081' self.power[1] = databus.get_value(power_2_register) databus.set_value(pow
er_2_register, self._get_power_2) power_3_register = 'register_1082' self.power[2] = databus.get_value(power_3_register) databus.set_value(power_3_register, self._get_power_3) gevent.spawn(self.usage_counter) def _get_energy_in(self): return self.energy_in def _get_en...
#!/usr/bin/python # -*- codi
ng: utf-8 -*- """ In this example, we connect a signal of a QSlider to a slot
of a QLCDNumber. """ import sys from PySide.QtGui import * from PySide.QtCore import * class Example(QWidget): def __init__(self): super(Example, self).__init__() lcd = QLCDNumber() sld = QSlider(Qt.Horizontal) vbox = QVBoxLayout() vbox.addWidget(lcd) vbox.addWi...
""" Package for managing a ranked ladder, which is a special kind of ongoing League. Package Requirements -------------
------- botbase match user Dependencies ------------ cmd_ladder botbase/ commandtype ladder/ ratingsdb match/ cmd_match matchinfo user/ userlib ladder util/ server ladderadminchannel botbase/ botchannel cmd_seedgen ladder/ ...
t ladder/ rating ratingutil ratingutil ladder/ rating util/ console """
from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import testing from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.testing.schema import Column from sqlalchemy.te...
Column("type", String(30)), ) b = Table( "b", metadata, Column("id", Integer, ForeignKey("a.id"), primary_key=True), Column("bdata", String(30)), ) c = Table( "c", metadata, Column("id", Integer,...
Column("cdata", String(30)), ) @testing.combinations(("union",), ("none",)) def test_abc_poly_roundtrip(self, fetchtype): class A(fixtures.ComparableEntity): pass class B(A): pass class C(B): pass if fetchtype == "union": ...
:ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`IntegrationAccountSchemaPaged <azure.mgmt.logic.models.IntegrationAccountSchemaPaged>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Con...
**operation_config): """Gets an integration account schema. :param resource_group_name: The resource group name. :type resource_group_name: str :param integration_account_name: The integration account name. :type integration_account_name: str :param schema_name: The int...
name. :type schema_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperati...
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest2 METRIC_TYPE =
'compute.googleapis.com/instance/uptime' METRIC_LABELS = {'instance_name': 'instance-1'} RESOURCE_TYPE = 'gce_instance' RESOURCE_LABELS = { 'project_id': 'my-project', 'zone': 'us-east1-a', 'instance_id': '1234567890123456789', } METRIC_KIND = 'DELTA' VALUE_TYPE = 'DOUBLE' TS0 = '2016-04-06T22:05:00.042Z...
TF_8 = str('iso-8859-1'), str('utf-8') class LimitedStream(object): ''' LimitedStream wraps another stream in order to not allow reading from it past specified amount of bytes. ''' def __init__(self, stream, limit, buf_size=64 * 1024 * 1024): self.stream = stream self.remaining = l...
e HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ if settings....
EDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') if not script_url: s...
import mysql.connector from model.group import Group from model.contact import Contact class DbFixture: def __init__(self, host, dbname, username, password): self.host = host self.dbname = dbname self.username = username self.password = password self.connection = mysql.conn...
0-00 00:00:00'") for row in cursor: (id, firstname, lastname) = row list.append(Contact(id=str(id), firstname=firstname, lastname=lastname)) finally:
cursor.close() return list def destroy(self): self.connection.close()