prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import math
import sys
import re
valuePattern = re.compile('= (.+)$')
def extractValue(line):
match = re.sea | rch(valuePattern, line)
if match:
return float.fromhex(match.group(1))
else:
return "ERROR"
intervalPattern = re.compile('= \[(.*?), (.*?)\]')
def extractInterval(line):
match = re.search(intervalPattern, line)
if match:
lower = float.fromhex(match.group(1))
| upper = float.fromhex(match.group(2))
return (lower, upper)
else:
return "ERROR"
def isInInterval(value, lower, upper):
return lower<=value and value<=upper
#f1 - values, f2 - ranges
f1 = open(str(sys.argv[1]), 'r')
f2 = open(str(sys.argv[2]), 'r')
wide = 0
total = 0
result = 0
for line1, line2 in z... |
# create a Session object by sessionmaker
import os
import ConfigParser
import sqlalchemy.orm
# get path to taskmanager. it is assumed that this script is in the lib directory of
# the taskmanager package.
tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) )
etcpath =... | self.engine = sqlalchemy.create_engine( "{dialect}://{user}:{password}@{host}:{port}/{name}".format( dialect=databaseDialect,
| user=databaseUsername,
password=databasePassword,
... |
break
else:
xlog.warn("entity header:%s", line)
break
payload += self.rfile.read(chunk_size)
get_crlf(self.rfile)
gae_handler.handler(self.command, self.path, request_headers, payload, se... | dline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
xlog.warn("read request line len:%d", len(self.raw_requestline))
return
... | ine:
xlog.warn("read request line empty")
return
if not self.parse_request():
xlog.warn("parse request fail:%s", self.raw_requestline)
return
except NetWorkIOError as e:
if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRE... |
def func(bar):
""" \\some comment
@param bar: The pa | rameter value.
| @type bar: Its type."""
pass
|
esults
def _dataset_for_stmt(ds, extra_test, body, init_state):
"""Overload of for_stmt that iterates over TF Datasets."""
if extra_test is not None:
raise NotImplementedError(
'break and return statements are not yet supported in '
'for/Dataset loops.')
def reduce_body(state, iterate):
... | a'
' TensorFlow loop? For example, `while True:` is a Python loop, and'
' `while tf.constant(True):` is a TensorFlow loop. The following'
' ops were created after iteration %s: %s', self.iterations, new_ops)
return True
def bef | ore_iteration(self):
"""Called before each iteration in a Python loop."""
if (self.check_inefficient_unroll and
self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS):
self.ops_before_iteration = self._get_ops()
self.check_op_count_after_iteration = True
def after_iteration(self):
"""Ca... |
del,),
),
migrations.CreateModel(
name='Ddjj',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('ano', models.IntegerField()),
('tipo_ddjj_id', models.IntegerField(choices=... | ,
('dias', models.CharField(max_length=255, blank=True)) | ,
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'db_table': 'tiempo_controls',
},
bases=(models.Model,),
),
migrations.CreateModel(... |
import os
import json
import urllib
import socket
import subprocess as sub
import string
import sys
MPCONF = "/etc/magicpool.conf"
MPURL = "https://magicpool.org/main/download_config/${U}/${W}/${G}"
SGCONF = "/home/crypto/.sgminer/sgminer.conf"
def niceprint(data):
return json.dumps(data,sort_keys=True,indent=4, se... | s | awk '{print $1}' > /tmp/get-pool.md5.2" % (SGCONF+".old"))
md51 = open("/tmp/get-pool.md5.1","r")
md52 = open("/tmp/get-pool.md5.2","r")
if md51.read() == md52.read():
print "No changes in configuration"
else:
print "Found changes in configuration, restarting sgminer"
#os.system('echo "quit|1" | | nc 127.0.0.1 4028')
os.system('killall -USR1 sgminer')
md51.close()
md52.close()
def getMPconf():
try:
mpconf = open(MPCONF,"r")
mp = json.loads(mpconf.read())
user = mp['username']
worker = mp['workeralias']
except:
user = "generic"
worker = "generic"
return {"user":user,"worker":worker}
def getMP... |
""" RUN RUN RUN !
"""
from buttersalt import create_app
from f | lask_script import Manager, Shell
app = create_app('default')
manager = Manager(app)
def make_shell_context():
return dict(app=app)
manager.add_command("shell", Shell(make_context=make_shell_context))
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = | unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == "__main__":
manager.run()
|
#!/usr/bin/env python3
# Copyright Istio Authors
#
# 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 agr... | deployment_replicas(TEST_NAMESPACE, LEGACY_DEPLOY)
total = istio_count + legacy_count
output = 'sidecar replica {}, legacy replica {}\n\n'.format(
istio_count, legacy_count)
istio_count = int(istio_pe | rcent * total)
legacy_count = total - istio_count
output += ('======================================\n'
'Scale Istio count {sc}, legacy count {nsc}\n\n').format(
sc=istio_count, nsc=legacy_count
)
scale_deployment(TEST_NAMESPACE, ISTIO_DEPLOY, istio_count)
scale_deployment(TES... |
from sklearn.feature_extraction.text import TfidfVectorizer
import xgboost as xgb
import cPickle as pickle
from string import punctuation
from nltk import word_tokenize
from nltk.stem import snowball
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style... | ..."
# vect = pickle.load(open('vect.p', 'rb'))
#
# cvpath = 'twitter_cross_val.csv'
# dfcv = pd.read_csv(cvpath)
# Xcv = dfcv['tweet_text'].values
# ycv = dfcv['label'].values
#
# print "transforming cross val data..."
# tfidf_Xcv = vect.tra | nsform(Xcv)
# tfidf_Xcvd = tfidf_Xcv.todense()
#
# xg_cv = xgb.DMatrix(tfidf_Xcvd, label=ycv)
# print "loading training data..."
# xg_train = xgb.DMatrix('xg_train2.buffer')
# xg_cv = xgb.DMatrix('xg_cv2.buffer')
train_tstart = time.time()
print 'training...'
#parameters
param... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | DOLAG column text format
# -----------------------------------------------------------------
# return the age of a star (in yr) given the universe ex | pansion factor when the star was born (in range 0-1)
@np.vectorize
def age(R):
H0 = 2.3e-18
OmegaM0 = 0.27
yr = 365.25 * 24 * 3600
T0 = 13.7e9
return T0 - (2./3./H0/np.sqrt(1-OmegaM0)) * np.arcsinh(np.sqrt( (1/OmegaM0-1)*R**3 )) / yr
# return the radius of a particle (in kpc) given its mass (in Msu... |
fro | m OpenGLCffi.GL | ES1 import params
@params(api='gles1', prms=['target', 'numAttachments', 'attachments'])
def glDiscardFramebufferEXT(target, numAttachments, attachments):
pass
|
"""
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from tests.helpers import login_user
def test_view_for_brand(jobs_admin_client):
url = '/admin/jobs/'
response = jobs_admin_client.get(url)
assert response.status_code == 200
@pytest... | e')
def jobs_admin(make_admin):
permission_ids = {
'admin.access',
'jobs.view',
}
admin = make_admin('JobsAdmin', permission_ids)
login_user(admin.id)
return admin
@pytest.fixture(s | cope='package')
def jobs_admin_client(make_client, admin_app, jobs_admin):
return make_client(admin_app, user_id=jobs_admin.id)
|
DEPS = | [
'chromium',
'chromium | _android',
'gsutil',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
]
|
from core_tests_base import CoreTestsBase, FakeTessagon, FakeTileSubClass
class TestTile(CoreTestsBase):
# Note: these tests are highly dependent on the behavior of
# FakeTessagon and FakeAdaptor
def test_add_vert(self):
tessagon = FakeTessagon()
tile = FakeTileSubClass(tessagon, u_rang... | tile.add_vert(['top', 'left'] | , 0.25, 0.75)
assert tile.blend(0.25, 0.75) == [0.625, 2.875]
# One vert added
assert tile.verts['top']['left'] == tile.f(0.625, 2.875)
assert tile.verts['top']['right'] is None
assert tile.verts['bottom']['left'] is None
assert tile.verts['bottom']['right'] is None
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------------------------
# Program Name: Lychee
# Program Description: MEI document manager for formalized document control
#
# Filename: lychee/__init__.py
# Purpose: ... | ou should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#--------------------------------------------------------------------------------------------------
"""
Initialize Lychee.
"""
__all__ = [
'converters',
'document',
'exce... | espaces',
'signals',
'tui',
'workflow',
'vcs',
'views',
]
from lychee import *
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
import unittest
from artifice.models import usage, tenants, resources, Session
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.orm.exc import FlushError
import os
from artifice.models.usage import Usage
from artifice.models.tenants import Tenant
from ... | sage(r, t, 1, start, end )
u.id = USAGE_ID
self.objects.append(u)
self.session.add(u)
self.session.add(r)
self.s | ession.add(t)
self.session.commit()
u2 = self.session.query(Usage)[0]
self.assertTrue( u2.resource.id == r.id )
self.assertTrue( u2.tenant.tenant.id == t.id )
self.assertTrue( u2.created == u.created )
print u2.time
def test_overlap_throws_exception(self):
... |
)
),
(0, 'Other'),
(5, _('translated')),
)
c = models.IntegerField(choices=CHOICES, null=True)
class WhizDelayed(models.Model):
c = models.IntegerField(choices=(), null=True)
# Contrived way of adding choices later.
WhizDelayed._meta.get_field('c').choices = Whiz.CHOICES
clas... | ion
field.
"""
name = models.CharField(max_length=50)
class PersonWithHeightAndWidth(models.Model):
"""
Model that defines height and width fields after the ImageField.
"""
name = models.CharField(max_length=50)
mugshot = TestImageField(storage=temp_s... | to='tests',
height_field='mugshot_height',
width_field='mugshot_width')
mugshot_height = models.PositiveSmallIntegerField()
mugshot_width = models.PositiveSmallIntegerField()
class PersonDimensionsFirst(models.Model):
"""
... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
from petl.compat import next, string_types
from petl.util.base import iterpeek, ValuesView, Table
from petl.util.materialise import columns
def infer_dtype(table):
import numpy as np
# get numpy to infer dtype
it = ... | as np
return toarray(*args, **kwargs).view(np.recarray)
Table.torecarray = torecarray
def fromarray(a):
"""
Extract a table from a `numpy <http://www.numpy.org/>`_ structured array,
e.g | .::
>>> import petl as etl
>>> import numpy as np
>>> a = np.array([('apples', 1, 2.5),
... ('oranges', 3, 4.4),
... ('pears', 7, 0.1)],
... dtype='U8, i4,f4')
>>> table = etl.fromarray(a)
>>> table
+------... |
# -*- coding: utf-8 -*-
from nose.tools import (
eq_,
raises,
)
from py3oauth2.utils import (
normalize_netloc,
normalize_path,
normalize_query,
normalize_url,
)
def test_normalize_url():
eq_(normalize_url('http://a/b/c/%7Bfoo%7D'),
normalize_url('hTTP://a/./b/../b/%63/%7bfoo%7d')... | eq_(normalize_path('/a//b'), '/a/b/')
eq_(normalize_path('/a/./b'), '/a/b/')
eq_(normalize_path('/a/foo/../b'), '/a/b/')
eq_(normalize_path('/%e3%81%82%a%e3%81%84'), '/%E3%81%82%a%E3%81%84/')
eq_(normalize_path('/%e3%81%82a%e3%81%84'), '/%E3%81%82a% | E3%81%84/')
|
import os
from PyQt4 import QtCore, QtGui
from Extensions.Global import sizeformat
class SearchWidget(QtGui.QLabel):
def __init__(self, parent):
QtGui.QLabel.__init__(self, parent)
self._parent = parent
self.setStyleSheet("""background: rgba(0, 0, 0, 50); border-radius: 0... | ultItemCountLabel, sizeLabel, busyIndicatorWidget, parent):
QtGui.QListWidget.__init__(self, parent)
self.redCenter = parent
self.setLayoutMode(1)
self.setBatchSize(1)
self.setUniformItemSizes(True)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedS... | self.setAlternatingRowColors(True)
self.setIconSize(QtCore.QSize(30, 30))
self.itemSelectionChanged.connect(self.selectionMade)
searchWidget = SearchWidget(self)
searchWidget.move(80, 0)
searchWidget.hide()
self.vaultItemCountLabel = vaultItemCou... |
oding: utf-8 -*-
"""
This is part of HashBruteStation software
Docs EN: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station_en
Docs RU: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Integration tests for Hash... | self._clean_db()
self.thrd = HashlistsByAlgLoaderThread()
self.thrd.delay_per_check = 1
self.thrd.catch_exceptions = False
self.loader_thrd = HashlistsLoaderThread()
self.loader_thrd.delay_per_check = 1
self.loader_thrd.catch_ | exceptions = False
def teardown(self):
""" Tests teardown """
if isinstance(self.thrd, HashlistsByAlgLoaderThread):
self.thrd.available = False
time.sleep(1)
del self.thrd
if isinstance(self.loader_thrd, HashlistsLoaderThread):
self.loader_thr... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION | FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Weapon()
result.template = "object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_s1_gen2.iff"
result.attribute_template_id = 10
result.stfName("weapon_name","sword | _lightsaber_lance_type1")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
###############################################################################
#
# Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights
# Reserved.
#
# This program is free software; you can redistribute it and/or | modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of ME... | ee 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/>.
#
###############################################################################
__metaclass__ = type
import genshi.core
... |
from gerencianet import Gerencianet
from credentials import CREDENTIALS
gn = Gerencianet(CREDENTIALS)
params = {
'txid': ''
}
body = {
| 'calendario': {
'expiracao': 3600
},
'devedor': {
'cpf': '',
'nome': ''
},
'valor': {
'original': '0.50'
},
'chave': '',
'solicitacaoPagador': 'Cobrança dos ser | viços prestados.'
}
response = gn.pix_create_charge(params=params,body=body)
print(response)
|
from alphatwirl.selection.factories.AllFactory import AllFactory
from alphatwirl.selection.modules.basic import All
from alphatwirl.selection.modules.basic import Any
from alphatwirl.selection.modules.LambdaStr import LambdaS | tr
import unittest
##__________________________________________________________________||
class Te | st_AllFactory(unittest.TestCase):
def test_obj(self):
path_cfg_list = ("ev : ev.nJet[0] >= 2", "ev : ev.nMET[0] >= 200")
kargs = dict(arg1 = 10, arg2 = 20, AllClass = All, LambdaStrClass = LambdaStr)
obj = AllFactory(path_cfg_list, name = 'test_all', **kargs)
##____________________________... |
erModes is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fi... | _value = [ | low]
else:
self._value = [low + index*(high |
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | bble.get_message
bubble.get_message = fake_get_message
utils.get_message = fake_get_message
def tearDown(self):
utils.get_message = self.real_get_message
bubble.get_message = self.real_get_message
os.environ['AUTH_DOMAIN'] = self.real_auth_domain
def test_value_info_ext... | name='haiti:example.org/123', type='hospital')
s.set_attribute('title', 'title_foo', datetime.datetime.now(),
users.User('test@example.com'),
'nickname_foo', 'affiliation_foo', 'comment_foo')
s.set_attribute('attribute_value', 'fake_to_localize',
... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | essionFormat': 'UNCOMPRESSED',
},
)
stream_arn = response['DeliveryStreamARN']
self.assertEqual(stream_arn, "arn:aws:firehose:us-east-1:123456789012:deliverystream/test_airflow")
records = [{"Data": str(uuid.uuid4())} for _ in range(100)]
response = hook.put_record... | elf.assertEqual(response['FailedPutCount'], 0)
self.assertEqual(response['ResponseMetadata']['HTTPStatusCode'], 200)
|
from myhdl import always, always_seq, block, delay, enum, instance, intbv, ResetSignal, Signal, StopSimulation
@block
def uart_tx(tx_bit, tx_valid, tx_byte, tx_clk, tx_rst):
index = Signal(intbv(0, min=0, max=8))
st = enum('IDLE', 'START', 'DATA')
state = Signal(st.IDLE)
@always(tx_clk.posedg... | d delay(100)
for v in (0x00, 0xff, 0x55, 0xaa):
yield tx_clk.negedge
tx_byte.next = v
tx_valid.next = 1
yield tx_clk.negedge
tx_valid.next = 0
yield delay(16 * 20)
raise StopSimulation
return clk_gen, stimulus, uart_tx_inst... | |
import os
from setuptools import setup, fin | d_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='poloniex',
version='0.1',
packages=[
'poloniex',
... | ude_package_data=True,
description='Python Poloniex API',
long_description=README,
url='https://github.com/absortium/poloniex.git',
author='Andrey Samokhvalov',
license='MIT',
author_email='andrew.shvv@gmail.com',
install_requires=[
'asyncio',
'aiohttp',
'autobahn',
... |
the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# ... | can drive RGB layers with a color,
or connect individual channels to a float.
If you want to add multiple channels at once, you can also add a closure plug,
which can accept a connection from an OSLCode with a combined output closure.
""",
"layout:customWidget:footer:widgetType", "GafferOSLUI.OSLImageU... | dule",
"noduleLayout:section", "left",
"noduleLayout:spacing", 0.2,
"plugValueWidget:type", "GafferUI.LayoutPlugValueWidget",
# Add + button for showing and hiding parameters in the GraphEditor
"noduleLayout:customGadget:addButton:gadgetType", "GafferOSLUI.OSLImageUI.PlugAdder",
],
"channels.*" : [
... |
class Zone | :
def __init__(self, id_zone, name, region, description):
self.id = id_zone
self.name = name
self.region = region
self.description = descriptio | n
|
#!/usr/bin/env python
# Copyright 2018 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.
import glob
import os
import shutil
import subprocess
import sys
netlog_viewer_root_path = os.path.abspath(
os.path.join(os.pa... | t-get install npm
sudo npm install -g vulcanize
'''[1:])
sys.exit(1)
for fn in glob.glob | (os.path.join(src_dir, "*.png")):
shutil.copyfile(fn, os.path.join(out_dir, os.path.split(fn)[1]))
|
# Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | s()
return vif
@base.remotable_classmethod
def get_by_domain(cls, context, domain):
db_dnsd = db.dnsdomain_get(context, d | omain)
if db_dnsd:
return cls._from_db_object(context, cls(), db_dnsd)
@base.remotable_classmethod
def register_for_zone(cls, context, domain, zone):
db.dnsdomain_register_for_zone(context, domain, zone)
@base.remotable_classmethod
def register_for_project(cls, context, dom... |
# D | efinition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node.left and not node.right: return node
h... | if node.left:
head = dfs(node.left)
cur = head
while cur.right:
cur = cur.right
cur.right = node
return head
else:
return node
return dfs(root)
t = TreeNode(2)
t.left = TreeNode(... |
ht: This module has been placed in the public domain.
"""
Tests for docutils.transforms.references.Substitutions.
"""
from __init__ import DocutilsTestSupport
from docutils.transforms.references import Substitutions
from docutils.parsers.rst import Parser
def suite():
parser = Parser()
s = DocutilsTestSuppo... | [
["""\
Insert an em-dash (|mdash|), a copyright symbol (|copy|), a non-breaking
space (|nbsp|), a backwards-not-equals (|bne|), and a captial omega (|Omega|).
.. | |mdash| unicode:: 0x02014
.. |copy| unicode:: \\u00A9
.. |nbsp| unicode::  
.. |bne| unicode:: U0003D U020E5
.. |Omega| unicode:: U+003A9
""",
u"""\
<document source="test data">
<paragraph>
Insert an em-dash (
\u2014
), a copyright symbol (
\u00a9
), a non-breaking
... |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
admin.au | todiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'votainteligente | .views.home', name='home'),
# url(r'^votainteligente/', include('votainteligente.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(... |
'''
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). F | ind two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
'''
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
lo, hi = 0, len(height) - ... | while lo < hi:
theBest = max(theBest, (hi - lo) * min(height[lo], height[hi]))
if height[lo] < height[hi]:
lo += 1
else:
hi -= 1
return theBest
def maxArea_TLE2(self, height):
maxlen = len(height)
def _max_area_as_short_s... |
import os
import discord
import requests
from utils import functions
description = "Show bot log"
perm = 2
async def ex(message, client):
if not os.path.isfile("screenlog.0"):
await client.send_message(message.channel, embed=discord.Embed(colour=discord.Color.red(),
| description="File `screenlog.0` does not exist!"))
else:
with open("screenlog.0") as f:
lines = f.readlines()
log_full = ""
for string in lines:
log_full += string
if len(lines | ) > 10:
lines = lines[len(lines) - 10:len(lines)]
log = ""
for string in lines:
log += string
message_send = await client.send_message(message.channel, embed=discord.Embed(
description="Uploading log to pastebin.com ..."))
params = {"api_option": "p... |
#!/usr/bin/env python3
import calendar
if __name__ == "__main__":
for num in range(1, 13):
month = calendar.month_ | name[num]
| print(f"{num:02} - {month}")
|
import theano
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn import cross_validation, metrics, datasets
from neupy import algorithms, layers, environment
environment.reproducible()
theano.config.floatX = 'float32'
mnist = datasets.fetch_mldata('MNIST original')
target_scaler = OneHo... | la | yers.Relu(500),
layers.Softmax(300),
layers.ArgmaxOutput(10),
],
error='categorical_crossentropy',
step=0.01,
verbose=True,
shuffle_data=True,
momentum=0.99,
nesterov=True,
)
network.train(x_train, y_train, x_test, y_test, epochs=20)
y_predicted = network.predict(x_test)
y... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
#
# L | icensed under the Apache L | icense, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on ... |
self.time_now.mjd - predictive_mjd > auto_max_age):
raise ValueError(INTERPOLATE_ERROR.format(auto_max_age))
def _refresh_table_as_needed(self, mjd):
"""Potentially update the IERS table in place depending on the requested
time values in ``mjd`` and the time span of the table.
... | systems.
The state itself is an IERS table, as an instance of one of the
`~astropy.utils.iers.IERS` classes. The default, the auto-updating
`~astropy.utils.iers.IERS_Auto` class, should suffice for most
purposes.
Examples
--------
To temporarily use the IERS-B file packaged with astropy:... | pen(iers.IERS_B_FILE)
>>> with iers.earth_orientation_table.set(iers_b):
... print(Time('2000-01-01').ut1.isot)
2000-01-01T00:00:00.355
To use the most recent IERS-A file for the whole session::
>>> iers_a = iers.IERS_A.open(iers.IERS_A_URL) # doctest: +SKIP
>>> iers.earth_orien... |
req + source_triple[-1]
norm_source_freq = float(source_triple_freq) / float(patterns_freq)
norm_target_freq = float(target_triple_freq) / float(patterns_freq)
norm_source_freqs.append(norm_source_freq)
norm_target_freqs.append(norm_target_freq)
triples.append... | s = filter(lambda tr: not self.is_light_triple(tr), target_triples)
print "\tAFTER IGNORING LIGHT TRIPLES: %d" % len(target_triples)
source_triples, source_triple_num = self.find_triples_by_patterns(target_term_id, target_triples)
print "\tFOUND SOURCE TRIPLES FOR %s: %d" % (term, source_triple_... | if source_term_id in self.stop_terms:
stops_ignored += 1
continue
if target_term_id in self.concept_net and source_term_id in self.concept_net[target_term_id]:
cnect_ignored += 1
continue
if source_term_id in self.concep... |
# Copyright (c) 2012 Intel
# Copyright (c) 2012 OpenStack, LLC.
# Copyright (c) 2015 EMC Corporation
#
# 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
#
# ... | oned_ratio": provisioned_ratio,
"oversub_ratio": host_state.max_over_subscription_ratio,
"host": host_state.host})
return False
else:
# NOTE(xyang): Adjust free_virtual calculation based on
# free and max_over_subscrip... | free * host_state.max_over_subscription_ratio)
return adjusted_free_virtual >= share_size
elif host_state.thin_provisioning_support:
LOG.error(_LE("Invalid max_over_subscription_ratio: %(ratio)s. "
"Valid value should be >= 1."),
... |
"""
altgraph.ObjectGraph - Graph of objects with an identifier
==========================================================
A graph of objects that have a "graphident" attribute.
graphident is the key for the object in the graph
"""
from __future__ import print_function
from __future__ import absolute_import
from altgr... | (self, node):
"""
Get the identifier for a node obje | ct
"""
if node is self:
return node
ident = getattr(node, 'graphident', None)
return ident
def __contains__(self, node):
return self.findNode(node) is not None
def findNode(self, node):
"""
Find the node on the graph
"""
ident... |
"""Base test suite for extension arrays.
These tests are intended for third-party libraries to subclass to validate
that their extension arrays and dtypes satisfy the interface. Moving or
renami | ng the tests | should not be done lightly.
Libraries are expected to implement a few pytest fixtures to provide data
for the tests. The fixtures may be located in either
* The same module as your test class.
* A ``conftest.py`` in the same directory as your test class.
The full list of fixtures may be found in the ``conftest.py`` ... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 BarraDev Consulting (<http://www.barradev.com>).
#
# This program is free software: you can redistribute it and/or modify
# it ... | U Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licen | ses/>.
#
##############################################################################
from . import http_session_redis
|
# fallback if the requested version is 2 and there is no
# 'volumev2' endpoint.
if api_version['version'] == 2:
try:
cinder_url = base.url_for(request, 'volumev2')
except exceptions.ServiceCatalogException:
LOG.warning("Cinder v2 requested but... | e:
return []
return [Volume(v) for v in c_client.volumes.list(search_opts=search_opts)]
def volume_get(request, volume_id):
volume_data = cinderclient(request).volumes.get(volume_id)
for attachment in volu | me_data.attachments:
if "server_id" in attachment:
instance = nova.server_get(request, attachment['server_id'])
attachment['instance_name'] = instance.name
else:
# Nova volume can occasionally send back error'd attachments
# the lack a server_id property; ... |
ght = ssd_config.negative_class_weight
anchor_generator = anchor_generator_builder.build(
ssd_config.anchor_generator)
if feature_extractor.is_keras_model:
ssd_box_predictor = box_predictor_builder.build_keras(
conv_hyperparams_fn=hyperparams_builder.KerasLayerHyperparams,
freeze_batchnorm... | his model is being | built for training purposes.
add_summaries: Whether to add tf summaries in the model.
Returns:
FasterRCNNMetaArch based on the config.
Raises:
ValueError: If frcnn_config.type is not recognized (i.e. not registered in
model_class_map).
"""
num_classes = frcnn_config.num_classes
image_resiz... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | se this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIE... | ither express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.contrib import messages
from django import shortcuts
import openstackx
import openstack
class User(object):
def __init__(self, token=None, user=None, tenant_id=None, ... |
e'] for o in orders]
existing_order_ids = sale_obj.search(cr, uid, [('name', 'in', submitted_references)], context = context)
existing_orders = sale_obj.read(cr, uid, existing_order_ids, ['name'], context=context)
existing_references = set([o['name'] for o in existing_orders])
orders_to_... | if not delivery_code or not partner_ref:
syncerr = u"店铺【%s】订单【%s】物流发货同步错误: 对应的发货单没有运单号,或者没有快递方式,或者快递方式的快递公司(Partner)没有填写’物流公司代码‘(Ref字段)!" % (shop.name, order.name)
self.pool.get('ebiz.syncerr').create(cr, uid, {'name':syncerr, 'shop_id': shop.id, 'type': 'delivery', 'state': 'd | raft' }, context = context )
continue
#tid 格式为 店铺前缀_电商订单编号,如果是合并订单,则格式为 店铺前缀mg_流水号
i = order.name.find('_')
if i <= 0: continue
tid = order.name[i+1:]
if order.name[:i].endswith('mg'): #处理合并订单
if not order.orig... |
"""JSON implementation of pystorm serializer"""
from __future__ import absolute_import, print_function, unicode_literals
import io
import logging
import simplejson as json
from six import PY2
from ..exceptions import StormWentAwayError
from .serializer import Serializer
log = logging.getLogger(__name__)
class J... | else:
return io.open(stream.fileno(), mode=stream.mode, encoding="utf-8")
def read_message(self):
"""The Storm multilang protocol consists of JSON messages followed by
a newline and "end\n".
All of Storm's messages (for either bolts or spouts) should be of the
for... | 537413359385", "comp": "1", "stream": "1", "task": 9, "tuple": ["snow white and the seven dwarfs", "field2", 3]}\\nend\\n'
Command example for a spout to emit its next Tuple::
'{"command": "next"}\\nend\\n'
Example, the task IDs a prior emit was sent to::
'[12, 22, 24]\\nend... |
import tempf | ile
import shutil
import sys
from unittest impor | t mock
import pytest
from tools.wpt import run
from tools import localpaths # noqa: F401
from wptrunner.browsers import product_list
@pytest.fixture(scope="module")
def venv():
from tools.wpt import virtualenv
class Virtualenv(virtualenv.Virtualenv):
def __init__(self):
self.path = tem... |
import logging
import sqlite3
from pyfcm import FCMNotification
def insert_token(token):
try:
con = sqlite3.connect('fcm.db')
cur = con.cursor()
cur.execute('CREATE TABLE I | F NOT EXISTS tokens(token TEXT)')
cur.execute('INSERT INTO tokens VALUES (?)', (token, ))
con.commit()
finally:
if cur:
cur.close()
if con:
con.close | ()
def notify_all(message_title=None, message_body=None):
con = sqlite3.connect('fcm.db')
con.row_factory = lambda cursor, row: row[0]
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS tokens(token TEXT)')
cur.execute('SELECT * FROM tokens')
registration_ids = [row for row in cur.fe... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasi | ng children from poverty in Jesus' name
# @author: David Coninckx <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from . i | mport contracts
from . import project_compassion
from . import ir_ui_menu
|
# Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Dunya
#
# Dunya 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 (FSF), either version 3 of the License, or... | (), name='api-andalusian-instrument-detail'),
url(r'^tab$', andalus | ian.api.TabList.as_view(), name='api-andalusian-tab-list'),
url(r'^tab/%s$' % uuid_match, andalusian.api.TabDetail.as_view(), name='api-andalusian-tab-detail'),
url(r'^mizan$', andalusian.api.MizanList.as_view(), name='api-andalusian-mizan-list'),
url(r'^mizan/%s$' % uuid_match, andalusian.api.MizanDetail.... |
import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | d by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multip | le font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where ... |
'''OpenGL extension OES.read_format
This module customises the behaviour of the
OpenGL.raw.GLES1.OES.read_format to provide a more
Python-friendly API
The official definition of | this extension is available here:
http://www.opengl.org/registry/specs/OES/read_format.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GLES1 import _types, _glgets
from OpenGL.raw.GLES1.OES.read_format import *
from OpenGL.raw.GLES1. | OES.read_format import _EXTENSION_NAME
def glInitReadFormatOES():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION |
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
from . import *
# Signals
from .signal import (Signal, EpicsSignal, EpicsSignalRO, DerivedSignal)
# Po | sitioners
from .positioner import (PositionerBase, SoftPositioner)
from .epics_motor import EpicsMotor
from .pv_positioner import (PVPositioner, PVPositionerPC)
from .pseudopos import (PseudoPositioner, PseudoSingle)
# Devices
from .scaler import EpicsScaler
from .device import (Device, Component, FormattedComponent,
... | micDeviceComponent)
from .status import StatusBase
from .mca import EpicsMCA, EpicsDXP
# Areadetector-related
from .areadetector import *
from ._version import get_versions
from .commands import (mov, movr, set_pos, wh_pos, set_lm, log_pos,
log_pos_diff, log_pos_mov)
from .utils.startup import... |
t(0,0,0,0)
# charger images
mur = pygame.image.load(SOURCE_IMG + 'mur.jpg').convert()
mur50 = pygame.image.load(SOURCE_IMG + 'mur50.jpg').convert()
caisse = pygame.image.load(SOURCE_IMG + 'caisse.jpg').convert()
caisse50 = pygame.image.load(SOURCE_IMG + 'caisse50.jpg').convert()
caisse_ok = pyg... | S_HAUTEUR):
if carte[i][j] ==MARIO:
alsoMario += 1
# white Bar
whiteBar = pygame.Surface((screen.get_width(), 60), screen.get_flags())
whiteBar | .fill(WHITE)
# police
police = pygame.font.Font('angelina.ttf', 20)
# define sourceFile default
pathFile = printLang(lang) # 'fr' ou 'en'
sourceFile = SOURCE_FILE + pathFile + '/edit.lvl' # './files/'fr' ou 'en'/edit.lvl'
# H: Help Level: Saved ESC: Exit ou H: Ai... |
# -*- coding: utf-8 -*-
from distu | tils.core import setup
setup(
name='popy',
description='Parser for GNU Po files',
long_description=open('README.rst').read(),
version='0.3.0',
| packages=['popy'],
author='Murat Aydos',
author_email='murataydos@yandex.com',
url='https://github.com/murataydos/popy',
license='MIT',
zip_safe=False,
include_package_data=True
)
|
#!/usr/bin/env python
import jumeg
import os.path
raw_fname = "109925_CAU01A_100715_0842_2_c,rfDC-raw.fif"
if not os.path.isfile(raw_fname):
print "Please find the test file at the below location on the meg_store2 network drive - \
cp /data/meg_store2/fif_data/jumeg_test_data/109925_CAU01A_100715_0842_... | = ocarta.JuMEG_ocarta()
ocarta_obj.fit(fclean, unfiltered=False, verbose=True)
# CTPS functions
#jumeg.jumeg_preprocessing.apply_ctps(fica_nam | e)
fctps_name = '109925_CAU01A_100715_0842_2_c,rfDC,bp1-45Hz,ctps-trigger.npy'
#jumeg.jumeg_preprocessing.apply_ctps_select_ic(fctps_name)
# Function recompose brain response components only
fname_ctps_ics = '109925_CAU01A_100715_0842_2_c,rfDC,bp1-45Hz,ctps-trigger-ic_selection.txt'
#jumeg.jumeg_preprocessing.apply_ic... |
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView
from .mixins import GenerateActionMixin
class DetailViewWithActionStream(GenerateActionMixin, DetailView):
def dispatch(self, request, *args, **kwargs):
if not self.request.user.is_anonymous... | id(self, form):
to_return = super(UpdateViewWithActionStream, self).form_valid(form)
if not self.request.user.is_anonymous():
self.generate_action()
return to_return
def get_action_actor(self, *args, **kwargs):
return self.request.user
def get_action_verb(self, * | args, **kwargs):
return 'updated'
def get_action_action_object(self, *args, **kwargs):
return self.get_object() |
def get_duplicates(self, ids, tolerance, fast=False):
dupes_dict = {}
dupes_list = []
values = {}
for i in ids:
values[i] = self.value(i)
selection = self.ids_sorted(ids)
print('Searching duplicates in %d structures' % len(selection))
for i in range(... | ry_id in dupes_dict:
dupes_dict[entry_id].append(entry_jd)
else:
dupes_dict[entry_id] = [entry_jd]
| dupes_list.append(entry_jd)
return dupes_dict, [x for x in selection if x in dupes_list]
def cleaned_from_duplicates(self, ids):
selection = self.ids_sorted(ids)
duplicates_dict = self.check_duplicates(selection)
return [x for x in selection if x not in duplicates... |
#!/usr/bin/python
# openvpn.py: library to handle starting and stopping openvpn instances
import subprocess
import threading
import time
class OpenVPN():
def __init__(self, config_file=None, auth_file=None, timeout=10):
self.started = False
self.stopped = False
self.error = False
... | line = self.process.stdout.readline().strip()
if not line:
break
self.output_callback(line, self.process.terminate)
def output_callback(self, line, kill_switch):
"""Set status of openvpn according to what we process"""
self.notifications += line + "\... | e
if "process exiting" in line:
self.stopped = True
def start(self, timeout=None):
"""Start openvpn and block until the connection is opened or there is
an error
"""
if not timeout:
timeout = self.timeout
self.thread.start()
start_tim... |
#!/usr/bin/python
from __fu | ture__ import absolute_import
from __future__ import print_function
import sys
if l | en(sys.argv) != 3:
sys.stderr.write("Usage: %s 'Host Name' 'Service Description'\n" % (sys.argv[0]))
sys.exit(2)
## This is for the custom nagios module
sys.path.insert(1, '../')
from pynag.Parsers import config
## Create the plugin option
nc = config('/etc/nagios/nagios.cfg')
nc.parse()
service = nc.get_... |
while True:
if self.evt_stop.is_set():
break
self.evt_enabled.wait()
if not self.sync.tunnel:
break
if | self.sync.tunnel.is_up():
self.poll()
time.sleep(TIMER_PERIOD)
def poll(self):
msg = self.sync.tunnel.po | ll()
if msg:
batch = [cmd.strip() for cmd in msg.split('\n') if cmd]
if batch:
gdb.post_event(Runner(batch))
else:
gdb.post_event(Runner(['syncoff']))
self.stop()
def enable(self):
self.evt_enabled.set()
def disable(self):... |
i | mport time
def start():
ret | urn time.time()
|
# Copyright 2012 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 ... | rs': errors,
'serialized_un | its': serialized_units,
'serialized_units_json': transforms.dumps(serialized_units),
'stats_calculated': stats_calculated,
'update_message': update_message,
}, autoescape=True))
|
ce position in kpc
xyz3 = xyz + dxyz
# back to the lab, deg
(ra3,dec3) = xyztoradec(xyz3)
# adjusted angular displacement, deg
dra = ra3 - ra
# tedious RA wrapping
dra += 360. * (dra < -180)
dra -= 360. * (dra > 180)
# convert back to proper motions
return ((dra * cos(deg2rad(de... | (dec >= 0) and 1. or -1.
d = dec * sgn
dd = int(floor(d))
m = (d - dd) * 60.
mm = int(floor(m))
s = (m - mm) * 60.
if s >= 60.:
| m += 1.
s -= 60.
# don't just return sgn*d because values between 0 and 1 deg will get you!
return (sgn, d, m, s)
# RA in degrees
def ra2hmsstring(ra, separator=' ', sec_digits=3):
(h,m,s) = ra2hms(ra)
#print 'hms', h,m,s
ss = int(floor(s))
#ds = int(round((s - ss) * 1000.0))
... |
"""
A "mirroring" ``stdout`` context manager.
While active, the context manager reverses text output to
``stdout``::
# BEGIN MIRROR_GEN_DEMO_1
>>> from mirror_gen import looking_glass
>>> with looking_glass() as what: # <1>
... print('Alice, Kitty and Snowdrop')
... print(what)
... |
"""
# BEGIN MIRROR_GEN_EX
import contextlib
@contextlib.con | textmanager # <1>
def looking_glass():
import sys
original_write = sys.stdout.write # <2>
def reverse_write(text): # <3>
original_write(text[::-1])
sys.stdout.write = reverse_write # <4>
yield 'JABBERWOCKY' # <5>
sys.stdout.write = original_write # <6>
# END MIRROR... |
import numpy as np
import pytest
from pandas._libs.tslib import iNaT
from pandas.core.dtypes.dtypes import PeriodDtype
import pandas as pd
from pandas.core.arrays import PeriodArray
from pandas.tests.extension import base
@pytest.fixture
def dtype():
return PeriodDtype(freq='D')
@pytest.fixture
def data(dtyp... | iodArray([2018, iNaT, 2017], freq=dtype.freq)
@pytest.fixture
def data_for_grouping(dtype):
B = 2018
NA = iNaT
A = 2017
C = 2019
return P | eriodArray([B, B, NA, NA, A, A, B, C], freq=dtype.freq)
@pytest.fixture
def na_value():
return pd.NaT
class BasePeriodTests(object):
pass
class TestPeriodDtype(BasePeriodTests, base.BaseDtypeTests):
pass
class TestConstructors(BasePeriodTests, base.BaseConstructorsTests):
pass
class TestGetite... |
# Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | testHost',
"adminPass": "MySecretPass",
"onSharedStorage": 'False'
}
self._test_evacuate(req_subs, 'server-evacuate-req',
'server-evacuate-resp', 202)
rebuild_mock.assert_called_once_with(mock.ANY, instance=mock.ANY,
orig_ | image_ref=mock.ANY, image_ref=mock.ANY,
injected_files=mock.ANY, new_pass="MySecretPass",
orig_sys_metadata=mock.ANY, bdms=mock.ANY, recreate=mock.ANY,
on_shared_storage=False, preserve_ephemeral=mock.ANY,
host='testHost')
@mock.patch('nova.conductor.... |
#!/usr/bin/python2.7
#
# This file is part of drizzle-ci
#
# Copyright (c) 2013 Sharan Kumar M
#
# drizzle-ci 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
... | o('\n\t\t==================================================')
log.i | nfo('\t\tstate minion status ')
log.info('\t\t==================================================')
for state in opt['state']:
top_data = top_file.format(state)
with open(path['state']+'/top.sls', 'w') as top_sls:
top_sls.write(top_data)
for minion in opt['minion']... |
import curses
import functools
from stem.control import EventType, Controller
from stem.util import str_tools
# colors that curses can handle
COLOR_LIST = {
"red": curses.COLOR_RED,
"green": curses.COLOR_GREEN,
"yellow": curses.COLOR_YELLOW,
"blue": curses.COLOR_BLUE,
"cyan": curses.COLOR_CYAN,
"magenta"... | abel = "Downloaded (%s/s):" % str_tools.size_label(download_rates[0], 1)
window.addstr(0, 1, label, DOWNLOAD_COLOR, curses.A_BOLD)
label = "Uploaded (%s/s):" % str_tools.size_label(upload_rates[0], 1)
window.addstr(0, GRAPH_WIDTH + 7, label, UPLOAD_COLOR, curses.A_BOLD)
# draw the graph bounds in KB
max_do... | % (max_download_rate / 1024), DOWNLOAD_COLOR)
window.addstr(GRAPH_HEIGHT, 1, " 0", DOWNLOAD_COLOR)
window.addstr(1, GRAPH_WIDTH + 7, "%4i" % (max_upload_rate / 1024), UPLOAD_COLOR)
window.addstr(GRAPH_HEIGHT, GRAPH_WIDTH + 7, " 0", UPLOAD_COLOR)
# draw the graph
for col in range(GRAPH_WIDTH):
col_... |
#/u/GoldenSights
import praw
import time
import datetime
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/
USERAGENT = ""
#This is a short description of what the bot does. For example "/u/GoldenS... | is time.
DELAY = 86400
#This is the time, IN SECONDS, which the post will hold the active flair
IGNOREMODS = False
#Do you want the bot to ignore posts made by moderators? Use True or False (With capitals! No quotations!)
IGNORESELFPOST = False
#Do you want the bot to ignore selfposts?
IGNORELINK = True
# | Do you want the bot to ignore linkposts?
FLAIRACTIVE = "Active"
CSSACTIVE = "active"
#The flair text and css class assigned to unsolved posts.
TITLEREQS = ['[',']']
#Every part of this list must be included in the title
'''All done!'''
WAITS = str(WAIT)
try:
import bot
USERAGENT = bot.getaG()
except ImportErro... |
r/bin/env python
# -*- coding: ascii -*-
r"""
LazGUI helps to create Lazarus Pascal GUI project.
LazGUI will place all of the required files for the Lazarus project
into a subdirectory by project name. The project can be built using "lazbuild"
that comes with a Lazarus install, or by opening the <project_name>.lpi f... | targ_fname = os.path.join( targ_abs_path, '%s.res'%self.project_name )
print 'Copying',src_fname,' --> ',targ_fname
shutil.copy(src_fname, targ_fname)
# Create Icon
src_fname = os.path.join( ref_proj_files, 'project1.ico' )
targ_fname = os.path.join( targ_abs_path, '... | |
# -*- coding: utf-8 -*-
import re
from pyload.plugin.Account import Account
class StahnuTo(Account):
__name = "StahnuTo"
__type = "account"
__version = "0.05"
__description = """StahnuTo account plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail | .cz")]
def loadAccountInfo(self, user, req):
html = req.load("http://www.stahnu.to/")
m = re.search(r'>VIP: (\d+.*)<', html)
trafficleft = self.parseTraffic(m.group(1)) if m else 0
return {"premium": trafficleft > 512, "trafficleft": trafficleft, "validuntil": -1}
def login... | word'],
"submit": "Login"},
decode=True)
if not '<a href="logout.php">' in html:
self.wrongPassword()
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
images = np.concatenate(
[
self.tf_sess.run(sres_op, feed_dict={
input_op: | lores[x:x + batch], **(feed_extra or {})})
for x in range(0, lores.shape[0], batch)
], axis=0)
images = images.clip(-1, 1)
images = np.concatenate([hires, pixelated, images], axis=3)
images = utils.images_to_grid(images.reshape((height, width) + images.shape[1:]))
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Simple agent which chooses a random label.
Chooses from the label candidates if they are available. If candidates ar... | et('label_candidates_file'))
self.label_candidates = f.read().split('\n')
def act(self):
"""
Generate response to last seen observation.
Replies with a randomly selected candidate if label_candidates or a
candidate file are available.
Otherwise, repl | ies with the label if they are available.
Oterhwise, replies with generic hardcoded responses if the agent has
not observed any messages or if there are no replies to suggest.
:returns: message dict with reply
"""
obs = self.observation
if obs is None:
return... |
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import redirect
from main.models import Link
from main.models import Tag
# Create your views here.
def index(request):
context = RequestContext(request)
... | ':links, 'tag_name': '#' + tag_name}, context)
def add_link(req | uest):
context = RequestContext(request)
if request.method == 'POST':
url = request.POST.get("url","")
tags = request.POST.get("tags","")
title = request.POST.get("title","")
tags = tags.split(',')
l = Link.objects.get_or_create(title=title, url=url)[0]
fo... |
"""
Written by Harry Liu (yliu17) and Tyler Nickerson (tjnickerson)
"""
import sys
import os.path
import pprint
from classes.bag import Bag
from classes.item import Item
from classes.constraint import Constraint
from classes.csp import CSP
from classes.solver import Solver
def main():
# Read command line argument... | # Items
items = {}
# Section tracker
current_section = 0
# Read each lin | e and add to the examples and output lists
if os.path.isfile(inputfilename):
with open(inputfilename, "r") as infile:
for line in infile:
# If the line is a comment, increment the section counter
if line[:5].strip() == "#####":
... |
#!/usr/bin/env python
"""Dump instances for bunny, in Promela and SlugsIn."""
import argparse
import itertools
import pprint
import logging
import re
from tugs import utils
log = logging.getLogger(__name__)
INPUT_FILE = 'bunny.pml'
PROMELA_PATH = 'pml/bunny_many_goals_{i}.txt'
SLUGSIN_PATH = 'slugsin/bunny_many_goals... | promela_file = PROMELA_PATH.format(i=i)
with open(promela_file, 'r') as f:
pml_code = f.read()
slugsin_code = utils.translate_promela_to_slugsin(pml_code)
slugsin_file = SLUGSIN_PATH.format(i=i)
with open(slugsin_file, 'w') as f:
f | .write(slugsin_code)
log.info('dumped SlugsIn for {i} masters'.format(i=i))
def make_promela(n):
"""Return Promela code for instance with size `n`."""
fname = INPUT_FILE
with open(fname, 'r') as f:
s = f.read()
# set number of cells
newline = '#define H {n}'.format(n=n)
code = ... |
tr | y:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description':'End to end solution for bitcoin data gathering, backtesting, and live trading',
'author': 'ross palmer',
'url':'http://rosspalmer.github.io/bitQuant/',
'license':'MIT',
'version': '0.2.10',
'install_r... | |
# -*- encoding: utf-8 -*-
import os
import subprocess
def graph(
expr,
image_format='pdf',
layout='dot',
graph_attributes=None,
node_attributes=None,
edge_attributes=None,
**kwargs
):
r'''Graphs `expr` with graphviz and opens resulting image in
the default image viewer.
::... | t = str(graphviz_graph)
assert image_format in ('pdf', 'png')
valid_layouts = (
'circo',
'dot',
'fdp',
'neato',
'osag | e',
'sfdp',
'twopi',
)
assert layout in valid_layouts
message = 'cannot find `{}` command-line tool.'
message = message.format(layout)
message += ' Please download Graphviz from graphviz.org.'
assert systemtools.IOManager.find_executable(layout), message
ABJADOUTPUT = a... |
"""NDG XACML ElementTree based reader for subject match type
NERC DataGrid
"""
__author__ = "P J Kershaw"
__date__ = "16/03/10"
__copyright__ = "(C) 2010 Science and Technology Facilities Council"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "Phi... | ReaderBase):
"""ElementTree based parser for XACML SubjectMatch
@cvar TYPE: XACM | L class type that this reader will read values into
@type TYPE: abc.ABCMeta
@cvar ATTRIBUTE_DESIGNATOR_TYPE: type for attribute designator sub-elements
@type ATTRIBUTE_DESIGNATOR_TYPE: abc.ABCMeta
"""
TYPE = SubjectMatch
ATTRIBUTE_DESIGNATOR_TYPE = SubjectAttributeDesignator |
self.assertTrue(zone.domain.startswith('auroradns'))
def test_create_zone(self):
zone = self.driver.create_zone('example.com')
self.assertEqual(zone.domain, 'example.com')
def test_get_zone(self):
zone = self.driver.get_zone('example.com')
self.assertEqual(zone.domain, 'ex... | e_health_check(self):
zone = self.dri | ver.get_zone('example.com')
type = AuroraDNSHealthCheckType.HTTP
hostname = "www.pcextreme.nl"
ipaddress = "109.72.87.252"
port = 8080
interval = 10
threshold = 3
check = self.driver.ex_create_healthcheck(zone=zone,
... |
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.utils import translation
import pytest
from shoop.front.apps.si... | tories import get_default_product, get_default_shop, create_product
from shoop.testing.utils import appl | y_request_middleware
UNLIKELY_STRING = "TJiCrQWaGChYNathovfViXPWO"
NO_RESULTS_FOUND_STRING = "No results found"
@pytest.mark.django_db
def test_simple_search_get_ids_works(rf):
prod = get_default_product()
bit = prod.name[:5]
request = rf.get("/")
assert prod.pk in get_search_product_ids(request, bit... |
import sys
import numpy
import math
from foldyFloatList import foldyFloatList
class OOBError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
from KMCLib.PluginInterfaces.KMCAnalysisPlugin import KMCAnalysisPlugin
from KMCLib.Utilities.CheckU... | self.__histogram[self.__currTot].addValue(self.__currentTime | - self.__lastTime)
self.__lastTime = time
def finalize(self):
self.__lastTime = self.__currentTime
self.__finalHist = []
totalWeight = foldyFloatList()
for data in self.__histogram:
temp = data.extractSum()
totalWeight.addValue(temp)
self... |
lic License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICU... | the module's file path
module_p | ath = ctypes.create_unicode_buffer(255)
windll.kernel32.GetModuleFileNameW(h_module_base, module_path, 255)
# then the ImageBase from python.exe file
pe = pefile.PE(module_path.value)
pe_header_base_addr = pe.OPTIONAL_HEADER.ImageBase
offsets.append(pe_header_base_addr - h_m... |
import unittest
import transaction
from pyramid import testing
from .models import DBSession
class TestMyViewSuccessCondition(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
from sqlalchemy import create_engine
engine = create_engine('sqlite://')
from .models i... | engine = create_engine('sqlite://')
from .models import (
Base,
MyModel,
)
DBSession.configure(bind=engine)
def tearDown(self):
DBSession.remove()
testing.tearDown()
def test_failing_view(self):
from .views import my_view
... | quest()
info = my_view(request)
self.assertEqual(info.status_int, 500) |
import pytest
import re
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from shuup.core.models import SavedAddress
from shuup.core.models import get_person_contact
from shuup.core.models._contacts import get_company_contact
from shu... | se.status_code == 302
assert " | Cannot remove address" not in soup
user = User.objects.create_user('john', 'doe@example.com', 'doepassword')
contact2 = get_person_contact(user)
address2 = get_address()
address2.save()
sa2 = SavedAddress.objects.create(owner=contact2, address=address2)
response, soup = client.response_and_sou... |
format_testing_audio = "audio_pipeline\\test\\test_files\\audio\\tag_test_files"
write_testing_audio = "audio_pipeline\\test\\test_files\\audio\\write_test_files"
release_mbids = "audio_pipeline/test/test_files/test_mbids/release_mbids.json"
artist_mbids = "audio_pipeline/test/test_files/test_mbids/artist_mbids.json"
m... | rate (confidence 62) [37DEB629]',
'artist': 'The Zutons', 'tracknumber': 4, 'disctotal': 1,
'genre': 'Rock', 'mbid': '5560ffa9-3824-44f4-b2bf-a96ae4864187', 'length': '0:07',
'item_code': '8b3b7f33-4e8c-4146-90b7-96611863d133', 'obscenity': 'RED DOT',
'send to enco': 'yes'... | altracks': 13, 'encoded by': 'dBpoweramp Release 14.4',
'media': 'CD', 'source': 'CD (Lossless)', 'releasestatus': 'official',
'script': 'Latn', 'accurateripresult': 'AccurateRip: Not in database 7CF59426',
'musicbrainz_trackid': '89715e73-cfa8-487f-8aa1-18c3b7d965b9', 'releaseco... |
import numpy as np
import pandas as pd
from ElectionsTools.Seats_assignation import DHondt_assignation
from previous_elections_spain_parser import *
import os
pathfiles = '../data/spain_previous_elections_results/provincia/'
pathfiles = '/'.join(os.path.realpath(__file__).split('/')[:-1]+[pathfiles])
fles = [pathfil... | turn d, d1, d2, parties
def prepare2export(d, d1, d2, parties):
logi = np.logical | _or(np.logical_or(d.sum(0)>0, d1.sum(0)>0), d2.sum(0)>0)
parties = [parties[i] for i in np.where(logi)[0]]
d, d1, d2 = d[:, logi].sum(0), d1[:, logi].sum(0), d2[:, logi].sum(0)
return d, d1, d2, parties
def compute_all_year(year):
filename = fles[years.index(year)]
d, d1, d2, parties = compute_dipu... |
#!/usr/bin/env python3
# this copies over all files in admin0:~/stripe/ to the ~/stripe folder in the statistics project
import sys
import | os
s | ys.path.insert(0, os.path.expanduser("~/bin/"))
os.chdir(os.path.join(os.environ['SMC_ROOT'], "smc-build/smc-ansible"))
# host of statistics project
from smc_rethinkdb import project_host
host = project_host("7561f68d-3d97-4530-b97e-68af2fb4ed13")
src = os.path.expanduser("~/stripe/")
# push to the project via ansib... |
# Functions and Variables
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers direct... | d_crackers(amount_of_cheese, amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + | 1000) |
import unittest
from katas.beta.number_to_bytes import to_bytes
class NumberToBytesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_bytes(0), ['00000000'])
def test_equals_2(self):
self.assertEqual(to_bytes(1), ['00000001'])
def test_equals_3(self):
| self.assertEqual(to_bytes(257), ['00000001', '00000001'])
def test_equals_4(self):
self.assertEqual(to_bytes(0x101), ['00000001', '00000001'])
def test_equals_ | 5(self):
self.assertEqual(to_bytes(0x000000000101), ['00000001', '00000001'])
def test_equals_6(self):
self.assertEqual(to_bytes(0xffff), ['11111111', '11111111'])
def test_equals_7(self):
self.assertEqual(to_bytes(0x1020304),
['00000001', '00000010', '00000011... |
# -*- coding: utf-8 -*-
from app import cre | ate_app
forms_app = create_app()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.