prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
"""
Copyrigh | t (C) <2010> Autin L. TSRI
This file git_upy/blender/v271/__init__.py is part of upy.
upy 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... | ITHOUT 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 upy. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>.... |
"""
Django settings for paypal_demo project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pa... | SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'paypal_demo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoT... | {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | et = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
| chart.axis_ids = [45705856, 45740416]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.ad... |
f.data['labels'])
self.label_config = self._label_config_to_df(self.config)
# Combine the labels data with the labels configuration
self.data['labels'] = self._merge_labels_and_config(
labels=self.data['labels'],
config=self.label_config)
def bin_data(self):
... | ist)
@staticmethod
def _clean_labels(labels):
"""
Turn the Biopac flag channel into a data frame of label flags and start
times.
"""
# TODO(janmtl): finish this docstring
flags = labels['flag'].values
low_offset = np.append(-255, flags)
high_offse... |
labels = pd.DataFrame({'flag': event_flags,
'Start_Time': start_times})
labels = labels[(labels['flag'] != 255)]
return labels
@staticmethod
def _clean_samples(samples):
"""
.
"""
scale = 0.55
samples.index = sa... |
#!/usr/bin/env python
from setuptools import setup
setup(
name='nodenet',
version='0.1.0',
description='an asynchronous node-based UDP networking library',
author='Ajay MT',
author_email='ajaymt@icloud.com',
url='http://github.com/AjayMT/nodenet',
download_url='https://github.com/AjayMT/no... | 'nodenet'],
requires=[
'pyuv (>1.0.0, <2.0.0)',
'emitter (>=0.0.6)'
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Py... | e :: Python :: 2',
]
)
|
#!/usr/b | in/env python
class RoundFloatManual(object):
def __init__(self, val):
assert isinstance(val, float), \
"Value must be a float!"
self.value = round(val, 2)
def __str__(self):
return '%.2f' % self.value
__repr__ = __str__ | |
# | !/usr/bin/env python
import turtle
import random
def bloom(radius):
turtle.colormode(255)
for rad in range(40, 10, -5):
for looper in range(360//rad):
turtle.up()
turtle.circle(radius+rad, rad)
turtle.begin_fill()
turtle.fillcolor((200+random.randint(0, ... | , rad),
200+random.randint(0, rad)))
turtle.down()
turtle.circle(-rad)
turtle.end_fill()
def main():
"""Simple flower, using global turtle instance"""
turtle.speed(0)
turtle.colormode(1.0)
bloom(5)
turtle.exitonclick()
###
if __na... |
#!/usr/bin/env python
# ======================================================================
# Copyright (C) 2007-2014 Giampaolo Rodola' <g.rodola@gmail.com>
#
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and assoc... | f._norma | l = unicode(curses.tigetstr("sgr0"), "ascii")
def format(self, record):
try:
record.message = record.getMessage()
except Exception:
err = sys.exc_info()[1]
record.message = "Bad message (%r): %r" % (err, record.__dict__)
record.asctime = time.strftime(TI... |
on import GridSearchCV
from grass.pygrass import raster as r
from grass.pygrass.utils import getenv
import grass.script as gs
from cStringIO import StringIO
from subprocess import PIPE
from io import BytesIO
from itertools import combinations
def setParamDict():
params = {}
for p in ['learning_rate', 'max_... | trip('.pdf') + '_twoway | .pdf')
# #############################################################################
# Predict data outside trainifrom subprocess import PIPEng areas
writeMap(output, coor_predict[:,0], coor_predict[:,1], clf.predict(predict))
# Write train error map
writeMap(output + '_train_error', coor_train[:,0], coor_train[:,1... |
from gittle import Gittle
repo = Gittle('.')
laste | st = [
info['sha']
for info in repo.commit_info()[1:3]
]
print(repo.diff(*lastest, diff_type='cl | assic'))
print("""
Last Diff
""")
print(list(repo.diff('HEAD')))
|
##########################################################################
#
# Copyright (c) 2012-2014, John Haddon. All rights reserved.
# Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | OptionsTest
from CopyOptionsTest import CopyOptionsTest
from SceneNodeTest import SceneNodeTest
from PathMatcherTest import PathMatcherTest
from PathFilterTest import PathFilterTest
from ShaderAssignmentTest import ShaderAssignmentTest
from CustomAttri | butesTest import CustomAttributesTest
from AlembicSourceTest import AlembicSourceTest
from DeletePrimitiveVariablesTest import DeletePrimitiveVariablesTest
from SeedsTest import SeedsTest
from SceneContextVariablesTest import SceneContextVariablesTest
from SubTreeTest import SubTreeTest
from OpenGLAttributesTest import... |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | s = ['user', 'password', "auth"]
def checkConfig(self, serverUrl, user=None, password=None, auth=None, format_fn=None, **kwargs):
if user is not None and auth is not None:
config.error("Only one of user/password or auth must be given")
if user is not None:
config.warnDepreca... | s not None) and not callable(format_fn):
config.error("format_fn must be a function")
HttpStatusPushBase.checkConfig(self, **kwargs)
@defer.inlineCallbacks
def reconfigService(self, serverUrl, user=None, password=None, auth=None, format_fn=None, **kwargs):
yield HttpStatusPushBase.r... |
# -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansTamil-Regular'
native_name = ''
def glyphs(self):
chars = []
chars.append(0x0000) #uni0000 ????
chars.append(0x200B) #uniFEFF ZERO WIDTH SPACE
chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER
... | (0x0BD0) #uni0BD0 TAMIL OM
chars.append(0x0BD7) #uni0BD7 TAMIL AU LENGTH MARK
chars.append(0x0BE6) #uni0BE6 TAMIL DIGIT ZERO
chars.append(0x0BE7) #uni0BE7 TAMIL DIGIT ONE
chars.append(0x0BE8) #uni0BE8 TAMIL DIGIT TWO
chars.append(0x0BE9) #uni0BE9 TAMIL | DIGIT THREE
chars.append(0x0BEA) #uni0BEA TAMIL DIGIT FOUR
chars.append(0x0BEB) #uni0BEB TAMIL DIGIT FIVE
chars.append(0x0BEC) #uni0BEC TAMIL DIGIT SIX
chars.append(0x0BED) #uni0BED TAMIL DIGIT SEVEN
chars.append(0x0BEE) #uni0BEE TAMIL DIGIT EIGHT
chars.append(0x0BEF... |
from nbodykit.base.catalog import CatalogSource
from nbodykit.io.stack import FileStack
from nbodykit import CurrentMPIComm
from nbodykit import io
from nbodykit.extern import docrep
from six import string_types
import textwrap
import os
__all__ = ['FileCatalogFactory', 'FileCatalogBase',
'CSVCatalog', 'Bi... | .fget(self)
return list(self._source.dtype.names) + defaults
def get_hardcolumn(self, col):
"""
Return a column from the underlying file source.
Columns are returned as dask arrays.
"""
if col in self._source.dtype.names:
return self._source.get_dask(col... | se:
return CatalogSource.get_hardcolumn(self, col)
def _make_docstring(filetype, examples):
"""
Internal function to generate the doc strings for the built-in
CatalogSource objects that rely on :mod:`nbodykit.io` classes
to read data from disk.
"""
qualname = '%s.%s' %(filetype.__... |
import unittest
from algoliasearch.configs import InsightsConfig
from algoliasearch.exceptions import AlgoliaException
from algoliasearch.insights_client import InsightsClient
class TestInsightsClient(unittest.TestCase):
def test_create(self):
client = InsightsClient.create("foo", "bar")
self.as... | f):
client = InsightsClient.create("foo", "bar")
self.assertEqual(client._config._region | , "us")
client = InsightsClient.create("foo", "bar", "fr")
self.assertEqual(client._config._region, "fr")
|
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
# See Core.Logic.FJudgementContext for the infor | mation
# of the 'context' parameter.
# This sample judging object does the following:
#
# JudgeBaseline: just verifies that the standard steps did not crash.
# JudgeSuperior: also verifies that the validation steps are not in error.
# JudgeExemplary: same as intermediate badge.
# We import an assistant scrip... |
from django.conf.urls import include, | url
from article import views
urlpatterns = [
url(r'^$', views.articles, name='articles'),
url(r'^add/?$', views.add_articles, name='ad | d-articles'),
] |
from fabric.api imp | ort *
from fabric.decorators import task
import os, sys
sys.path[0:0] = [os.path.join(os.path.realpath('.'), '..'), ]
try:
from d51.django.virtualenv.test_runner import run_tests
except ImportError, e:
import sys
sys.stderr.write("This project requires d51.django.virtualenv.test_runner\n")
| sys.exit(-1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IRC bot...
"""
import threading
import src.utilities as util
import src.settings
import src.irc.botObject
class BotDispatcher(threading.Thread):
" | ""
The BotDispatcher object handles the delegation of the various bots on
the various specified servers.
One Bot object for each server (call name), meaning several bots can be
connected to the same address.
All bots are stored in the botObjects class variable.
"""
botObj... | d fire off the dispatch method."""
super(BotDispatcher, self).__init__()
self.settingsInstance = src.settings.Settings()
self.dispatch()
def dispatch(self):
"""Create one Bot object for each server and start it in threads."""
servers = self.settingsInstance.settings[... |
import os
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
parser = argparse.ArgumentParser('ODE demo')
parser.add_argument('--method', type=str, choices=['dopri5', 'adams'], default='dopri5')
parser.add_argument('--data_size', type=int, default=1000)
parse... | eq import odeint
device = torch.device('cuda:' | + str(args.gpu) if torch.cuda.is_available() else 'cpu')
true_y0 = torch.tensor([[2., 0.]]).to(device)
t = torch.linspace(0., 25., args.data_size).to(device)
true_A = torch.tensor([[-0.1, 2.0], [-2.0, -0.1]]).to(device)
class Lambda(nn.Module):
def forward(self, t, y):
return torch.mm(y**3, true_A)
wi... |
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render
from .models impor | t Comment
from .forms import UpdateCommentForm
from django.http.response import JsonResponse
from django.views.decorators.http import require_http_methods
def update_comment(request, cid):
"""
TODO: This function has code duplication, clean it when you have time.
"""
comment = get_object_or_404(Commen... | ST, comment=comment)
if update_comment_form.is_valid():
update_comment_form.save()
return render(request, 'comments/comment.html', {
'comment': comment})
else:
update_comment_form = UpdateCommentForm(comment=comment)
return render(request, 'comments/update_form.ht... |
# -*- coding: UTF-8 -*-
# bp_v1
from .api_v1 import bp_v1
# b | p_v2
from .api_v2 | import bp_v2
__author__ = 'lpe234'
"""
Controller
"""
|
import logging
import re
from pathlib import Path
def find_by_name(path, name):
if type(path) is str:
path = Path(path)
for child in path.iterdir():
if child.name == name:
return child
elif child.is_dir():
ret = find_by_name(child, name)
if ret:
... | if all([filter_.check(child) for filter_ in filters]):
if child.is_dir():
files | += gen_file_list(child, filters, toplevel=False)
else:
files.append(child)
files = [file.relative_to(path) for file in files] if toplevel else files
for file in files:
if not all([filter_.check(file) for filter_ in filters]):
files.remove(file)
logging... |
from Bio import SeqIO
from Bio.Alphabet import IUPAC, ProteinAlphabet
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from optparse import OptionParser
def translate_to_six_frame(dnaRecord, translationTable):
'''
translate a Bio.SeqRecord of a DNA sequence via the given translation table in... | me:]
aaSeq = Seq(str(sequence.translate(translationTable)), alphabet = ProteinAlphabet)
aaRecord = SeqRecord(aaSeq, dnaRecord.name)
aaRecord.id = '%s_%s%i' % (aaRecord.id, direction[0], fra | me)
aaRecord.description = '%s|translation %s frame %i' % (aaRecord.description, direction, frame)
translations.append(aaRecord)
return translations
if __name__ == '__main__':
op = OptionParser()
op.add_option('-g','--genomes', dest='genome... |
readsf', help='Fasta file of sequences')
parser.add_option('-k', dest='k', type='int', help='Number of clusters')
parser.add_option('-p', dest='proc', type='int', default=2, help='Number of processes to run [Default=%default]')
# help='Use a soft assignment of reads to clusters [Default=%default]'
parse... | ####################
def maxlike_clusters(total_starts, readsf, k, soft_assign):
like = [0]*total_starts
for i in range(total_starts):
os.chdir('tmp.start%d' % i)
if len(glob.glob('cluster-*.fa')) > 0:
# determine likelihood
like[i] = scimm_like(readsf, k, soft_assign)
... | ihood initial partitioning
max_like = min(like) # '' is greater than numbers
for i in range(len(like)):
if like[i] != '' and like[i] >= max_like:
max_like = like[i]
max_clust = i
# get files from max
for c in range(len(glob.glob('cluster-*.fa'))):
shuti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''CMU dict file parser
Copyright (C) 2010
Yosuke Matsusaka
Intelligent Systems Research Institute,
National Institute of Advanced Industrial Science and Technology (AIST),
Japan
All rights reserved.
Licensed und | er the Eclipse Public Li | cense -v 1.0 (EPL)
http://www.opensource.org/licenses/eclipse-1.0.txt
'''
class CMUDict:
""" Utility class to parse CMU Pronunciation Dictionaly."""
def __init__(self, fname):
self._fname = fname
self._dict = {}
self.parse(self._fname)
def parse(self, fname):
f = open(fnam... |
# -*- coding: utf-8 -*-
# | © 2015 Roberto Lizana (Trey)
# © 2016 Pedro M. Baeza
# © 2017 Rosen Vladimirov
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, SUPERUSER_ID
def post_init_hook(cr, registry):
cr.execute("""
INSERT INTO res_partner_id_number
(partner_id, name, category_id, stat... | |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 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
# ... | ") or salle.navire is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
if navire.etendue is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
| return
personnage.agir("bouger")
# On va chercher la salle la plus proche
etendue = navire.etendue
# On cherche la salle de nagvire la plus proche
d_salle = None # la salle de destination
distance = 2
x, y, z = salle.coords.tuple()
for t_salle in... |
),
_uuid.UUID(bytes=m[1])))
def _convert_source_monotonic(s):
return _datetime.timedelta(microseconds=int(s))
def _convert_realtime(t):
return _datetime.datetime.fromtimestamp(t / 1000000)
def _convert_timestamp(s):
return _datetime.datetime.fromtimestamp(int(s) / 1000000)
if _sys.... | EFAULT_CONVERTERS = {
'MESSAGE_ID': _convert_uuid,
'_MACHINE_ID': _convert_uuid,
'_BOOT_ID': _convert_uuid,
'PRIORITY': int,
'LEADER': int,
'SESSION_ID': int,
'USERSPACE_USEC': int,
'INITRD_USEC': int,
'KERNEL_USEC': int,
'_UID': int,
'_GID': int,
'_PID': int,
'SYSLOG... | ID': int,
'_AUDIT_SESSION': int,
'_AUDIT_LOGINUID': int,
'_SYSTEMD_SESSION': int,
'_SYSTEMD_OWNER_UID': int,
'CODE_LINE': int,
'ERRNO': int,
'EXIT_STATUS': int,
'_SOURCE_REALTIME_TIMESTAMP': _convert_timestamp,
'__REALTIME_TIMESTAMP': _convert_realtime,
'_SOURCE_MONOTONIC_TIMESTA... |
from distutils.core import set | up
setup(
name='jerboa',
packages=['jerboa'], # this must be the same as the name above
version='0.2.1-alpha',
description='',
author='Matt Badger',
author_email='foss@lighthouseuk.net',
url='https://github.com/LighthouseUK/jerboa', # use the URL to the github repo
download_url='https... | 2.1-alpha', # I'll explain this in a second
keywords=['gae', 'lighthouse', 'jerboa', 'webapp2'], # arbitrary keywords
classifiers=[],
requires=['webapp2', 'blinker', 'wtforms', 'jinja2', 'pytz', 'babel', 'pycrypto'],
# tests_require=['WebTest']
)
|
##
# simple test #
###############
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 1.0 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)... | have enough inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 2.6 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].... | d = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
################################
# simple test with tw... |
import unittest
import click
from tests.test_app import TestApp
from tests.test_models import TestModels
from tests.test_utils import TestUtils
@click.group(name='tests', invoke_without_command=False)
def test():
| pass
@test.command(name='test_models')
def test_models():
"""Tes | ts implemented models"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestModels)
unittest.TextTestRunner(verbosity=2).run(suite)
@test.command(name='test_utils')
def test_utils():
"""Tests utility functions"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestUtils)
unittest.TextTest... |
ntext else {}
conn = http_client.HTTPSConnection(server, port=port, **kwargs)
elif protocol == "http":
conn = http_client.HTTPConnection(server, port=port)
else:
raise Exception("Protocol " + protocol + " not supported.")
conn.request("GET", path)
response = conn.getresponse()
if respon... | port,
path,
sslContext)
if serviceVersi | onDescription is None:
return None
if not isinstance(preferredApiVersions, list):
preferredApiVersions = [ preferredApiVersions ]
for desiredVersion in preferredApiVersions:
if __VersionIsSupported(desiredVersion, serviceVersionDescription):
return desiredVersion
return None
def S... |
p
# preserves the getitem optimization
out = ddf.to_frame().to_parquet(tmp_path_wt, engine=engine, compute=False)
dsk = optimize_dataframe_getitem(out.dask, keys=[out.key])
read = [key for key in dsk.layers if key.startswith("read-parquet")][0]
subgraph = dsk.layers[read]
assert isinstance(subg... | (ddf3["i32"] == search_val).any().compute()
assert_eq(
ddf2[ddf2["i32"] == search_val].compute(),
ddf3[ddf3["i32"] == search_val].compute(),
)
@ANY_ENGINE_MARK
def test_optimize_getitem_and_nonblockwise(tmpdir):
path = os.path.join(tmpdir, "path.parquet")
df = pd.DataFrame(
{"a... | .to_parquet(path)
df2 = dd.read_parquet(path)
df2[["a", "b"]].rolling(3).max().compute()
@ANY_ENGINE_MARK
def test_optimize_and_not(tmpdir):
path = os.path.join(tmpdir, "path.parquet")
df = pd.DataFrame(
{"a": [3, 4, 2], "b": [1, 2, 4], "c": [5, 4, 2], "d": [1, 2, 3]},
index=["a", "b"... |
if len(tier) > 1:
tier2children[tier[0:-1]].add(tier)
else:
tier2children[()].add(tier)
return tier2children
def validate_and_normalize_ip(ip):
"""
Return normalized ip if the ip is a valid ip.
Otherwise raise ValueError Exception. The hostname is
... | ion 6.1.2.4). However, a valid host name can never
have the dotted-decimal form #.#.#.#, since at least the
highest-level component label will be alphabetic.
"""
new_address = address.lstrip('[').rstrip(']')
if address.startswith('[') and address.endswith(']'):
return validate_and_n... | n new_address
elif is_valid_ipv6(new_address):
return expand_ipv6(new_address)
elif is_valid_hostname(new_address):
return new_address
else:
raise ValueError('Invalid address %s' % address)
def is_valid_hostname(hostname):
"""
Return True if the provided hostname is a valid... |
"""
__author__ = 'Christopher Fagiani'
"""
import sys, argparse, json, string, collections
from datetime import datetime
SummaryData = collections.namedtuple('SummaryData', 'wordCounts articles commentCount authors anonCount')
def main(args):
"""This program will output a word cloud as html based on the freque... | "+str(len(summary_data.articles))+"';\n")
out_file.write("var authorCount='"+str(len(summary_data.authors))+"';\n")
out_file.write("var anonCount='"+str(summary_data.anonCount)+"';\n")
if interval is not None:
out_file.write("var intervalHrs='"+interval+"';\n")
... | ;\n")
out_file.write("var words = [")
else:
out_file.write("[")
for item in sorted_data:
if(item[1]['count']<threshold):
break
if count > 0:
out_file.write(",")
count += 1
out_file.write(json.dumps(ite... |
f not self.request:
self.request = Request()
self.request.RequestName = 'noname_request'
self.request.SourceComponent = 'FailoverTransfer'
self.defaultChecksumType = defaultChecksumType
sel | f.registrationProtocols = getRegistrationProtocols()
| #############################################################################
def transferAndRegisterFile( self,
fileName,
localPath,
lfn,
destinationSEList,
fileM... |
def __init__(self, api_url=None, app_name=None, app_pwd=None):
"""Constructor function
Params:
api_url: The URL to the Crowd API
app_name: Application login name for Crowd server
app_pwd: Application password for Crowd server
"""
self.crowd_user = app... | thod='PUT')
def delete_user(self, username):
"""
Performs a delete on a user
:param username: The login name of the user to delete
:return: nothing
"""
| self._make_request('user?username=%s' % username, method='DELETE')
def _make_request(self, resource, data=None, method=None):
"""
Helper function for making requests to the Crowd REST API
:param resource: The REST resource to access
:param data: Optional JSON payload
:p... |
import o | s
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.restless
app = Flask(__name__)
app.config.from_object('config')
#flask-sqlalchemy
db = SQLAlchemy(app)
from app import models, views
from app.models import Fact, Log
#API
manager = flask.ext.restless.APIManager(app, flask_sqlalch... | '])
|
self.assertEqual(len(init_state), 1)
self.assertEqual(init_state[0].shape.as_list(), [None, unit_a, unit_b])
model = keras.models.Model(x, y)
model.compile(
optimizer='rmsprop',
loss='mse',
run_eagerly=testing_utils.should_run_eagerly())
model.train_on_batch(
np.zeros(... | model.train_on_batch(
[np.zeros((batch, t, i1)),
np.zeros((batch, t, i2, i3))],
[np.zeros((batch, t, o1)),
np.zeros((batch, t, o2, o3))])
self.assertEqual(model.output_shape, [(None, t, o1), (None, t, o2, o3)])
def test_nest_input_output_with_init_state(self):
| batch = 10
t = 5
i1, i2, i3 = 3, 4, 5
o1, o2, o3 = 2, 3, 4
cell = NestedC |
ro General Public license along
# with this program. If not, see <http://www.gnu.org/licenses/agpl-3.0.en.html>.
#
#####################################################################################
from __future__ import absolute_import, division, print_function
from six import StringIO as NativeStringIO
from tw... | write("""{"controller": {}}""")
reactor = SelectReactor()
reactor.run = lambda: None
cli.run("crossbar",
["start", "--cbdir={}".format(self.cbdir), "--logtofile"],
reactor=reactor)
with open(os.path.join(self.cbdir, "node.l | og"), "r") as f:
logFile = f.read()
self.assertIn("Entering reactor event loop", logFile)
self.assertEqual("", self.stderr.getvalue())
self.assertEqual("", self.stdout.getvalue())
def test_stalePID(self):
with open(self.config, "w") as f:
f.write("""{"contr... |
import logging.handlers
import os
_pabotlog = logging.getLogger('PABot')
_pabotlog.setLevel(logging.DEBUG)
_logPath = os.path.abspath("./logging/pabot.log")
_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
_consoleStreamHandler = logging.StreamH | andler()
_consoleStreamHandler.setLevel(logging.DEBUG)
_consoleStreamHandler.setFormatter(_formatter)
_symLogRotFileHandler = logging.handlers.RotatingFileHandler(_logPath, maxBytes=2000000, backupCount=5)
_symLogRotFileHandler.setLevel(logging.DEBUG)
_symLogRotFileHandler.setFormatter(_formatter)
_pabotlog.addHandle... | dler(_symLogRotFileHandler)
def LogPABotMessage(message):
_pabotlog.info(message)
def LogPABotError(message):
_pabotlog.error(message)
|
"""
This module defines serializers f | or the main API data objects:
.. autosummary::
:nosignatures:
DimensionSerializer
FilterSerializer
MessageSerializer
Q | uestionSerializer
"""
from django.core.paginator import Paginator
from rest_framework import serializers, pagination
import emoticonvis.apps.corpus.models as corpus_models
import emoticonvis.apps.enhance.models as enhance_models
from django.contrib.auth.models import User
# A simple string field that looks up dimen... |
#
# Copyright 2019 The FATE 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 appli... | ue)
data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=False)
pipeline.add_component(reader_0)
pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
pipeline.compile()
pipeline.fit()
if __name__ == "__main__":
parser = argpars... | if args.config is not None:
main(args.config)
else:
main()
|
ncode('utf-8'))
root = tree.getroot()
self.assertEquals([_bytes('FooBar\\u0680\\u3120').decode("unicode_escape"),
_bytes('BarFoo\\u0680\\u3120').decode("unicode_escape")],
tree.xpath('/a/b/text()'))
self.assertEquals([root[0], root[1]],
... | _extensions_wrong_args(self):
def foo(evaluator, a, b):
retu | rn "hello %s and %s" % (a, b)
extension = {(None, 'foo'): foo}
tree = self.parse('<a><b></b></a>')
e = etree.XPathEvaluator(tree, extensions=[extension])
self.assertRaises(TypeError, e, "foo('you')")
def test_xpath_extensions_error(self):
def foo(evaluator, a):
r... |
# This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | fy_message(
'Bitcoin',
'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j',
unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'),
'This is an example of a signed message.'
)
... | 'Bitcoin',
'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j',
unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'),
'This is an example of a signed message.'
)
assert res is False
... |
class JWTValidationError( | Exception):
pass
class JWTAudienceError(JWTValid | ationError):
pass
|
ager
import pytest
import six
from cryptography.exceptions import UnsupportedAlgorithm
import cryptography_vectors
HashVector = collections.namedtuple("HashVector", ["message", "digest"])
KeyedHashVector = collections.namedtuple(
"KeyedHashVector", ["message", "digest", "key"]
)
def select_backends(names, ba... | (
example_vector and
line.startswith("# =============================================")
):
for key, value in six.iteritems(example_vector):
hex_str = "".join(value).replace(" ", "").encode("asc | ii")
example_vector[key] = hex_str
examples.append(example_vector)
example_vector = None
attr = None
elif example_vector and line.startswith("#"):
continue
else:
if attr is not None and example_vector is not None:
... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_dzenlog. | models import GeneralPost
class TextPost(GeneralPost):
body_detail_template = 'blog/text_post.html'
feed_description_template = 'blog/text_feed_detail.html'
body = models.TextField(_('Post\'s body'))
class LinkPost(GeneralPost):
body_detail_template = 'blog/link_post.html'
feed_description_templ... | '), blank=True)
|
def subtrees_equal(expected_schema_node, actual_node):
if expected_schema_node[0] != actual_node.get_name():
return False
if expected_schema_node[1] != actual_node.get_state():
return False
expected_children = expected_schema_node[2]
actual_children = actual_node.get_children()
actual_ch | ildren_names = [child.get_name() for child in actual_children]
actual_ | children_names.sort()
if len(expected_children) != len(actual_children_names):
return False
for (expected_child, actual_child_name) in \
zip(expected_children, actual_children_names):
subtrees_equal(
expected_child, actual_node.get_child(actual_child_name))
return True |
import pytest
import numpy as np
import pandas as pd
import pandas.util.testing as tm
@pytest.mark.parametrize('ordered', [True, False])
@pytest.mark.parametrize('categories', [
['b', 'a', 'c'],
['a', 'b', 'c', 'd'],
])
def test_factorize(categories, ordered):
cat = pd.Categorical(['b', 'b', 'a', 'c', No... | def test_positional_take(self, ordered):
cat = pd.Categorical | (['a', 'a', 'b', 'b'], categories=['b', 'a'],
ordered=ordered)
result = cat.take([0, 1, 2], allow_fill=False)
expected = pd.Categorical(['a', 'a', 'b'], categories=cat.categories,
ordered=ordered)
tm.assert_categorical_equal(result, ... |
his work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)]
]
with mock.patch('socket.getaddrinfo', return_value=fake_addr_info):
| self._assert_get_lb_policy(
'WhiteListRoundRobinPolicy', {'hosts': ['host1', 'host2']}, WhiteListRoundRobinPolicy
)
# test TokenAwarePolicy with args
with mock.patch('socket.getaddrinfo', return_value=fake_addr_info):
self._assert_get_lb_policy(
... |
from datapackage_pipelines.wrapper import ingest, spew
def get_votes(resource, data, stats):
data['session_voters'] = {}
stats['num_votes'] = 0
stats['num_vote_mks'] = 0
for vote in resource:
voters = data['session_voters'].setdefault(vote['session_id'], set())
for attr in ['mk_ids_pro... | if not session['voter_mk_ids']:
session['voter_mk_ids'] = None
yield session
def get_resources(resources, stats, data):
for i, resource in enumerate(resources):
if i == data['votes_index']:
get_votes(resource, data, stats)
elif i == data['plenum_index']:
... | enumerate(datapackage['resources']):
if descriptor['name'] == 'view_vote_rslts_hdr_approved':
data['votes_index'] = i
elif descriptor['name'] == 'kns_plenumsession':
data['plenum_index'] = i
fields = [{'name': 'voter_mk_ids', 'type': 'array'}]
descriptor[... |
ize=int(self.test_percentage * len(non_zeros)))
train[user, test_ratings] = 0.
test[user, test_ratings] = self.ratings[user, test_ratings]
assert(numpy.all((train * test) == 0))
self.test_indices = test
return train, test
def naive_split_items(self):
"""
... | n(rated_items_indices))
# 2d List that stores all the indices of each test set for each fold.
test_ratings = [[] for x in range(self.k_folds)]
counter = 0
numpy.random.shuffle(non_rated_indices)
# List that stores the number of indices to be added to each te... | ex == self.k_folds - 1:
test_ratings[index] = numpy.array(rated_items_indices[counter:len(rated_items_indices)])
else:
test_ratings[index] = numpy.array(rated_items_indices[counter:counter + size_of_test])
counter += size_of_test
#... |
# -*- coding: utf-8 -*-
"""Provides concept object."""
from __future__ import absolute_import
from .. import t1types
from ..entity import Entit | y
class Concept(Entity):
"""Concept entity."""
collection = 'concepts'
resource = 'concept'
_relations = {
'advertiser',
}
_pull = {
'advertiser_id': int,
'created_on': t1types.strpt,
'id': int,
'name': None,
'status': t1types.int_to_bool,
... | types.strpt,
'version': int,
}
_push = _pull.copy()
_push.update({
'status': int,
})
def __init__(self, session, properties=None, **kwargs):
super(Concept, self).__init__(session, properties, **kwargs)
|
"""
Hack to get scripts to run from source checkout without having t | o set
PYTHONPATH.
"""
import sys
from os.path import dirname, join, abspath
db_path | = dirname(__file__)
project_path = abspath(join(db_path, ".."))
sys.path.insert(0, project_path)
|
import calendar
from datetime import date
| from django.conf import settings
from django.core.mail import send_mail
from django.core.management import BaseCommand |
from django.template.loader import get_template
from compta.bank import get_bank_class
from compta.models import Compte
def generate_mail():
# Dernier jour du mois, on envoie un mail pour les comptes joints afin de fournir les sommes à y déposer
if date.today().day == calendar.monthrange(date.today().year, ... |
= pd.DataFrame(bunch.data, columns=bunch.feature_names)
>>> enc = LeaveOneOutEncoder(cols=['CHAS', 'RAD']).fit(X, y)
>>> numeric_dataset = enc.transform(X)
>>> print(numeric_dataset.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 506 entries, 0 to 505
Data columns (total 13 columns):
... | self.feature_names = X_temp.columns.tolist()
if self.drop_invariant:
self.drop_cols = []
generated_cols = util.get_generated_cols(X, X_temp, self.cols)
self.drop_cols = [x for x in generated_cols if X_temp[x].var() <= 10e-5]
try:
[self.feat... | ]
except KeyError as e:
if self.verbose > 0:
print("Could not remove column from feature names."
"Not found in generated cols.\n{}".format(e))
return self
def transform(self, X, y=None, override_return_df=False):
"""Perform ... |
import zlib
from test_support import TestFailed
import sys
import imp
try:
t = imp.find_module('test_zlib')
file = t[0]
except ImportError:
file = open(__file__)
buf = file.read() * 8
file.close()
# test the checksums (hex so the test doesn't break on 64-bit machines)
print hex(zlib.crc32('penguin')), hex... | o tongue,
| Nor any unproportioned thought his act.
Be thou familiar, but by no means vulgar.
Those friends thou hast, and their adoption tried,
Grapple them to thy soul with hoops of steel;
But do not dull thy palm with entertainment
Of each new-hatch'd, unfledged comrade. Beware
Of entra... |
import csv
import collections
import json
import numpy
from smqtk.utils.bin_utils import logging, initialize_logging
from smqtk.representation.data_set.memory_set import DataMemorySet
from smqtk.algorithms.descriptor_generator.caffe_descriptor import CaffeDescriptorGenerator
from smqtk.algorithms.classifier.index_labe... | ] for ad in child_ads])
cluster2score_avg[c] = numpy.average([ad2score_avg[ad] for ad in child_ads])
len(cluster2score_max)
###############################################################################
missing_clusters = {json.loads(l)['cluster_id'] for l in open(EVAL_MISSING_CLUSTERS)}
cluster_id_order = sort... | r2score_avg) | missing_clusters)
with open(OUTPUT_MAX_JL, 'w') as f:
for c in cluster_id_order:
if c in cluster2score_max:
f.write( json.dumps({"cluster_id": c, "score": float(cluster2score_max[c])}) + '\n' )
else:
# Due to a cluster having no child ads with imagery
... |
# -*- coding: utf-8 -*-
# © 2014 Elico Corp (https:// | www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org | /licenses/agpl.html)
import report
import wizard
|
# -*- coding: utf-8 -*-
#
# Copyright 2021 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, software
# distributed under the License is distribu | ted on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
import uuid
import asyncio
from appdaemon.appdaemon import AppDaemon
class Sequences:
def __init__(self, ad: AppDaemon):
self.AD = ad
self.logger = ad.logging.get_child("_sequences")
async def run_sequence_service(self, namespace, domain, service, kwargs):
if "entity_id" not in kwar... | ce)
#
# OK, lets run it
#
future = asyncio.ensure_future(coro)
self.AD.futures.add_future(_name, future)
return future
async def prep_sequence(self, _name, namespace, sequence):
ephemeral_entity = False
loop = False
if isinstance(se | quence, str):
entity_id = sequence
if await self.AD.state.entity_exists("rules", entity_id) is False:
self.logger.warning('Unknown sequence "%s" in run_sequence()', sequence)
return None
entity = await self.AD.state.get_state("_services", "rules", seq... |
# gcp xml backend
# Copyright (C) 2012 Jesse van den Kieboom <jessevdk@gnome.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any la... | ARAM_READABLE)
def __init__(self):
GObject.Object.__init__(self)
self.documents = []
def do_get_property(self, spec):
if spec.name == 'size':
return len(self.documents)
GObject.Obje | ct.do_get_property(self, spec)
def do_register_document(self, doc):
d = Document(document=doc)
self.documents.append(d)
d.connect('changed', self.on_document_changed)
return d
def do_unregister_document(self, doc):
doc.disconnect_by_func(self.on_document_changed)
... |
defa | ult_app_config = 'users.apps.UserConf | ig' |
from imap_tools import MailBox
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailb | ox:
criteria = 'ALL'
found_nums = mailbox.numbers(criteria)
page_len = 3
pages = int(len(found_nums) // page_len) + 1 if len(found_nums) % page_len else int(len(found_nums) // page_len)
for page in range(pages):
print('page {}'.format(page))
page_limit = slice(page * page_len, page *... | print(page_limit)
for msg in mailbox.fetch(criteria, bulk=True, limit=page_limit):
print(' ', msg.date, msg.uid, msg.subject)
|
from marshmallow_jsonapi import Schema, fields
from marshmallow import validate
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
db = SQLAlchemy(session_options={"autoflush": False})
class CRUD():
def add(self, resource):
db.session.add(resource)
return db... | = db.Column(db.String(250), unique=True, nullable=False)
class MaterialsSalvageSchema(Schema):
not_blank = validate.Length(min=1, error='Field cannot be blank')
id = fields.Integer()
MATERIAL_SALVAGE_ID = fields.Integer(primary_key=True)
name = fields.String(validate=not... | if many:
self_link = "/materials/salvage/"
else:
if 'attributes' in data:
self_link = "/materials/salvage/{}".format(data['attributes']['MATERIAL_SALVAGE_ID'])
return {'self': self_link}
class Meta:
type_ = 'materi... |
ysis_count = 100
def get_mongo_items(self, consistency_record):
# get the records from mongo in chunks
projection = dict(superdesk.resources[self.resource_name].endpoint_schema['datasource']['projection'])
superdesk.resources[self.resource_name].endpoint_schema['datasource']['projection'] =... | append(key)
elif isinstance(dict_1[key], dict):
differences.extend(self.compare_dicts(dict_1[key], dict_2[key]))
else:
if not dict_1[key] == dict_2[key]:
differences.append(key)
def run(self, resource_name,
elasticsearch_url=EL... | ares the records in mongo and elastic for a given collection
Saves the results to "consistency" collection
:param resource_name: Name of the collection i.e. ingest, archive, published, text_archive
:param elasticsearch_url: url of the elasticsearch
:param elasticsearch_index: name of the... |
# -*- coding: utf-8 -*-
# Ge | nerated by Django 1.11.28 on 2021-11-10 19:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('osf', '0238_abstractprovider_allow_updates'),
]
operations = [
migrations.AddIndex(
model_... | ject__8cc95e_idx'),
),
]
|
.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'groups'", 'symmetrical': 'False', 'to': "orm['karaage.... | ax_length': | '4', 'null': 'True', 'blank': 'True'}),
'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'title': ('django.... |
# -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... | ers.DynamicCharsetResponseMixin, Response):
default_charset = 'utf-7'
resp = MyResponse(mimetype='te | xt/html')
assert resp.charset == 'utf-7'
resp.charset = 'utf-8'
assert resp.charset == 'utf-8'
assert resp.mimetype == 'text/html'
assert resp.mimetype_params == {'charset': 'utf-8'}
resp.mimetype_params['charset'] = 'iso-8859-15'
assert resp.charset == 'iso-8859-15'
resp.data = u'Hällo ... |
# -*- coding: utf-8 -*-
import datetime as dt
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.inser... | Texinfo output ---------- | --------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'textblob', u'TextBlob Documentation',
u'Steven Loria', 'textblob', 'Simplified Pytho... |
#!/usr/bin/env python
""":mod:`Redirection <testbed.resources._redirect>` tests."""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import json as _json
import unittest as _unittest
from urllib import quote as _percent_encode
import napper as _napper
import spruce.logging as _lo... | q=0.01'))
self.assert_response_redirect_response(response,
loc=self._redirect_loc,
contenttype='text/html')
def test_postget_response_redirect(self):
response = self.request('postget', self._redirect_path)... | :
response = self.request('postget',
self._redirect_path,
accept_mediaranges=('text/html',
'*/*; q=0.01'))
self.assert_response_redirect_response(response,
... |
s None
def test_iter(self, element_cls):
keys = list(element_cls({u"foo": 1}))
assert len(keys) == 1
assert keys[0].value == u"foo"
@python2_only
def test_iterkeys(self, element_cls):
keys = list(element_cls({u"foo": 1}).iterkeys())
assert len(keys) == 1
ass... | _cls):
element = element_cls()
assert element.is_valid is None
assert not element.validate()
assert not element.is_valid
def test_validate_is_recursive(self):
validators = []
def key_validator(element, st | ate):
validators.append("key")
return True
def value_validator(element, state):
validators.append("value")
return True
element = Dict.of(
Integer.validated_by([key_validator]),
Integer.validated_by([value_validator])
)({1: 1... |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | apper.out').replace('\\', '\\\\'))
test.write('SConstruct', """
| foo = Environment()
shcc = foo.Dictionary('SHCC')
bar = Environment(SHCC = r'%(_python_)s wrapper.py ' + shcc)
foo.SharedObject(target = 'foo/foo', source = 'foo.c')
bar.SharedObject(target = 'bar/bar', source = 'bar.c')
""" % locals())
test.write('foo.c', r"""
#include <stdio.h>
#include <stdlib.h>
int
main(int argc... |
ugin(irc, msg, args, state, require=True):
cb = irc.getCallback(args[0])
if cb is not None:
state.args.append(cb)
del args[0]
elif require:
state.errorInvalid('plugin', args[0])
else:
state.args.append(None)
def getIrcColor(irc, msg, args, state):
if args[0] in ircut... | **kw):
if 'default' in kw:
self.default = kw.pop('default')
assert not kw, 'Bad kwargs for first.__init__'
self.spec = specs # for __repr__
self.sp | ecs = map(contextify, specs)
def __call__(self, irc, msg, args, state):
errored = False
for spec in self.specs:
try:
spec(irc, msg, args, state)
return
except Exception, e:
errored = state.errored
state.errored ... |
__author__ = 'Maximilian Bisani'
__version__ = '$LastChangedRevision: 1691 $'
__date__ = '$LastChangedDate: 2011-08-03 15:38:08 +0200 (Wed, 03 Aug 2011) $'
__copyright__ = 'Copyright (c) 2004-2005 RWTH Aachen University'
__license__ = """
This program is free software; you can redistribute it and/or modify... | 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 Li | cense
along with this program; if not, you will find it at
http://www.gnu.org/licenses/gpl.html, or write to the Free Software
Foundation, Inc., 51 Franlin Street, Fifth Floor, Boston, MA 02110,
USA.
Should a provision of no. 9 and 10 of the GNU General Public License
be invalid or become invalid, a valid provision i... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | except exceptions.NotFound:
pass
try:
try:
return manager.find(human_id=name_or_id, **find_args)
except exceptions.NotFound:
pass
# finally try to find entity by name
try:
resource = getattr(manager, 'resource_class', None)
... | except exceptions.NotFound:
msg = _("No %(name)s with a name or "
"ID of '%(name_or_id)s' exists.") % \
{
"name": manager.resource_class.__name__.lower(),
"name_or_id": name_or_id
}
raise exceptio... |
# 0 = open space, 1=boundary , 2= the robot, 3= finish
def maze_vision():
path= ''
maze=[]
maze.append(list('000000002000000'))
maze.append(list('000000003001100'))
maze.append(list('000000000000000'))
maze.append(list('000000000000000'))
maze.append(list('000000000000000'))
maze.append(list('000... | range(0,len(maze)-1):
if maze[y][x]=='2':
sx=x
sy=y
elif maze[y][x]=='3':
fx=x
fy=y
#print(fx)
#print(fy)
#print(sx)
#print(sy)
ans= distance(maze,sx,sy,fx,fy,path)
print ("the shortest path is "+str(ans)+ " spaces")
print(path)
def distance(maz | e, sx, sy, fx, fy,path):
up= int(sy-1)
down= int(sy+1)
left = int(sx-1)
right = int(sx+1)
print(str(sx)+','+str(sy))
updist=3333333
downdist=6666666
leftdist=5555555
rightdist=4444444
if maze[sy][sx]=='3': #reached finish
print(hit)
return 0 #return
#up
# if up >-1:... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | in(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
assert os.path.exists(path)
if _REPOSITORY is None:
_REPOSITORY = Repos | itory(path)
return _REPOSITORY
|
c | lass PowerDNSRouter(object):
"""Route all operations on powerdns models to the powerdns database."""
db_name = 'powerdns'
app_name = 'powerdns'
def db_for_read(self, model, **hints):
if model._meta.app_label | == self.app_name:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self.app_name:
return self.db_name
return None
def allow_relation(self, obj1, obj2, **hints):
if (obj1._meta.app_label == self.app_name ... |
# -*- coding: utf-8
"""
Tests related to the Cuttle class.
"""
import os
import unittest
import warnings
import time
from cuttle.reef import Cuttle, Column
from cuttlepool import CuttlePool
from cuttlepool.cuttlepool import PoolConnection
DB = '_cuttle_test_db'
DB2 = '_cuttle_test_db2'
HOST = 'localhost'
class Bas... | lass TwoDbTestCase(BaseDbTestCase):
def setUp(self):
super(TwoDbTestCase, self).setUp()
self.db2 = Cuttle(self.sql_type, db=DB2, **self.credentials)
class ThrowAway(self.db2.Model):
columns = [
Column('throwaway', 'INT')
]
self.testtable2 = ... | owAway
def tearDown(self):
super(TwoDbTestCase, self).tearDown()
self.db2.drop_db()
class CuttleInstanceTestCase(unittest.TestCase):
def test_improper_sql_type(self):
with self.assertRaises(ValueError):
db = Cuttle('wrongsql', db='db')
def test_no_db(self):
... |
# coding: utf-8
from unittest import TestCase
from yased import EventsDispatcher, Event
class AnyEvent(Event):
"""Represents any event."""
class EventsDispatcherTestCase(TestCase):
def setUp(self):
self.ed = EventsDispatcher()
def test_send(self):
calls = []
def handler(*args... | vent, sender=self)
self.ed.send(AnyEvent(), sender=self)
self.assertEqual(len(calls), 2)
def test_send_args_kwargs(self):
calls = []
event_args = (1, 2, 3)
event_kwargs = {'a': 4, 'b': 5, 'c': 6}
def handler(*args, **kwargs):
calls.append(True)
... |
self.ed.send(AnyEvent(*event_args, **event_kwargs))
self.assertEqual(len(calls), 1) |
# django-offline-messages Test Settings
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttype | s',
'django.contrib.messages',
'offline_messages',
'tests'
)
ROOT_URLCONF = ''
CO | VERAGE_ADDITIONAL_MODULES = ('offline_messages',)
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | nty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# | You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
## This file defines parameters for a prediction experiment.
import os
from n... |
""" | Subpackage for the Archiver server."""
from ..envars import SRVURL_ARCHIVER as SERVER_URL
from .client import ClientArchiver
from .pvarch import PVDetails, PVData, PVDataSet
from .devices import Orbit, Correctors, TrimQuads
from .time import Time
from . import exceptions
del client, pvarch, devic | es
|
# coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... | r of steps required to reach the destination.
**Example 1:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the first move we step from 0 to 1.
On the second step we step from 1 to 3.
**Example 2:**
**In | put:** target = 2
**Output:** 3
**Explanation:**
On the first move we step from 0 to 1.
On the second move we step from 1 to -1.
On the third move we step from -1 to 2.
**Note:**
* `target` will be a non-zero integer in the range `[-10^9, 10^9]`.
Similar Questions:
"""
class Sol... |
# -*- coding: utf-8 -*-
from kivy.uix.listview import ListView
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.adapters.listadapter import ListAdapter
from kivy.adapters.models import SelectableDataItem
from kivy.uix.listview import ListItemButton
from random import choice
from str... |
self.toggle = 'adding'
Clock.schedule_interval(self.update_list_data, 1)
def update_list_data(self, dt):
items = self.list_adapter.data
if self.toggle == 'ad | ding':
item = DataItem(name='New ' * random.randint(1, 2))
items.append(item)
self.toggle = 'changing'
print 'added ' + item.name
else:
random_index = random.randint(0, len(items) - 1)
item = items[random_index]
items[random_ind... |
"""
Benchmarking and performance tests.
"""
import pytest
from pluggy import HookspecMarker, HookimplMarker, PluginManager
from pluggy._hooks import HookImpl
from pluggy._callers import _multicall
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
@hookimpl
def hook(arg1, arg2, arg3):
ret... | , 1),
(1, 1, 5),
(1, 5, 1),
(1, 5, 5),
(5, 1, 1),
(5, 1, 5),
(5, 5, 1),
(5, 5, 5),
(20, 20, 0),
(100, 1 | 00, 0),
],
)
def test_call_hook(benchmark, plugins, wrappers, nesting):
pm = PluginManager("example")
class HookSpec:
@hookspec
def fun(self, hooks, nesting: int):
yield
class Plugin:
def __init__(self, num):
self.num = num
def __repr__(self):
... |
__author__ = 'ariel'
"""
Python Population Simulator
Copyright (C) 2015 Ariel Young
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at yo... | e = None, letter_two = None):
self.trait = trait
if alleles:
if letter_one != None:
self.letterOne = letter_one
if letter_two != None:
self.letterTwo = letter_two
if self.letterOne and self.letterTwo:
if self.letterOne. | isupper() and self.letterTwo.isupper():
self.expression = Expressions.HOMOZYGOUS_DOMINANT
self.genotype = Genotypes.DOMINANT
elif self.letterOne.isupper() and not self.letterTwo.isupper():
self.expression = Expressions.HETEROZYGOUS_DOMINANT
... |
rt pyamg
from pyamg import smoothed_aggregation_solver
from scipy.sparse.linalg import lobpcg
from diffusions import _build_laplacian
def spectral_embedding(adjacency):
""" A diffusion reordering, but that works for negative values.
"""
# Normalize the graph: the sum of each set of edges must be one
ab... | = len(adjacency)
abs_adjacency = np.abs(adjacency)
abs_adjacency.flat[::n+1] = 0
degrees = abs_adjacency.sum(axis=0)
weights = abs_adjacency - np.dot(degrees[:, np.newaxis], |
degrees[np.newaxis, :])/degrees.sum()
weights.flat[::n+1] = 0
weights -= np.diag(weights.sum(axis=0))
lambdas, maps = linalg.eigh(weights)
if lambdas[-1] <= eps:
return np.ones(n, dtype=np.int)
cluster1 = maps.T[-1] >= 0
cluster2 = maps.T[-1] < 0
... |
# -*- coding: utf-8 -*-
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from .client import SearchServiceClient
from .async_client import SearchServiceAsyncClient
__all__ = (
| "SearchServiceClient",
"SearchServiceAsyncClient",
)
|
# Copyright 2015 - StackStorm, 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 ... | result: <% $ %>
"""
WORKFLOW2 = """
---
version: "2.0"
wf2:
type: direct
tasks:
task1:
action: std.http url="https://api.library.org/books" timeout=60
publish:
result: <% $ %>
"""
WORKFLOW1_WIT | H_ITEMS = """
---
version: "2.0"
wf1_with_items:
type: direct
input:
- links
tasks:
task1:
with-items: link in <% $.links %>
action: std.http url=<% $.link %>
publish:
result: <% $ %>
"""
WORKFLOW2_WITH_ITEMS = """
---
version: "2.0"
wf2_with_items:
type: direct
input:
-... |
from datetime import datetime, timedelta
from django.db import models
from django.db.models import Max, Min
from tinymce.models import HTMLField
class Company(models.Model | ):
name = models.CharField(max_length=75, blank=True, null=True)
symbol = models.CharField(max_length=10, blank=True, null=True)
description = HTMLField(blank=True, null=True, default='')
listing_date = models.DateField(blank=True, null=True)
renamed_to = models.ForeignKey('self', blank=True, n... | =False)
is_currently_listed = models.BooleanField(blank=True, default=True)
is_suspended = models.BooleanField(blank=True, default=False)
created_datetime = models.DateTimeField(auto_now_add=True)
updated_datetime = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('symbo... |
from draftjs_exporter.constants import BLOCK_TYPES, INLINE_STYLES
from draftjs_exporter.dom import DOM
from draftjs_exporter.types import Element, Props
def render_children(props: Props) -> Element:
"""
Renders the children of a component without any specific
markup for the component itself.
"""
r... | t:
return DOM.create_element(
"pre", {}, DOM.create_element("code", {}, props["children"])
)
# Default block map to extend.
BLOCK_MAP = {
BLOCK_TYPES.UNSTYLED: "p",
BLOCK_TYPES.HEADER_ONE: "h1",
BLOCK_TYPES.HEADER_TWO: "h2",
BLOCK_TYPES.HEADER_THREE: "h3",
BLOCK_TYPES.HEADER_FOUR: ... | h4",
BLOCK_TYPES.HEADER_FIVE: "h5",
BLOCK_TYPES.HEADER_SIX: "h6",
BLOCK_TYPES.UNORDERED_LIST_ITEM: {"element": "li", "wrapper": "ul"},
BLOCK_TYPES.ORDERED_LIST_ITEM: {"element": "li", "wrapper": "ol"},
BLOCK_TYPES.BLOCKQUOTE: "blockquote",
BLOCK_TYPES.PRE: "pre",
BLOCK_TYPES.CODE: code_block... |
rl_two = provider.bucket.generate_url(
100,
'POST',
query_parameters=query_params,
headers=headers_two,
)
aiohttpretty.register_uri('POST', delete_url_two, status=204)
await provider.delete(path)
assert aiohttpretty.has_call(method='GET',... | ync def test_empty_metadata_folder(self, provider, folder_empty_ | metadata, mock_time):
path = WaterButlerPath('/this-is-not-the-root/')
metadata_url = provider.bucket.new_key(path.path).generate_url(100, 'HEAD')
url = provider.bucket.generate_url(100)
params = build_folder_params(path)
aiohttpretty.register_uri('GET', url, params=params, body... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bankaccounts', '0001_initial'),
('banktransactiontags', '0001_initial'),
]
... | ('amount', models.DecimalField(max_digits=10, verbose_name='Amount', decimal_places=2)),
('currency', models.CharField(editable=False, max_length=3, verbose_name='Currency')),
('status', models.CharField(max_length=32, default='active', verbose_name='Status', help_text='Depending on its ... | ing used by statistics.', choices=[('active', 'Active'), ('ignored', 'Ignored'), ('inactive', 'Inactive')])),
('reconciled', models.BooleanField(verbose_name='Reconciled', help_text='Whether the bank transaction has been applied on the real bank account.', default=False)),
('payment_meth... |
##########
def _doxygen_version_okay(s, want_major, want_minor, want_fix):
values = s.split('.')
maj =int(values[0])
minor = int(values[1])
fix = 0
if len(values) > 2:
# remove everything after the dash for things like: 'Doxygen
# 1.5.1-p1'
values[2] = re.sub(r'-.*$',''... | = doxygen_cmd_mac
else:
doxygen_cmd = env['doxygen_cmd']
doxygen_cmd = env.escape_string(doxygen_cmd)
doxygen_okay = False
if base.verbose(2):
base.msgb('Checking doxygen version','...')
if base.check_python_version(2,4):
| try:
(retval, output, error_output) = \
util.run_command(doxygen_cmd + " --version")
if retval==0:
if len(output) > 0:
first_line = output[0].strip()
if base.verbose(2):
base.msgb("Doxygen ... |
# systemOverloadHardening
#
# Used by:
# Celestials named like: Red Giant Beacon Class (6 of 6)
runTime = "early"
type = ("projected", "passive")
def handler(fit, module, context):
fit.modules.filteredItemMultiply(lambda mod | : "overloadHardeningBonus" in mod.itemModifiedAttributes,
"overloadHardeningBonus", module. | getModifiedItemAttr("overloadBonusMultiplier"))
|
# Django settings for celery_http_gateway project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
CARROT_BACKEND = "amqp"
CELERY_RESULT_BACKEND = "database"
BROKER_HOST = "localhost"
BROKER_VHOST = "/"
BROKER_USER = "guest"
BROKER_PASSWORD = "guest"
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
... | rating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# | Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.