prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import logging
class MockManager(object):
""" Mock manager for filter unit testing. """
def get_child_logger(self, name):
return logging.getLogger('test').getChild(name)
def generic_filter_test(test):
"""Decorator used for creating a generic filter test.
Requires the argument to be a functi... | s,
pass_vals = values that create passing events,
fail_vals = values that create failing events
"""
test(test)
def generic_test(self):
# Create the filter
filt = self.gen_filter(test.filt)
# Test passing
for val in test.pass_vals:
event = self.gen_event({... | "pass_val failed check in {}: \n{} passed {}"
"".format(test.__name__, event, filt))
# Test failing
for val in test.fail_vals:
event = self.gen_event({test.event_key: val})
self.assertFalse(
filt.check_event(event),
... |
from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rariti... | ags and tag > 0:
unknown_tags.add(tag)
# Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...)
assert card.rarity in known_rarities
assert not unknown_tags
def test_play_scripts():
for card in CARDS.values():
if card.scripts.activate:
assert card.type == CardType.HERO_POWER
elif card.script... | ype.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
def test_card_docstrings():
for card in CARDS.values():
c = utils.fireplace.utils.get_script_definition(card.id)
name = c.__doc__
if name is not None:
if name.endswith(")"):
continue
assert name == card.name
|
from SloppyCell.ReactionNetworks import *
import Nets
traj2a = Dynamics.integrate(Nets.fig2a, [0, 3*60])
traj2b = Dynamics.integrate(Nets.fig2b, [0, 3*60])
traj2c = Dynamics.integrate(Nets.fig2c, [0, 3*60])
traj2d = Dynamics.integrate(Nets.fig2d, [0, 3*60])
traj2e = Dynamics.integrate(Nets.fig2e, [0, 3*60])
Plotting... | 60., percent, '-k')
Plotting.axis([0, 3, 0, 105])
traj6a = Dynamics.integrate(Nets.fig6a, [0, 16*60])
traj6b = Dynamics.integrate(Nets.fig6b, [0, 16*60])
traj6c = Dynamics.integrate(Nets.fig6c, [0, 16*60])
Plot | ting.figure(6, (5, 10))
Plotting.subplot(2,1,1)
Plotting.plot(traj6a.get_times()/60., traj6a.get_var_traj('BCatenin'), '-k')
Plotting.plot(traj6b.get_times()/60., traj6b.get_var_traj('BCatenin'), '-r')
Plotting.plot(traj6c.get_times()/60., traj6c.get_var_traj('BCatenin'), '-g')
Plotting.axis([-1, 16, 34, 72])
Plotting.... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para Google Video basado en flashvideodownloader.org
# http://blog.tvalacarta.info/plugin-xb | mc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import scrapertools
# Re | turns an array of possible video url's from the page_url
def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("(page_url='%s')" % page_url)
video_urls = []
# Lo extrae a partir de flashvideodownloader.org
if page_url.startswith("http://"):
url = 'htt... |
# -*- coding: utf-8 -*-
############################################## | ################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
###### | ######################################################################## |
if response.status_code in [200,201,202]:
responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type'])
return responseObject
else:
raise ApiException(response.status_code,response.content)
ex... |
if 'assignmentUid' in allParams and allParams['assignmentUid'] is not None:
resourcePath = resourcePath.replace("{" + "assignmentUid" + "}" , str(allParams['assignmentUid']))
else:
resourcePath = re.sub("[&?]assignmentUid.*?(?=&|\\?|$)", "", resourceP | ath)
if 'storage' in allParams and allParams['storage'] is not None:
resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage']))
else:
resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath)
if 'folder' in allPar... |
__author__ = 'Administrator'
from django.conf.urls import patterns
from django.contrib.auth.views impor | t login, logout_then_login
urlpatterns = patterns('',
(r'^$', 'apps.sims.views.ind | ex_view'),
(r'index/$', 'apps.sims.views.index_view'),
(r'login/$', login, {'template_name': 'sims/login.html'}),
(r'logout/$', logout_then_login),
(r'stuinfo/$', 'apps.sims.views.student_info_list'),
(r'save/$', 'apps.sims.views.save_student'),
(r'delete/$', 'apps.sims.views.delete_studen... |
#!/usr/bin/env python
"""Simulation bootstrapper"""
from formation_flight.formation import handlers as formation_handlers
from formation_fli | ght.aircraft import handlers as aircraft_handlers
from formation_flight.aircraft import generators
from formation_flight.hub import builders
from formation_flight.hub import allocators
from lib import sim, debug, sink
from lib.debug import print_line as p
from formation_flight import | statistics
import config
import os
import numpy as np
config.sink_dir = '%s/sink' % os.path.dirname(__file__)
def init():
sink.init(config.sink_dir)
def execute():
init()
for z in np.linspace(0, 1, 250):
config.Z = z
single_run()
def single_run():
sim.init()
ai... |
# Copyright 2018 New Vector Ltd
#
# 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 writin... | ertEqual(string_file.getvalue(), "Foo")
yield producer.write_and_wait("Bar")
self.assertEqual(string_file.getvalue(), "FooBar")
finally:
consumer.unregisterProducer()
yield consumer.wait()
| self.assertTrue(string_file.closed)
@defer.inlineCallbacks
def test_push_consumer(self):
string_file = BlockingStringWrite()
consumer = BackgroundFileConsumer(string_file, reactor=reactor)
try:
producer = NonCallableMock(spec_set=[])
consumer.registerProducer(p... |
__author__ = 'Ting'
from Craw | lWorker.spiders.stackoverflow import StackOverflowSpider
class ServerFaultSpider(StackOverflowSpider):
name = 'ServerFaultSpider'
allowed_domains = ['serverfault.com']
def __init__(self, op=None, **kwargs):
StackOverflowSpider.__init__(self, op, **kwargs)
def get_feed_start_urls(self):
... | om/questions'] |
import sys
import os
from com.googlecode.fascinator.common import FascinatorHome
sys.path.append(os | .path.join(FascinatorHome.getPath(),"harvest", "workflows"))
from baserules import BaseIndexData
class IndexData(BaseIndexData):
def __activate__(self, context):
BaseIndexData.__activate | __(self,context)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: test_maximal_independent_set.py 577 2011-03-01 06:07:53Z lleeoo $
"""
Tests for maximal (not maximum) independent sets.
"""
# Copyright (C) 2004-2016 by
# Leo Lopes <leo.lopes@monash.edu>
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.ed... | lf.florentine | = nx.Graph()
self.florentine.add_edge('Acciaiuoli','Medici')
self.florentine.add_edge('Castellani','Peruzzi')
self.florentine.add_edge('Castellani','Strozzi')
self.florentine.add_edge('Castellani','Barbadori')
self.florentine.add_edge('Medici','Barbadori')
self.florentin... |
"""
Add an excerpt field to the page.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(extensions.Extension):
def handle_model(self):
self.model.add_to_class(
... | ,
blank=True,
help_text=_(
'Add a brief excerpt summarizing the content'
' of this page.')))
def handle_modeladmin(self, modeladmin):
modeladmin.add_extension_options(_('Excerpt'), {
'fields': ('excerpt',),
'cla... |
})
|
# -*- coding: utf-8 -*-
# © <YEAR(S)> <A | UTHOR(S)>
# License AGPL-3.0 or later (http://www.gn | u.org/licenses/agpl.html).
from . import account_payment
|
from RMPY.representations import curve
from RMPY.creators import skinCluster
import pymel.core as pm
from RMPY.core import config
import os
def save_curve(*args):
"""
:param args: the scene objects that will be saved if nothing is provide it it will try to save the selection.
:return:
"""
if args:... | :param args: the scene objects that will be loaded if nothing is provide it it will try to load the selection.
:return:
"""
if args:
scene_curves = args
e | lse:
scene_curves = pm.ls(selection=True)
for each in scene_curves:
try:
if pm.objExists(each):
curve_node = curve.Curve.by_name(each)
curve_node.load()
curve_node.set_repr_dict()
else:
print "the curve {} doesn... |
newline character is found
:param str file: the file name (path)
:param FileSize length: the expected length of the file
:return tuple: (line number, line content)
note: the line number is not available for long files
"""
# In order to use the optimized version for long files, t... | return 0, file_handle.readline().decode()
except OSError:
# The file | might be empty or somehow broken
return 0, ''
# Otherwise use simple line enumeration until we hit the last one
else:
with open(file, 'r') as file_handle:
last = (0, '')
for line_num, line in enumerate(file_handle):
last = (line_num + 1, line)
... |
# -*- coding: utf-8 -*-
from __future__ import unicod | e_literals
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
| |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('monitoring', '0002_monitoring_updat | e'),
]
operations = [
migrations.RemoveField(
model_name='requestevent',
name='resources',
),
migrations.AddField(
model_name='requestevent',
name='resources',
field=models.Man | yToManyField(help_text='List of resources affected', to='monitoring.MonitoredResource', null=True, blank=True),
),
]
|
"""
Code for MT1 review worksheet.
Direct all complaints to Owen Jow (owenjow@berkeley).
"""
# Part 1: Contr | ol
x = (0 and 1 and 2) + (0 or 1 or 2)
((-4 or 0) and 4) / (-2 or (0 and 2))
if x <= 1:
print('hello')
elif x <= 2:
print(' world')
if x <= 3:
print(' my name is inigo montoya')
else:
print(' from the other side')
# Part 2: HOF / Lambdas
def f(v, x):
def g(y, z):
return y(x, z)(z, x)
... | lambda y, x: y * 4
v = lambda x, y: x * 3 + y
f(u, 1)(lambda x, y: lambda y, x: y * 3 + v(x, y), 2)
# Part 4: Environment Diagrams
def f(x, h):
def g(y, i):
f = i[:]
h = [f, lambda: g(5, h)]
return h
return g(4, h)
x, y = 6, 7
f = f(3, [lambda: x * y])
g = f[-1]()[0][0][0]()
|
import numpy as np
import unittest
import pycuda.driver a | s drv
import pycuda.compiler
import pycuda.autoinit
import pycuda.gp | uarray as gpuarray
import pycuda.cumath as cumath
from pycuda.compiler import SourceModule
__author__ = 'AlistairMcDougall' |
################################################################################
# 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... | "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WI... | ##################################################################
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import unittest
import grpc
from apache_beam.portability.api.beam_provision_api_pb2 import (ProvisionInfo,
... |
"""
Gigablast (Web)
@website https://gigablast.com
@provide-api yes (https://gigablast.com/api.html)
@using-api yes
@results XML
@stable yes
@parse url, title, content
"""
import random
from json import loads
from time import time
from lxml.html import fromstring
from searx.url_utils impo... | '\
'&rxiec={rxieu}'\
'& | ulse={ulse}'\
'&rand={rxikd}'\
'&dbez={dbez}'
# specific xpath variables
results_xpath = '//response//result'
url_xpath = './/url'
title_xpath = './/title'
content_xpath = './/sum'
supported_languages_url = 'https://gigablast.com/search?&rxikd=1'
# do search-request
def request(query, params):
offset = (... |
"""
def __init__(self, inbound_nodes=[]):
"""
Node's constructor (runs when the object is instantiated). Sets
properties that all nodes need.
"""
# A list of nodes with edges into this node.
self.inbound_nodes = inbound_nodes
# The eventual value of this nod... | self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
# Cycle through the outputs. The gradient will change depending
# on each output, so the gradients are summed over all outputs.
for n in self.outbound_nodes:
# Get the partial of the cost with respect to this... | # Set the partial of the loss with respect to this node's inputs.
self.gradients[self.inbound_nodes[0]] += np.dot(grad_cost, self.inbound_nodes[1].value.T)
# Set the partial of the loss with respect to this node's weights.
self.gradients[self.inbound_nodes[1]] += np.dot(se... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django | .db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('managers', '0011_auto_20150422_2018'),
]
operations = [
migratio | ns.AlterField(
model_name='managerprofile',
name='picture',
field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg', upload_to=b'profiles'),
preserve_default=True,
),
]
|
LookingGlassLogHandler
from bagpipe.bgp.engine.bgp_manager import Manager
from bagpipe.bgp.rest_api import RESTAPI
from bagpipe.bgp.vpn import VPNManager
def findDataplaneDrivers(dpConfigs, bgpConfig, isCleaningUp=False):
drivers = dict()
for vpnType in dpConfigs.iterkeys():
dpConfig = dpConfigs... | ataplane": self.dataplaneConfig,
"bgp": self.bgpConfig
}
def _loadConfig(configFile):
parser = SafeConfigParser()
if (len(parser.read(configFile)) == 0):
logging.error("Configuration file not found (%s)", conf | igFile)
exit()
bgpConfig = parser.items("BGP")
dataplaneConfig = dict()
for vpnType in ['ipvpn', 'evpn']:
try:
dataplaneConfig[vpnType] = dict(
parser.items("DATAPLANE_DRIVER_%s" % vpnType.upper()))
except NoSectionError:
if vpnType == "ipvpn... |
import os
import logging
import numpy as np
from torch.utils.data import Dataset
import cv2
from PIL import Image
import subprocess
import torchvision.transforms as tfs
np.random.seed(0)
def TransCommon(image):
image = cv2.equalizeHist(image)
image = cv2.GaussianBlur(image, (3, 3), 0)
return image
de... | n(self.data_path, os.path.expanduser(fields[0]))
flg_enhance = False
for index, value in enumerate(fields[5:]):
if index == 5 or index == 8:
labels.append(self.dict[1].get(value))
if self.dict[1].get(
... | e = True
elif index == 2 or index == 6 or index == 10:
labels.append(self.dict[0].get(value))
if self.dict[0].get(
value) == '1' and \
self.cfg.enhance_index.count(index) > 0:
... |
from __future__ import unicode_li | terals |
from django.apps import AppConfig
class PermsConfig(AppConfig):
name = 'perms'
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from routes.campapel.home import returnIndex
from tekton import router
from tekton.gae.m... | t_by_id(camPapel_id)
contexto={'salvar_path':router.to_path(editar,camPapel_id),'camPapel':camPapel}
return TemplateResponse(contexto,template_path='campapel/form.html')
@login_not_required
def editar(camPapel_id,**prop):
camPapel_id=int(camPapel_id)
camPapel=CamPapel.get_by_id(camPapel_id)
camP... | elF.validate()
if erros:
contexto={'salvar_path':router.to_path(editar),
'erros':erros,
'camPapel':camPapelF}
return TemplateResponse(contexto,'campapel/form.html')
else:
camPapelF.fill_model(camPapel)
camPapel.put()
return RedirectRes... |
#!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import argparse
import logging
import sys
import gold_inexact_matching.base_parameter_optimiz... | parser
def SetLoggingVerbosity(args):
logger = logging.getLogger()
if args.verbose_count == 0:
logger.setLevel(logging.WARNING)
elif args.verbose_count == 1:
logger.setLevel(logging.INFO)
else:
logger.setLevel(loggin | g.DEBUG)
def main():
parser = CreateArgumentParser()
args = parser.parse_args()
SetLoggingVerbosity(args)
optimizer = optimizer_set.OptimizerSet(args, args.clazz)
optimizer.RunOptimization()
return 0
if __name__ == '__main__':
sys.exit(main())
|
# pylint: disable=too-many-lines
"""
Component to interface with cameras.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import asyncio
import logging
from aiohttp import web
from homeassistant.helpers.entity import Entity
from homeassista... | status=401)
response = yield from self.handle(request, camera)
return response
@asyncio.coroutine
def handle(self, request, camera):
"""Hanlde the camera request."""
raise NotImplementedError()
class CameraImageView(CameraView):
"""Camera view to serve an image."""
u... | image = yield from camera.async_camera_image()
if image is None:
return web.Response(status=500)
return web.Response(body=image)
class CameraMjpegStream(CameraView):
"""Camera View to serve an MJPEG stream."""
url = "/api/camera_proxy_stream/{entity_id}"
name = "api:... |
import pytest
from testutils import get_co, get_bytecode
from equip import BytecodeObject, BlockVisitor
from equip.bytecode import MethodDeclaration, TypeDeclaration, ModuleDeclaration
from equip.bytecode.utils import show_bytecode
import equip.utils.log as logutils
from equip.utils.log import logger
logutils.enableL... | lue,key in items:
print "%30s: %30s"%(key, value)
def return_Stmts(i):
if i == 1:
return 1
elif i == 2:
return 2
print "This is | something else"
if __name__ == '__main__':
main()
"""
def test_block_visitor():
co_simple = get_co(SIMPLE_PROGRAM)
assert co_simple is not None
bytecode_object = BytecodeObject('<string>')
bytecode_object.parse_code(co_simple)
class BlockPrinterVisitor(BlockVisitor):
def __init__(self):
Bloc... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Wil Mahan <wmahan+fatics@gmail.com>
#
# This file is part of FatICS.
#
# FatICS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... | if param is not None:
g = game.from_name_or_number(param, conn)
else:
if conn.user.session.game:
g = conn.user.session.game
elif conn.user.session.observed:
g = conn.user.session.observed.primary()
else:
| conn.write(_("You are not playing, examining, or observing a game.\n"))
g = None
return g
@ics_command('abort', 'n')
class Abort(Command, GameMixin):
def run(self, args, conn):
g = self._get_played_game(conn)
if not g:
return
'''if len(conn.user.se... |
import glob, os, sys
def get_build_info(ipp_static=True, # static build requires static IPP libs
ipp_arch=None,
ipp_root=None,
):
"""get options to build Python extensions built with Intel IPP
ipp_static - True to build using static IPP library (requires I... | vals = {}
if sys.platform.startswith('linux'):
libdirname = 'lib/%s_lin' % ipp_arch
else:
libdirname = 'lib'
incdirname = 'include' |
ipp_define_macros = []
ipp_extra_link_args = []
ipp_extra_objects = []
if sys.platform.startswith('win'):
ipp_define_macros = [('FASTIMAGE_IPP_ARCH','\\"%s\\"'%ipp_arch)]
else:
ipp_define_macros = [('FASTIMAGE_IPP_ARCH','"%s"'%ipp_arch)]
if ipp_static:
ipp_define_macros... |
""" unit test for Watchdo | g.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# imports
import os
from mock import MagicMock
# sut
from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog
mock_exeThread = MagicMock()
mock_spObject = MagicMock()
def test_calib... | e()
assert res['OK'] is True
def test__performChecks():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000)
res = wd.calibrate()
assert res['OK'] is True
res = wd._performChecks()
assert res['OK'] is True
def test__performChecksFull():
pid = os.getpid()
wd = Watchdog(pid, mo... |
7 2005/04/30 07:20:27 snakeru Exp $
"""Simplexml module provides xmpppy library with all needed tools to handle XML nodes and XML streams.
I'm personally using it in many other separate projects. It is designed to be as standalone as possible."""
import xml.parsers.expat
def XMLescape(txt):
"""Returns provided stri... | ore readable by human.
Node class have attribute FORCE_NODE_RECREATION that is defaults to False thus enabling fast node
replication from the some other node. The drawback of the fast way is that new node shares some
info with the "original" node that is changing the one node may influence the | other. Though it is
rarely needed (in xmpppy it is never needed at all since I'm usually never using original node after
replication (and using replication only to move upwards on the classes tree).
"""
FORCE_NODE_RECREATION=0
def __init__(self, tag=None, attrs={}, payload=[], parent=None, nsp=None, node_built=... |
from django.urls import path
from tickets import views
urlpatterns = [
path('', views.last_event, name='last_event'),
path('event/<str:ev>/', views.event, name='event'),
path('event/<str:ev>/<str:space>/<str:session>/register/', views.register, name='register'),
pa | th('ticket/<str:order>/payment/', views.payment, name='payment'),
path('ticket/<str:order>/thanks/', views.thanks, name='thanks'),
path('ticket/confirm/', views.confirm, name='confirm'),
path('ticket/confirm/paypal/', views.confirm_paypal, name='confirm_paypal'),
path('ticket/<str:order>/confirm/stripe/... | w'),
path('ticket/email-confirm/<int:id>/preview/', views.email_confirm_preview, name='email_confirm_preview'),
path('<str:ev>/', views.multipurchase, name='multipurchase'),
path('seats/<int:session>/<int:layout>/', views.ajax_layout, name='ajax_layout'),
path('seats/view/<int:map>/', views.seats, nam... |
)),
pnet.PoolingLayer(shape=(4, 4), strides=(4, 4)),
]
elif 0:
layers += [
pnet.PartsLayer(1000, (5, 5), settings=dict(outer_frame=1,
em_seed=training_seed,
... | es = np.array_split(test_labels, 200)
def format_error_rate(pr):
return "{:.2f}%".format(100*(1-pr))
#import gv
#with g | v.Timer('Testing'):
start2 = time.time()
args = (tup+(net,) for tup in itr.izip(ims_batches, labels_batches))
for i, res in enumerate(pnet.parallel.starmap(test, args)):
corrects += res.sum()
total += res.size
pr = corrects / total
end2 = time.time()
... |
# Copyright 2015 Cloudbase Solutions Srl
# 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 r... | _VM_STATE_DISABLED)
serialops = self._event_handler._serial_console_ops
serialops.stop_console_handler.assert_called_once_with(
mock.sentinel.insta | nce_name)
def _test_get_instance_uuid(self, instance_found=True,
missing_uuid=False):
if instance_found:
side_effect = (mock.sentinel.instance_uuid
if not missing_uuid else None, )
else:
side_effect = exception.NotFo... |
#!/usr/bin/python
"""
Copyright 2010 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of th... | 'gh_sid'].value
except KeyError:
sid = form.getfirst('gh_sid', '')
else:
currentUser = ''
loginResult = 'success'
sid = form.getfirst('gh_sid', | '')
userpass = form.getfirst("userpass")
# escape input to prevent sql injection
sid = dbShared.dbInsertSafe(sid)
userpass = dbShared.dbInsertSafe(userpass)
# Get a session
logged_state = 0
linkappend = ''
sess = dbSession.getSession(sid, 2592000)
if (sess != ''):
logged_state = 1
currentUser = sess
linka... |
import numpy as np
import scipy.io as sio
import pylab as pl
import itertools as it
import io
def ret_tru(inval):
return true
def get_next_ind(in_file, sep_ln="&", predicate = ret_tru):
lvals = []
for line in in_file:
line = line.strip()
if line == sep_ln:
break
if predic... | nt len(fncstack)
neur_mat = np.vstack(fncstack).transpose();
time_vec = np.fromstring(timelist, sep=' ')
#write to .mat file
#create file name
fbase = "abl_study_"
for abl in abl_val:
fbase = fbase + str(int(abl)) + "_"
fbase = fbase[:-1]
prin | t fbase
sio.savemat(fbase, {'abl_vals':np.array(abl_val), 'neur_series':neur_mat, 'time_vec':time_vec})
ltest = get_next_ind(dat_file, "&", lambda x:(x.startswith("Ablation") or x.startswith("Func") or x.startswith("Time") or x.startswith("&&")))
|
# This Source Code Form is subject to the terms of the Mozilla Public
# | License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Etherios, Inc. All rights reserved.
# Etherio | s, Inc. is a Division of Digi International.
|
from bears.c_languages.CPPLintBear import CPPLintBear
from tests.LocalBearTestHelper impo | rt verify_local_bear
test_file = """
int main() {
return 0;
}
"""
CPPLintBearTest = verify_local_bear(CPPLintBear,
valid_files=(),
invalid_files=(test_file,),
tempfile_kwargs={'suffix': '.cpp'})
CPPLintBea... | file_kwargs={'suffix': '.cpp'})
CPPLintBearLineLengthConfigTest = verify_local_bear(
CPPLintBear,
valid_files=(),
invalid_files=(test_file,),
settings={'cpplint_ignore': 'legal',
'max_line_length': '13'},
tempfile_kwargs={'suffix': '.cpp'})
|
onError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': ... | ize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
... | rl, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_paramet... |
# -*- coding: utf-8 -*-
#
# ELLIPTIc documentation build configuration file, created by
# sphinx-quickstart on Sat Mar 25 15:56:12 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | asename = 'ellipticdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff f... | # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'elliptic.tex', u'ELLIPTIc Documentation',
u'Guilherme Caminha', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSx... | render_template | ('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "!!! Email address already exists !!!"
newuser = User(form.email.data, form.password.data)
db.session.add... |
#!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... | ls(event=event, description=description, checksum=checksum, timestamp=datetime.now())
session.add(record)
return record
def create_database():
""""
Create a new database or overwrit | e the existing one
:return: None
"""
Base.metadata.create_all(engine)
def database_exists():
"""
Check if the database exists
:return: True if the database exists
:rtype: bool
"""
return os.path.exists(DATABASE_PATH)
|
= 'cloudwatch_' + region
default_section_name = 'cloudwatch'
self.enabled = self.config.getboolean(
self.section_name, 'enabled', False, default_section_name)
self.workers = int(self.config.get(
self.section_name, 'workers', 1, default_section_name))
self.has_su... | self.metrics_config = None
def update_start_end_times(self):
"""
Updates sta | rt/end times after last_run_time set
"""
utcnow = (datetime.datetime.utcnow()
.replace(microsecond=0, tzinfo=dateutil.tz.tzutc()))
delta = datetime.timedelta(minutes=self.default_delay_minutes)
if self.last_run_time:
if not self.start_time or self.last_run_... |
"""SCons.Tool.SCCS.py
Tool-specific initialization for SCCS.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Fou... | and construction variables for
SCCS to an Environment."""
def SCCSFactory(env=env):
""" """
import SCons.Warnings as W
W.warn(W.DeprecatedSourceCodeWarning, """The SCCS() factory is deprecated and there is no replacement.""")
act = SCons.Action.Acti | on('$SCCSCOM', '$SCCSCOMSTR')
return SCons.Builder.Builder(action = act, env = env)
#setattr(env, 'SCCS', SCCSFactory)
env.SCCS = SCCSFactory
env['SCCS'] = 'sccs'
env['SCCSFLAGS'] = SCons.Util.CLVar('')
env['SCCSGETFLAGS'] = SCons.Util.CLVar('')
env['SCCSCOM'] ... |
coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']... | s equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# | Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generat... |
__author__ = "Laura Martinez Sanchez"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "lmartisa@gmail.com"
from osgeo import gdal, gdalnumeric, ogr, osr
import numpy as np
from PIL import Image, ImageDraw
from collections import defaultdict
import pickle
import time
from texture_common import *
#Uses a gdal ge... | rray(ulX, ulY, lrX - ulX, lrY - ulY)
clip[band - 1] = imgaux
return clip
#Does the clip of the shape
def ObtainPixelsfromShape(field, rasterPath, shapePath, INX, *args):
# field='zona'
# open dataset, also load as a gdal image to get | geotransform
# INX can be false. If True, uses additional layers.
print "Starting clip...."
start = time.time()
if args:
texture_train_Path = args[0]
print texture_train_Path
img, textArrayShp = createTextureArray(texture_train_Path, rasterPath)
else:
#print"Indexes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007, 2010 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 ... | or now:
#u"%": u"٪",
}
ignoretests = ["startcaps", "simplecaps"]
#TODO: check per | sian numerics
#TODO: zwj and zwnj?
def punctranslate(cls, text):
"""Implement "French" quotation marks."""
text = super(cls, cls).punctranslate(text)
return guillemets(text)
punctranslate = classmethod(punctranslate)
|
'
"defaults to 'trybot' directory at top level of your "
'repo-managed checkout.'))
parser.add_remote_option('--chrome_rev', default=None, type='string',
action='callback', dest='chrome_rev',
callback=_CheckChrom... | help='Change the local sav | ed build count limit.')
parser.add_remote_option('--manifest-repo-url',
help=('Overrides the default manifest repo url.'))
group.add_remote_option('--compilecheck', action='store_true', default=False,
help='Only verify compilation and unit tests.')
group.add_re... |
from xcrawler.compatibility.string_converter.compatible_string_c | onverter import Compatib | leStringConverter
class StringConverterPython3(CompatibleStringConverter):
"""A Python 3 compatible class for converting a string to a specified type.
"""
def convert_to_string(self, string):
string = self.try_convert_to_unicode_string(string)
return string
def list_convert_to_string... |
u | pperLimit = 1000
oddCounter = 3
oddList = []
n = 0
while upperLimit >= oddCounter:
oddList.append(oddCounter)
oddCounter += 2
while oddList(n) < (upperLimit - 1):
if o | ddList(n) %
print(oddList) |
# coding=utf-8
import unittest
"""295. Find Median from Data Stream
https://leetcode.com/problems/find-median-from-data-stream/description/
Median is the middle value in an ordered integer list. If the size of the list
is even, there is no middle value. So the median is the mean of the two middle
value.
For example,... | here.
"""
def addNum(self, num):
"""
:type num: int
| :rtype: void
"""
def findMedian(self):
"""
:rtype: float
"""
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
def test(self):
pass
if __nam... |
"""A very simple logger that tries to be concurrency-safe."""
import os, sys
import time
import traceback
import subprocess
import select
LOG_FILE = '/var/log/nodemanager.func'
# basically define 3 levels
LOG_NONE=0
LOG_NODE=1
LOG_VERBOSE=2
# default is to log a reasonable amount of stuff for when running on oper... | result=True
break
# child has failed
else:
log("log_call:end command (%s) returned with code %d" %(message,returncode))
break
# no : still within timeout ?
if time.time() >= trigger:
... | age,timeout))
break
except: log_exc("failed to run command %s" % message)
return result
|
import numpy as np
from displays.letters import ALPHABET
class Writer:
"""Produce scrolling text for the LED display, f | rame by frame"""
def __init__(self):
self.font = ALPHABET
self.spacer = np.zeros([8, | 1], dtype=int)
self.phrase = None
def make_phrase(self, phrase):
"""Convert a string into a long numpy array with spacing"""
# phrase.lower() called because ALPHABET currently doesn't have capitals
converted = [np.hstack([self.font[letter], self.spacer])
for le... |
"""Handle nice names"""
import base64
from | pysyte.oss import platforms
def nice(data):
return base64.b64encode(bytes(data, 'utf-8'))
def name(data):
return base64.b64decode(data).decode('utf-8')
def chmod(data, *_):
platforms.put_ | clipboard_data(name(data))
return ''
|
# Copyright 2017 The TensorFlow Authors. 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 applica... | ms.eval())
def testGatherTreeBatch(self):
batch_size = 10
beam_width = 15
max_time = 8
max_sequence_lengths = [0 | , 1, 2, 4, 7, 8, 9, 10, 11, 0]
end_token = 5
with self.session(use_gpu=True):
step_ids = np.random.randint(
0, high=end_token + 1, size=(max_time, batch_size, beam_width))
parent_ids = np.random.randint(
0, high=beam_width - 1, size=(max_time, batch_size, beam_width))
bea... |
from distutils.core import setup
import | py2e | xe
setup(console=['DTR2Sync.py'])
|
import unittest
from music_app.post import Post
class TestPost(unittest.TestCase):
"""Class to test the Post Class"""
def t | est_object_creation(self):
p = Post('Promises', 'Dreamers', 'rock', '2014', 8, 'http://example.com', 146666666.66, 'https://www.youtube.com')
self.assertEqual(p.title, 'Promises')
se | lf.assertEqual(p.artist, 'Dreamers')
self.assertEqual(p.genre, 'rock')
self.assertEqual(p.year, '2014')
self.assertEqual(p.score, 8)
self.assertEqual(p.thumbnail, 'http://example.com')
self.assertEqual(p.timestamp, 146666666.66)
self.assertEqual(p.url, 'https://www.youtub... |
from __ | future__ import unicode_literals
try:
from django.urls import re_path
except ImportError:
from django.conf.urls import url as re_path
from django.shortcuts import render
from django.views.decorators.http import require_GET
from paypal.standard.pdt.views import process_pdt
@require_GET
def pdt(request, templ... | d implementation of a view that processes PDT and then renders a template
For more advanced uses, create your own view and call process_pdt.
"""
pdt_obj, failed = process_pdt(request)
context = context or {}
context.update({"failed": failed, "pdt_obj": pdt_obj})
return render(request, template,... |
import ast
from python_minifier.rename.binding import NameBinding
from python_minifier.rename.name_generator import name_filter
from python_minifier.rename.util import is_namespace
def all_bindings(node):
"""
All bindings in a module
:param node: The module to get bindings in
:type node: :class:`ast... | in a reservation scope
:param str name: The name to reserve
:param reservation_scope:
:type reservation_scope: Iterable[:class:`ast.AST`]
"""
for namespace in reservation_scope:
namespace.assigned_names.add(name)
| class UniqueNameAssigner(object):
"""
Assign new names to renamed bindings
Assigns a unique name to every binding
"""
def __init__(self):
self.name_generator = name_filter()
self.names = []
def available_name(self):
return next(self.name_generator)
def __call__(se... |
labels for each output.
`loss_` : float
The current loss computed with the loss function.
`label_binarizer_` : LabelBinarizer
A LabelBinarizer object trained on the training set.
`coefs_` : list, length n_layers - 1
The ith element in the list represents the weight matrix corresp... | trix}, shape (n_samples, n_features)
| The input data.
Returns
-------
y_prob : array-like, shape (n_samples, n_classes)
The predicted probability of the sample for each class in the
model, where classes are ordered as they are in `self.classes_`.
"""
y_scores = self.decision_function(X)
... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# 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
# l... |
try:
nom_stat, valeur = msg.split(" / ")
except ValueError:
self.pere << "|err|Syntaxe invalide.|ff|"
else:
# On cherche la stat
stat = None
for t_stat in self.objet:
if not t_stat.max and contient(t_stat.nom, nom_stat)... | stat = t_stat
break
if not stat:
self.pere << "|err|Cette stat est introuvable.|ff|"
else:
# Convertion
try:
valeur = int(valeur)
assert valeur > 0
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 00:00:05 2016
@author: rstreet
"""
import logging
from os import path, remove
from sys import exit
from astropy.time import Time
from datetime import datetime
import glob
def start_day_log( config, log_name, version=None ):
"""Function to initialize a new log fil... | tomatically created
if none for the current UTC day already exist, otherwise output is appended
to an existing file.
| This function also configures the log file to provide timestamps for
all entries.
Parameters:
config dictionary Script configuration including parameters
log_directory Directory path
log_root_name Name of the log file
... |
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import threading
from wpwithin.WPWithinCallback import Client
from wpwithin.WPWithinCallback import Processor
class CallbackHandler:
d... | ceDeliveryToken.key)
print "SDT.Expiry: {0}\n".format(serviceDeliveryToken.expiry)
print "SDT.Issued: {0}\n".format(serviceDeliveryToken.issued)
print "S | DT.Signature: {0}\n".format(serviceDeliveryToken.signature)
print "SDT.RefundOnExpiry: {0}\n".format(serviceDeliveryToken.refundOnExpiry)
except Exception as e:
print "doBeginServiceDelivery failed: " + str(e)
def endServiceDelivery(self, serviceId, serviceDeliveryToken, unitsReceiv... |
# -*- coding: utf-8 -*-
# Copyright 2016-2017 Nate Bogdanowicz
import datetime
__distname__ = "Instrumental-lib"
__version__ = "0.6"
|
__author__ = "Nate Bogdanowicz"
__email__ = "natezb@gmail.com"
__url__ = 'https://github.com/mabuchilab/Instrumental'
__license__ = "GPLv3"
__copyright__ = "C | opyright 2013-{}, {}".format(datetime.date.today().year, __author__)
|
from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... | ))
query_string = "%s&%s&%s" % (method, uri, "&".join(sorted_query))
return hashlib.sha256(query_string.encode("utf8")).hexdigest()
def get_jira_auth_from_request(request):
# https://developer.atlassian.com/static/connect/docs/latest/concepts/authentication.html
# Extract the JWT token from the reque... | t query
# parameter or the authorization header.
token = request.GET.get("jwt")
if token is None:
raise ApiError("No token parameter")
# Decode the JWT token, without verification. This gives
# you a header JSON object, a claims JSON object, and a signature.
decoded = jwt.decode(token, v... |
nt()
order.m_deltaNeutralOrderType = ("NONE" if (receivedInt == 0) else "MKT")
else:
# version 12 and up
order.m_deltaNeutralOrderType = self.readStr()
order.m_deltaNeutralAuxPrice = self.readDoubleMax()
... | >= 27 and not Util.StringIsEmpty(order.m_deltaNeutralOrderType):
order.m_deltaNeutralConId = self.readInt()
order.m_deltaNeutralSettlingFirm = self.readStr()
order.m_deltaNeutralClearingAccount = self.readStr()
order.m_delta... | order.m_continuousUpdate = self.readInt()
if self.m_parent.serverVersion() == 26:
order.m_stockRangeLower = self.readDouble()
order.m_stockRangeUpper = self.readDouble()
order.m_referencePriceType = self.readInt()
if ver... |
#!/usr/bin/env python
from | setuptools import setup
setup(name='features',
version='0.1',
description='A collection of feature extraction/selection algorithms',
author='Charanpal Dhanjal',
author_email='charanpal@gmail.com',
url='https://github.com/charanpald/features',
install_requires=['numpy>=1.5.0', 'scip... | "kernel.test"],
)
|
#The MIT License (MIT)
#Copyright (c) 2015-2016 mh4x0f P0cL4bs Team
#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, mo... | )
def sniff_probe(self,p):
if (p.haslayer(Dot11ProbeReq)):
mac_address=(p.addr2)
ssid=p[Dot11Elt].info
ssid=ssid.decode('utf-8','ignore')
if ssid == "":ssid="null"
self.list_probe.addItem("[:] Probe Request from | %s for SSID '%s'" %(mac_address,ssid)) |
t self.replacement_db_product.end_of_sale_date or \
self.replacement_db_product.current_lifecycle_states == [Product.NO_EOL_ANNOUNCEMENT_STR]:
# product is not EoL and therefore valid
return True
else:
return Fa... | self.full_clean()
# normalize value in database, remove duplicates and sort the list
values = self.get_string_product_list_as_list()
self.string_product_list = "\n".join(sorted(list(set(values))))
# calculate hash value for Product check linking on the queries
s = "%s:%s:%s"... | based_on_products(self):
# discovery vendor based on the products (if not set, used primary for data migration)
if self.vendor is None:
product_id_list = self.get_string_product_list_as_list()
if len(product_id_list) > 0:
self.vendor = Product.objects.filter(produ... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | '])
plugin.register_semantic_types(SampleData, AlphaDiversity)
plugin.register_semantic_type_to_format(
SampleData[AlphaDiversity],
artifact_format=AlphaD | iversityDirectoryFormat
)
|
le:
self.client.force_login(self.admin_user)
response = self.client.post(reverse('oppia:upload'),
{'course_file': course_file})
self.assertEqual(200, response.status_code)
course_log = CoursePublishingLog.objects.latest('log_date')... | tionEvent.objects.all().count()
self.assertEqual(media_game_events_start+4, media_game_events_end)
activity_game_events_end = ActivityGamificationEvent. \
objects.all().count()
self.assertEqual(activity_game_events_start+1,
activity_game_e | vents_end)
@pytest.mark.xfail(reason="works on local but not on github workflows")
def test_course_with_custom_points_updated(self):
with open(self.course_with_custom_points, 'rb') as course_file:
self.client.force_login(self.admin_user)
response = self.client.post(reverse('opp... |
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, True)
def test_share_volume_above_oversub_ratio(self):
fake_capacity_info = (4, 4, 7)
fake_volume_size = 2
ret_value = se... | lume_size = 1
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_parse_options(self):
(opt_list,
opt_dict) = self._smbfs_driver.parse_options(
self._... | AKE_SHARE_OPTS)
expected_ret = ([], self._FAKE_OPTIONS_DICT)
self.assertEqual(expected_ret, (opt_list, opt_dict))
def test_parse_credentials(self):
fake_smb_options = r'-o user=MyDomain\Administrator,noperm'
expected_flags = '-o username=Administrator,noperm'
flags = self._s... |
# -*- coding: utf-8 -*-
import pandas as pd
import sys
from builtins import str as text
from utils import find_zipcode, str2date
header | _mapping = {
'origin': 'ORIGIN',
'company_name': 'LABO',
'lastname_firstname': 'BENEF_PS_QUALITE_NOM_PRENOM',
'address': 'BENEF_PS_ADR',
'job': 'BENEF_PS_QUALIFICATION',
'rpps': 'BENEF_PS_RPPS',
'value': 'DECL_AVANT_MONTANT',
'date': 'DECL_AVANT_DATE',
'kind': 'DECL_AV | ANT_NATURE',
'BENEF_PS_CODEPOSTAL': 'BENEF_PS_CODEPOSTAL'
}
input_filename = sys.argv[1]
output_filename = sys.argv[2]
df = pd.read_csv(input_filename, encoding='utf-8')
df['lastname_firstname'] = df['name'] + ' ' + df['firstname']
df['origin'] = 'Pharmacien'
df['date'] = df['date'].apply(str2date)
df['BENEF_PS_... |
omico',
'cbElencoPrezzi',
'cbComputoMetrico',
'cbCostiManodopera',
'cbQuadroEconomico',
)
def loadExportSettings(oDoc):
cfg = LeenoConfig.Config()
data = DocUtils.loadDataBlock(oDoc, 'ImpostazioniExport')
if data is None or len(data) == 0:
data = cfg.readBlock('ImpostazioniExport', ... |
ep = oDoc.Sheets.getByName('Elenco Prezzi')
# lancia l'export
nDoc = str(nTavola)
baseName = ''
if nDoc != '' and nDoc is not None:
baseName = nDoc + '-'
destPath = os.path.join(destFolder, baseName + 'ElencoPrezzi.pdf')
print(f"Export to '{destPath}' file")
selection = [ep, ]
... | }
headerFooter = prepareHeaderFooter(oDoc, docSubst)
SheetUtils.pdfExport(oDoc, selection, destPath, headerFooter, lambda oDoc, nDoc: prepareCover(oDoc, nDoc, docSubst))
# purtropp non c'è alcun modo di determinare in anticipo il numero di pagine, indi
# dobbiamo creare il PDF, usare una funzione per c... |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the Licen... | 0.0 0.346
0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338
0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 | 0.394 0.559 0.653 -0.0329 0.0202 0.349
0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351
0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356
0.90 1.433 -0.00232 0... |
from asposewords import Settings
from com.aspose.words import Document
from com.aspose.words import BreakType
from com.aspose.words import DocumentBuilder
from com.aspose.words import StyleIdentifier
class UpdateFields:
def __init__(self):
dataDir = Settings.dataDir + 'quickstart/'
# Demo... | the second page.
builder.insertBreak(BreakTyp | e.SECTION_BREAK_NEW_PAGE)
# Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1)
builder.writeln("Heading 1")
builder.getParagraphFormat().setStyleIdenti... |
# -*- coding: utf-8 -*-
import unittest
from getkey.platforms import PlatformTest
def readchar_fn_factory(stream):
v = [x for x in stream]
def inner(blocking=False):
return v.pop(0)
return inner
class TestGetkey(unittest.TestCase):
def test_basic_character(self):
getkey = Platform... | result = getkey()
self.assertEqual(char, result)
def test_special_key(self):
char = '\x1b\x5b\x41'
getkey = PlatformTest(char + 'foo').getkey
result = getkey()
self.assertEqual(char, result)
def test_special_key_combo(self):
char = '\x1b\x5b\x33\x5e'
... | xt = u'Ángel'
getkey = PlatformTest(text).getkey
result = getkey()
self.assertEqual(u'Á', result)
|
from django.db import models
class Empresa(models.Model):
nombre | = models.CharField(max_length=100)
ciudad = models.CharField(max_length=50)
sector = models.CharField(max_length=200)
def __str__(self):
return | self.nombre
class Calificacion(models.Model):
alumno = models.CharField(max_length=100)
calificacion = models.IntegerField(default=0)
empresa = models.ForeignKey(Empresa)
def __str__(self):
return self.alumno
|
from seleniumhelpers import SeleniumTestCase |
from seleniumhelpers import get_default_timeout
from seleniumhelpers import get_se | tting_with_envfallback
|
# Copyright 2016 Conchylicultor. 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 ... | """
return self.rnn_cell.zero_state(batch_size=self.args.batch_size, dtype=tf.float32)
def get_cell(self, prev_input, prev_states):
"""
"""
next_output, next_state = self.rnn_cell(prev_input, prev_states[1])
next_output = self.proje | ct_output(next_output)
# No activation function here: SoftMax is computed by the loss function
return next_output, next_state
|
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If an stale block more than a month old or its header are requeste... | ,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import threading
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.mininode import (
CInv,
NodeConnCB,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
| network_thread_start,
wait_until,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
p2p_port)
class P2PFingerprintTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
... |
pady=2, sticky=W)
#
cal.transient(siWin)
cal.grab_set()
siWin.wait_window(cal)
print( '\nmonoCal(): done!')
#
## Power Up - operations to sequence initialization of hardware/software
#
def PowerUp():
'''Load "settings" and calibrate SPEX.'''
global serOutReady
#
readSet... | ,activebackground=ACTIVB, font=monoFont14 )
macroFileLoad.grid(row=0, column=0,sticky=NW)
#
#
macroEditIcon = PhotoImage(file='icons/icon_macroEDIT.gif')
#
#-------
macroFileEdit = Button(macroFrame, image=macroEditIcon, bg = TANBG
, borderwidth = 0
,activebackground... |
#====================================
## Settings Frame
#
#-------
settingsFrame = LabelFrame(controlsFrame,text='Settings',
bg = TANBG, borderwidth=4)
settingsFrame.grid(row=12,column=0, sticky=S)
#
#
settingsIcon = PhotoImage(file='icons/icon_settings.gif')
#
#-------
settingsBtn = Button(setti... |
# -*- encoding: utf-8 -*-
#
# 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, so... | for i in six.moves.range(self.NUM_SACKS):
for metric in self.list_metric_with_measures_to_process(i):
build_metric_report(metric, i)
return (report_vars['metrics'] or
len(report_vars['metric_details'].keys()),
report_vars['measures'] or
... | return set(self._list_target(self._sack_path(sack)))
def _list_measures_container_for_metric_id_str(self, sack, metric_id):
return self._list_target(self._measure_path(sack, metric_id))
def _list_measures_container_for_metric_id(self, metric_id):
return self._list_target(self._build_measure... |
"""This demo program solves the incompressible Navier-Stokes equations
on an L-shaped domain using Chorin's splitting method."""
# Copyright (C) 2010-2011 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Publi... | - DOLFIN_EPS")
outflow = DirichletBC(Q, 0, "x[0] > 1.0 - DOLFIN_EPS")
bcu = [ | noslip]
bcp = [inflow, outflow]
# Create functions
u0 = Function(V)
u1 = Function(V)
p1 = Function(Q)
# Define coefficients
k = Constant(dt)
f = Constant((0, 0))
# Tentative velocity step
F1 = (1/k)*inner(u - u0, v)*dx + inner(grad(u0)*u0, v)*dx + \
nu*inner(grad(u), grad(v))*dx - inner(f, v)*dx
a1 = lhs(F1)
L1... |
from __future__ import | absolute_import
from .base import *
from .local import *
CACHE_BA | CKEND = 'redis_cache.cache://127.0.0.1:6379/?timeout=15'
DEBUG = False
|
"""
Learning python3
"""
def document_it(func):
'''
decractor for func, only print doc of func.
'''
def new_function(*args, **kwargs):
'''
internal function for wrappering of func and print out function parameter and result.
'''
print('Running functions:', func.__name__)
... | rgs)
print('Result:', result)
return result
return new_function
@document_it
def add_ints0(add_a, add_b):
'''
add with decrator of @document_it.
'''
return add_a + add_b
def square_it(func):
'''
decractor for func, return square of func returned | value.
'''
def new_function(*args, **kwargs):
'''
internal function for wrappering of func and return square of func as result.
'''
result = func(*args, **kwargs)
return result * result
return new_function
@document_it
@square_it
def add_ints1(add_a, add_b):
'''
... |
.bsz = NervanaObject.be.batch_size = batch_size
check_gru(seq_len, input_size, hidden_size, batch_size,
Gaussian())
def test_ref_compare_rand_init_state(backend_default, refgruargs):
seq_len, input_size, hidden_size, batch_size = refgruargs
NervanaObject.be.bsz = NervanaObject.be.batch_size... | ndn(*output_shape)
# run neon fprop
gru.configure((input_size, seq_len))
gru.prev_layer = True
gru.allocate()
test_buffer = DeltasTree()
gru.allocate_deltas(test_buffer)
test_buffer.allocate_buffers()
gru.set_deltas(test_buffer)
if add_init_state:
init_state = np.random.ra... | ms[1] + inp_moms[0]
init_state_dev = gru.be.array(init_state)
gru.fprop(inp_dev, init_state=init_state_dev)
else:
gru.fprop(inp_dev)
# reference numpy GRU
gru_ref = RefGRU(input_size, hidden_size)
WGRU = gru_ref.weights
# make ref weights and biases the same with neon model... |
a = "¢пр"
print(a[0], a[0: | 1])
print(a[1], a[1:2])
print(a[2], a[2:3])
try:
print(a[3])
except IndexError:
print("IndexError")
print(a[3:4])
print(a[-1])
p | rint(a[-2], a[-2:-1])
print(a[-3], a[-3:-2])
try:
print(a[-4])
except IndexError:
print("IndexError")
print(a[-4:-3])
print(a[0:2])
print(a[1:3])
print(a[2:4])
|
# -*- coding: utf8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2011 *
#* Yorik van Havre <yorik@uncreated.net> ... | else :
ss = "[ "
for o in siteobj:
ss += "FreeCAD.ActiveDocumen | t." + o.Name + ", "
ss += "]"
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Site"))
FreeCADGui.addModule("Arch")
FreeCADGui.doCommand("Arch.makeSite("+ss+")")
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recom... |
# This file is part of jacqq.py
# Copyright (C) 2015 Saman Jirjies - sjirjies(at)asu(dot)edu.
#
# 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 opt... | rt_date, end_date, case_point[0], case_point[1]))
writer.writerow(('control_'+str(id_index+1)+'A', start_date, end_date, case_point[0], case_point[1]-2))
writer.writerow(('control_'+str(id_index+1)+'B', start_date, end | _date, case_point[0]+2, case_point[1]))
writer.writerow(('control_'+str(id_index+1)+'C', start_date, end_date, case_point[0]+1, case_point[1]+1))
writer.writerow(('control_'+str(id_index+1)+'D', start_date, end_date, case_point[0]-1, case_point[1]+1))
writer.writerow(('control_'+str(... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the core module.
"""
import itertools
from contextlib import nullcontext
from astropy.modeling.models import Gaussian1D, Gaussian2D
from astropy.utils.exceptions import AstropyUserWarning
import numpy as np
from numpy.testing import assert_... | e:
mask = None
nwarn = 1
ctx = pytest.warns(AstropyUserWarning,
match='Input data contains | non-finite values')
with ctx as warnlist:
xc, yc = centroid_1dg(data, mask=mask)
assert_allclose([xc, yc], [xc_ref, yc_ref], rtol=0, atol=1.e-3)
if nwarn == 1:
assert len(warnlist) == nwarn
with ctx as warnlist:
xc, yc = centroid_2dg(data, mask=mask)
assert_allclose([xc, yc... |
r = list(bch.torque_fft[-1]['order'])
if order and max(order) < 5:
order += [15]
tq += [0]
torque_fft(order, tq)
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+... | h.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['o... | ce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos,
[f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos,
[f['current_k'... |
"""
gof.py
gof stands for Graph Optimization Framework
The gof submodule of theano implements a framework
for manipulating programs described as graphs. The
gof module defines basic theano graph concepts:
-Apply nodes, which represent the application
of an Op to Variables. Together these make up a
graph.
-The... | f domain-specific language could be
made by using gof with different Variables and Ops.
In practice, gof and the rest of theano are somewhat more
tightly intertwined.
Currently, gof also contains much of the C compilation
functionality. Ideally this should be refactored into
a different submodule.
For more details an... | t \
CLinker, OpWiseCLinker, DualLinker, HideC
# Also adds config vars
from theano.gof.compiledir import \
local_bitwidth, python_int_bitwidth
from theano.gof.fg import \
CachedConstantError, InconsistencyError, MissingInputError, FunctionGraph
from theano.gof.destroyhandler import \
DestroyHandler
f... |
#!/usr/bin/env python3
# Copyright (c) 2016 The nealcoin C | ore developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""S | pecialized SipHash-2-4 implementations.
This implements SipHash-2-4 for 256-bit integers.
"""
def rotl64(n, b):
return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b
def siphash_round(v0, v1, v2, v3):
v0 = (v0 + v1) & ((1 << 64) - 1)
v1 = rotl64(v1, 13)
v1 ^= v0
v0 = rotl64(v0, 32)
v2 = (v2... |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test resources processing, i.e. <if> and <include> tag handling."""
import unittest
from processor import FileCache, Processor, Lin... | @fileoverview Coolest app ever.
* @author Douglas Crockford (douglas@crockford.com)
*/
<include src="/global.js">
debug(global);
// Here continues checked.js, a swell file.
""".strip()
FileCache._cache["/double-debug.js"] = """
<include src="/debug.js">
<include src="/debug.js">
""".strip()
| self._processor = Processor("/checked.js")
def testInline(self):
self.assertMultiLineEqual("""
// Copyright 2028 Future Chromium Author dudes.
/**
* @fileoverview Coolest app ever.
* @author Douglas Crockford (douglas@crockford.com)
*/
// Copyright 2014 Old Chromium Author dudes.
// Copyright 2002 Older Chro... |
self._jstore.save(self._json)
def get_user(self):
"""
Returns the current user
:return: user
"""
return self._user
def get_watch_later_id(self):
"""
Returns the current users watch later playlist id
:return: the current users watch late... | rns the access token for some API
:para | m addon_id: addon id
:return: access_token
"""
self._json = self._jstore.get_data()
return self._json['access_manager']['developers'].get(addon_id, {}).get('access_token', '')
def get_dev_refresh_token(self, addon_id):
"""
Returns the refresh token
:return: r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.