repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
josephsuh/extra-specs | nova/tests/api/openstack/compute/test_consoles.py | Python | apache-2.0 | 11,446 | 0.000786 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack LLC.
# Copyright 2011 Piston Cloud Computing, 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 o... | ke_delete_console(cons_self, cont | ext, instance_id, console_id):
self.ass |
cloudera/Impala | tests/benchmark/plugins/__init__.py | Python | apache-2.0 | 1,407 | 0.004264 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | test suite run
* A pre-hook method, which is run at the beginning of the 'scope'
* A post-hook method, which is run at the end of the scope.
'''
__name__ = "BasePlugin"
def __init__(self, scope=None):
self.scope = scope
def run_pre | _hook(self, context=None):
pass
def run_post_hook(self, context=None):
pass
|
mback2k/django-bawebauth | bawebauth/apps/bawebauth/migrations/0001_initial.py | Python | mit | 1,925 | 0.005714 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import bawebauth.apps.bawebauth.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
o... | l(
name='Device',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=100, verbose_name='name')),
('ident', models.CharField(max_length=40, verbose_name='i... | Field(auto_now=True, verbose_name='date edited')),
('active', models.BooleanField(default=False, verbose_name='active')),
('enabled', models.BooleanField(default=False, verbose_name='enabled')),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
... |
robotcator/gensim | gensim/test/test_text_analysis.py | Python | lgpl-2.1 | 6,853 | 0.001605 | import logging
import unittest
from gensim.corpora.dictionary import Dictionary
from gensim.topic_coherence.text_analysis import \
InvertedIndexAccumulator, WordOccurrenceAccumulator, ParallelWordOccurrenceAccumulator, \
CorpusAccumulator
class BaseTestCases(object):
class TextAnalyzerTestBase(unittest.... | s(KeyError):
accumulator.get_occurrences("irrelevant")
with self.assertRaises(KeyError):
accumulator.get_co_occurrences("test", "irrelevant")
class TestInvertedIndexAccumulator(BaseTestCases.TextAnalyzerTestBase):
| accumulator_cls = InvertedIndexAccumulator
def test_accumulate1(self):
accumulator = InvertedIndexAccumulator(self.top_ids, self.dictionary)\
.accumulate(self.texts, 2)
# [['this', 'is'], ['is', 'a'], ['test', 'document'], ['this', 'test'],
# ['test', 'document'], ['test', 'tes... |
tierney/mustached-bear | tools/quote_test.py | Python | bsd-3-clause | 5,459 | 0.006228 | #!/usr/bin/env python
# Copyright (c) 2012 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 optparse
import quote
import sys
import unittest
verbose = False
# Wrapped versions of the functions that we're testing, ... | lf, fn, in_args, expected_out_obj):
actual = apply(fn, in_args)
self.assertEqual(actual, expected_out_obj)
def check_invertible(self, in_string, specials, escape='\\'):
q | = VerboseQuote(in_string, specials, escape)
qq = VerboseUnquote(q, specials, escape)
self.assertEqual(''.join(qq), in_string)
def run_test_tuples(self, test_tuples):
for func, in_args, expected in test_tuples:
self.generic_test(func, in_args, expected)
def testQuote(self):
test_tuples = [[Ve... |
battlemidget/cage-cmf | app/system/interface.py | Python | mit | 2,396 | 0.002087 | import os
import re
import sys
import logging
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.process import fork_processes, task_id
from tornado.log import app_log
from tornado.options import define, options, parse_command_line
from app.conf import Config
cfg ... | 0.0.0.0')
ioloop = tornado.ioloop.IOLoop.instance()
if options.debug:
tornado.autoreload.start(ioloop)
# enter the Tornado IO loop
ioloop.start()
class Application(tornado.web.Application):
def __init__(self, commons):
| self.commons = commons
self.cfg = cfg
self.cage_path = self.commons['script_location']
app_log.debug("Application path (%s)" % (self.cage_path,))
# Set application path in config
self.cfg.app_path = self.cage_path
urls = [
(r"/", "app.controllers.views.I... |
reviewboard/reviewboard | reviewboard/scmtools/tests/test_svn.py | Python | mit | 39,691 | 0 | # coding=utf-8
import os
import unittest
from hashlib import md5
from django.conf import settings
from djblets.testing.decorators import add_fixtures
from kgb import SpyAgency
from reviewboard.diffviewer.diffutils import patch
from reviewboard.diffviewer.testing.mixins import DiffParserTestingMixin
from reviewboard.... | name)
return desc
def test_get_repository_info(self):
"""Testing SVN (<backend>) get_repository_info"""
info = self.tool.get_repository_info()
self.assertIn('uuid', info)
self.assertIsInstance(info['uuid'], str)
| self.assertEqual(info['uuid'], '41215d38-f5a5-421f-ba17-e0be11e6c705')
self.assertIn('root_url', info)
self.assertIsInstance(info['root_url'], str)
self.assertEqual(info['root_url'], self.repository.path)
self.assertIn('url', info)
self.assertIsInstance(info['url'], str... |
mahak/spark | python/pyspark/ml/recommendation.py | Python | apache-2.0 | 24,774 | 0.001655 | #
# 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 us... | int] = Param(
Params._dummy(), "rank", "rank of the factorization", typeConverter=TypeConverters.toInt
)
numUserBlocks: Param[int] = Param(
Params._dummy(),
"numUserBlocks",
"number of user blocks",
typeConverter=TypeConverters.toInt,
)
numItemBlocks: Param[int] =... | )
implicitPrefs: Param[bool] = Param(
Params._dummy(),
"implicitPrefs",
"whether to use implicit preference",
typeConverter=TypeConverters.toBoolean,
)
alpha: Param[float] = Param(
Params._dummy(),
"alpha",
"alpha for implicit preference",
t... |
xdega/.dotfiles | .vim/.vim/R/synctex_evince_forward.py | Python | mit | 5,473 | 0.007491 |
# The code in this files is borrowed from Gedit Synctex plugin.
#
# Copyright (C) 2010 Jose Aliste
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free Software
# Foundation; either version 2 of the Licence, or (at your... | sys.stdout.flush()
else:
self.window.SyncView(input_file, data, 0, dbus_interface = "org.gnome.evince.Window")
sys.stdout.write("let g:rplugin_evince_loop = 0")
sys.stdout.flush()
def _syncview_handler(self, window_list):
self.handle_get_window_list_r... | 2], dbus_interface="org.gnome.evince.Window")
del self._tmp_syncview
self._handler = None
return True
path_input = sys.argv[1]
path_output = sys.argv[2]
line_number = int(sys.argv[3])
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
a = EvinceWindowProxy('file://' + path_output, True)
d... |
Metonimie/Beaglebone | alexa-amazon/basicServer/gpio_handlers.py | Python | gpl-3.0 | 525 | 0.00381 | """
/*
* Custom handlers for the BBB
*
*/
"""
import Adafruit_BBIO.GPIO as GPIO
GPIO.setup("P9_12", GPIO.OUT)
def alexaHandler(client, userdata, message):
print "Received payload: " + str(message.payload.decode())
# Assume only 1 and 0 are send here.
if message.payload == "1":
GPIO.output("P9_1... | print "Turned christmas tree On"
elif message.payload == "0":
GPIO.output("P9_12 | ", GPIO.LOW)
print "Turned christmas tree Off"
def cleanUp():
GPIO.cleanup()
|
leegao/readme2tex | readme2tex/__init__.py | Python | mit | 26 | 0.038462 | from . | render import | render |
ros/catkin | python/catkin/workspace_vcs.py | Python | bsd-3-clause | 76 | 0 | # f | or backward compatibility
from catkin | _pkg.workspace_vcs import * # noqa
|
pelson/conda-build-all | setup.py | Python | bsd-3-clause | 752 | 0.00266 | from setuptools import setup
import versioneer
setup(
name='conda-build-all',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Build all c | onda recipes within a directory/repository.',
author='Phil Elson',
author_email='pelson.pub@gmail.com',
url='https://github.com/scitools/conda-buildall',
packages=['conda_build_all'],
entry_points={
'console_scripts': [
'conda-build-all = conda_build_all.cli:main',
... | ull/1840).
'conda-buildall = conda_build_all.cli:main',
]
},
)
|
DinoV/PTVS | Python/Tests/TestData/Grammar/Ellipsis.py | Python | apache-2.0 | 17 | 0 | fob(...)
1 + . | ..
| |
Canpio/Paddle | python/paddle/fluid/tests/unittests/test_parallel_executor_crf.py | Python | apache-2.0 | 7,871 | 0.000508 | # Copyright (c) 2018 PaddlePaddle 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... | _name, trainable=False)) for x in word_input
]
emb_layers.append(predicate_embedding)
emb_layers.append(mark_embedding)
hidden_0_layers = [
fluid.layers.fc(input=emb, size=hidden_dim, act='tanh')
for emb in emb_layers
]
hidden_0 = fluid.layers.sums(input=hidden_0_layers) |
lstm_0 = fluid.layers.dynamic_lstm(
input=hidden_0,
size=hidden_dim,
candidate_activation='relu',
gate_activation='sigmoid',
cell_activation='sigmoid')
# stack L-LSTM and R-LSTM with direct edges
input_tmp = [hidden_0, lstm_0]
for i in range(1, depth):
... |
eevee/cocos2d-mirror | test/test_fadeout_layer.py | Python | bsd-3-clause | 802 | 0.028678 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 1, s, t 2, s, t 3, s, t 4.1, s, t 4.2, s, q"
tags = "FadeIn, FadeOut, ColorLayer"
import pyglet
from pyglet.gl import *
import cocos
from ... | _scene.add( l, z=0 )
l.do( FadeOut( duration=2) + FadeIn( duration=2) )
director.run (main_scene)
description = """
A ColorLayer is faded-out and fadded-in.
Notice this will not work for arbitrary Lay | er objects.
"""
if __name__ == '__main__':
main()
|
huyphan/pyyawhois | test/record/parser/test_response_whois_ax_status_available.py | Python | mit | 1,334 | 0.005247 |
# This file is autogenerated. Do not edit it | manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.ax/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from | nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisAxStatusAvailable(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.ax/status_available.txt"
host = "whois.ax"
part = yawhois.record.Part(open(fixture_pa... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/system/systementitytype_args.py | Python | apache-2.0 | 1,188 | 0.023569 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | ntitytype resource.
"""
def __init__(self) :
self._datasource = ""
@property
def datasource(self) :
ur"""Specifies the source which contains all the stored counter values.
"""
try :
return self._datasource
except Exception as e:
raise e
@datasource.setter
def datasource(self, datasource) :
ur"... | ns all the stored counter values.
"""
try :
self._datasource = datasource
except Exception as e:
raise e
|
lausser/coshsh | tests/recipes/test9/classes/os_linux.py | Python | agpl-3.0 | 1,048 | 0.009542 | import coshsh
from coshsh.application import Application
from coshsh.templaterule import TemplateRule
from coshsh.util import compare_attr
def __mi_ident__(params={}):
if coshsh.util.compare_attr("type", params, ".*red\s*hat.*|.*sles.*|.*l | inux.*|.*limux.*|.*debian.*|.*ubuntu.*|.*centos.*"):
return Linux
class Linux(coshsh.application.Application):
template_rules = [
coshsh.templaterule.TemplateRule(needsattr=None,
template="os_linux_default"),
coshsh.templaterule.TemplateRule(needsattr="filesystems",
... |
return object.__new__(cls)
def __init__(self, params):
self.test4_linux = True
class RedHat(Linux):
pass
class SuSE(Linux):
pass
class EmbeddedLinux(Linux):
template_rules = [
coshsh.templaterule.TemplateRule(needsattr=None,
template="os_linux_heartbeat"),
... |
lokik/sfepy | sfepy/physics/schroedinger_app.py | Python | bsd-3-clause | 7,582 | 0.001715 | from __future__ import absolute_import
import os
import time
from math import pi
import numpy as nm
from sfepy.base.base import Struct, output, get_default
from sfepy.applications import PDESolverApp
from sfepy.solvers import Solver
from six.moves import range
def guess_n_eigs(n_electron, n_eigs=None):
"""
G... | ng_box[1][0] - bounding_box[0][0]
E_exact = None
if options.hydrogen or options.boron:
if options.hydrogen:
Z = 1
elif options.boron:
Z = 5
if dim == 2:
E_exact = [-float(Z)**2/2/(n-0.5)**2/4
f... | elif dim == 3:
E_exact = [-float(Z)**2/2/n**2 for n in [1]+[2]*2**2+[3]*3**2 ]
if options.well:
if dim == 2:
E_exact = [pi**2/(2*a**2)*x
for x in [2, 5, 5, 8, 10, 10, 13, 13,
17, 17, 18, 20, 20 ] ]
... |
antoinecarme/pyaf | tests/periodicities/Minute/Cycle_Minute_100_T_60.py | Python | bsd-3-clause | 82 | 0.04878 | impo | rt tests.periodicities.period_test as per
per.buildModel((60 , 'T' | , 100));
|
openstack/dragonflow | dragonflow/db/neutron/models.py | Python | apache-2.0 | 1,561 | 0 | # Copyright (c) 2015 OpenStack Foundation
# 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 ... | import types
class utc_timestamp(expression.FunctionElement):
type = types.DateTime()
@compiles(utc_timestamp, 'postgresql')
def pg_utc_timestamp(element, compiler, **kw):
return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
@compiles(utc_timestamp, 'mssql')
def ms_utc_timestamp(element, compiler, **kw):
retu... | :
__tablename__ = 'dflockedobjects'
object_uuid = sa.Column(sa.String(36), primary_key=True)
lock = sa.Column(sa.Boolean, default=False)
session_id = sa.Column(sa.BigInteger, default=0)
created_at = sa.Column(sa.DateTime, onupdate=utc_timestamp())
|
tensorflow/tensorflow | tensorflow/lite/schema/upgrade_schema.py | Python | apache-2.0 | 12,866 | 0.004819 | # ==============================================================================
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
... | chema.")
parser.add_argument(
"input",
type=str,
help="Input TensorFlow lite file in `.json`, `.bin` or `.tflite` format.")
parser.add_argument(
"output",
type=str,
help="Output json or bin TensorFlow lite model compliant with "
"the new schema. Extension must be `.json`, `.bin` or `.tflite`... | irect use of tempfiles.
@contextlib.contextmanager
def TemporaryDirectoryResource():
temporary = tempfile.mkdtemp()
try:
yield temporary
finally:
shutil.rmtree(temporary)
class Converter(object):
"""Converts TensorFlow flatbuffer models from old to new version of schema.
This can convert between an... |
ChatNode/PerpetualFailure | perpetualfailure/knowledgebase/views.py | Python | gpl-2.0 | 5,808 | 0.001377 | from pyramid.httpexceptions import (
HTTPException,
HTTPFound,
HTTPNotFound,
HTTPBadRequest,
HTTPConflict,
)
from pyramid.security import Authenticated
from pyramid.view import view_config
from perpetualfailure.db import session
from perpetualfailure.knowledgebase.models import (
KB_Article,
... | # | Validate data and if appropriate update and redirect.
r = articleUpdate(request, article, path)
if isinstance(r, HTTPException): return r
return {"article": article}
def articleUpdate(request, article, path, is_new=False):
if not request.method == "POST":
return None
for key in ['title',... |
s1na/darkoob | darkoob/book/ajax.py | Python | mit | 2,980 | 0.00604 | from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from dajax.core import Dajax
from django.db import transaction
from darkoob.book.models import Book, Review
@dajaxice_register(m... |
opacity: .8
});
$('#id_text').val('');
$('#id_title').val('');
| ''')
else:
review = Review.objects.create(book=book, user=request.user, title=title, text=text)
t_rendered = render_to_string('book/review.html', {'review': review})
dajax.prepend('#id_new_post_position', 'innerHTML', t_rendered)
dajax.script('''
... |
gnunixon/sport-news-writer | writer/game/migrations/0013_auto_20150303_1108.py | Python | gpl-3.0 | 847 | 0.001181 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('game', '0012_auto_20150301_2207'),
]
operations = [
migrations.AddField(
model_name='team',
... | name='lider',
field=models.NullBooleanField(),
preserve_default=True,
),
migrations.AddField(
model_name='team',
name='loser',
field=models.NullBooleanField(),
preserve_default=True,
),
migrations.AlterField(
... | , 11, 8, 11, 345625)),
preserve_default=True,
),
]
|
Datafable/gbif-data-licenses | code/unique_licenses.py | Python | mit | 2,877 | 0.030587 | #!/usr/bin/python
import sys
import csv
import re
import os
def check_arguments():
if len(sys.argv) != 3:
print "usage: ./unique_licenses.py <input file> <output file>"
print " The input file should contain two fields: <dataset id> and <license>"
print " This script will read in the | input, fetch all licenses and compile a"
print " unique list of them. The licenses will be printed out in Markdown that"
print " allows manual annotation. As generating a file and then manually editing"
print " the result can be tricky (because a second run could overwrite manual"
print " work | ), this script will first check for the presence of licenses in the"
print " outputfile. It will only append new licenses to the outputfile."
sys.exit(-1)
return sys.argv[1:]
def get_unique_input_licenses(infile_name):
csvreader = csv.reader(open(infile_name))
input_licenses = []
header = csvreade... |
hach-que/systemd-packaged | src/python-systemd/journal.py | Python | gpl-2.0 | 20,444 | 0.002397 | # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
#
# This file is part of systemd.
#
# Copyright 2012 David Strauss <david@davidstrauss.net>
# Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
# Copyright 2012 Marti Raudsepp <marti@juffo.org>
#
# systemd is free software; you can redist... | ournal
will be closed when exiting the block.
"""
super(Reader, self).__init__(flags, path, files)
if _sys.version_info >= (3,3):
self.converters = _ChainMap()
if converters is not None:
self.converters.maps.append(converters)
self.conv... | is not None:
self.converters.update(converters)
def _convert_field(self, key, value):
"""Convert value using self.converters[key]
If `key` is not present in self.converters, a standard unicode
decoding will be attempted. If the conversion (either
key-specific or t... |
esikachev/sahara-backup | sahara/db/sqlalchemy/models.py | Python | apache-2.0 | 15,416 | 0.000065 | # Copyright (c) 2013 Mirantis 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 writ... | sa.Column(sa.String(80), nullable=False)
cluster_configs = sa.Column(st.JsonDictType())
default_image_id = sa.Column(sa.String(36))
neutron_management_network = sa.Column(sa.String(36))
anti_affinity = sa.Column(st.JsonListType() | )
management_private_key = sa.Column(sa.Text, nullable=False)
management_public_key = sa.Column(sa.Text, nullable=False)
user_keypair_id = sa.Column(sa.String(80))
status = sa.Column(sa.String(80))
status_description = sa.Column(st.LongText())
info = sa.Column(st.JsonDictType())
extra = sa.C... |
flowsha/zhwh | web/com/zhwh/controllers/error.py | Python | apache-2.0 | 264 | 0.026515 | # -*- coding: utf-8 -*-
#
#Copyright 2013 Xiangxiang Telecom Cor | poratio | n.
#@author: liusha
"""This module contains implementations of error action.
"""
#import web
class ErrorAction:
def GET(self):
return "You are accessing valid url."
#end |
vipulroxx/sympy | sympy/concrete/expr_with_limits.py | Python | bsd-3-clause | 14,916 | 0.002078 | from __future__ import print_function, division
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.relational import Equality
from sympy.sets.sets import Interval
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify ... | def is_number(self):
"""Return True if the Sum has no free symbols, else False."""
return not self.free_symbols
def as_dummy(self):
"""
Replace instances of the given dummy variables with explicit dum | my
counterparts to make clear what are dummy variables and what
are real-world symbols in an object.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x, (x, x, y), (y, x, y)).as_dummy()
Integral(_x, (_x, x, _y)... |
anselmobd/fo2 | src/lotes/migrations/0070_regracolecao_table_name.py | Python | mit | 608 | 0.001656 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-05-19 15:13
from __futu | re__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lotes', '0069_leadcolecao_regracolecao'),
]
operations = [
| migrations.AlterModelOptions(
name='regracolecao',
options={'verbose_name': 'Regra por coleção', 'verbose_name_plural': 'Regras por coleção'},
),
migrations.AlterModelTable(
name='regracolecao',
table='fo2_lot_regra_colecao',
),
]
|
Raukonim/piva | qr.py | Python | gpl-3.0 | 6,541 | 0.099832 | # -*- coding: utf-8 -*-
"""
Created on Tue May 05 09:12:14 2015
@author: afajula
"""
from pylab import *
s="HELLO WORLD"
#%% variable declaration
alphanumeric_table2 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
numeric_table ="0123456789"
alphanumeric_table={
'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':... | ing(self):
z=''
for i in range(0,self.length,2):
x=''
x=self.data[i:i+2]
print x
if len(x)==1:
y=bi | n(alphanumeric_table[x])[2:]
y=y.zfill(6)
else:
y=bin((45*alphanumeric_table[x[0]])+alphanumeric_table[x[1]])[2:]
y=y.zfill(11)
print y
z+=y
print z
#%%
hello=qrcode(s)
hello.car_count_calc()
hello.alphanumeric_encoding(... |
NicoVarg99/daf-recipes | ckan/ckan/ckan/ckanext/reclineview/tests/test_view.py | Python | gpl-3.0 | 6,249 | 0 | # encoding: utf-8
import paste.fixture
from ckan.common import config
import ckan.model as model
import ckan.tests.legacy as tests
import ckan.plugins as p
import ckan.lib.helpers as h
import ckanext.reclineview.plugin as plugin
import ckan.lib.create_test_data as create_test_data
import ckan.config.middleware as mid... | result = self.app.get(url)
assert self.resource_view['title | '] in result
assert self.resource_view['description'] in result
assert 'data-module="data-viewer"' in result.body
class TestReclineView(BaseTestReclineViewBase):
view_type = 'recline_view'
view_class = plugin.ReclineView
def test_it_has_no_schema(self):
schema = self.p.info().get(... |
scrapinghub/exporters | tests/test_readers.py | Python | bsd-3-clause | 2,129 | 0.001409 | import unittest
from exporters.readers.base_reader import BaseReader
from exporters.readers.random_reader import RandomReader
from .utils import meta
class BaseReaderTest(unittest.TestCase):
def setUp(self):
self.reader = BaseReader({}, meta())
def test_get_next_batch_not_implemented(self):
... | t_batch(self):
batch = list(self.reader.get_next_batch())
self.assertEqual(len(batch), self.options['reader']['options']['batch_size'])
def test_get_second_batch(self):
self.reader.get_next_batch()
batch = list(self.reader.get_next_batch())
self.assertEqual(len(batch), self.... | reader.get_metadata('read_items'),
self.options['reader']['options']['batch_size'])
def test_get_all(self):
total_items = 0
while not self.reader.finished:
batch = list(self.reader.get_next_batch())
total_items += len(batch)
self.assertEqual(... |
daicang/Leetcode-solutions | 137-single-number-ii.py | Python | mit | 413 | 0.024213 | from typing import List
class Solution:
de | f singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for n in nums:
seen_once = ~seen_twice & (seen_once^n)
seen_twice = ~seen_once & (seen_twice^n)
| # print(seen_once, seen_twice)
return seen_once
data = [
[1,1,1,3,3,3,5]
]
s = Solution()
for d in data:
print(s.singleNumber(d))
|
rit-sailing/website | events/migrations/0002_auto_20160123_1320.py | Python | mit | 749 | 0.001335 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-23 18:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
de | pendencies = [
('main', '0001_initial'),
('events', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='event',
old_name='start_date',
new_name='date',
),
migrations.AddField(
model_name='event',
... | ls.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='organizer', to='main.TeamMember'),
),
]
|
ScreamingUdder/mantid | qt/python/mantidqt/widgets/manageuserdirectories.py | Python | gpl-3.0 | 933 | 0.001072 | # This file is part of the mantidqt package
#
# Copyright (C) 2017 mantidproject
#
# 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) an... | U General Public License
# along with this program. If not, see <ht | tp://www.gnu.org/licenses/>.
from __future__ import (absolute_import, unicode_literals)
from mantidqt.utils.qt import import_qtlib
ManageUserDirectories = import_qtlib('_widgetscore', 'mantidqt.widgets', 'ManageUserDirectories')
|
peterayeni/django-kong-admin | kong_admin/logic.py | Python | bsd-3-clause | 1,977 | 0.003035 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from .factory import get_api_sync_engine, get_consumer_sync_engine
from .models import APIReference, ConsumerReference, PluginConfigurationReference
def synchronize_apis(client, queryset=None):
return get_api_sync_engine().synchroniz... |
def synchronize_api(client, obj, toggle=False):
if (toggle and obj.enabled) or (not toggle and not obj.enabled):
obj = get_api_sync_engine().withdraw(client, obj)
obj.enabled = False
else:
obj = get_api_sync_engine().publish(client, obj)
obj.enabled = True
if toggle:
... | bj.id).update(enabled=obj.enabled)
return obj
def synchronize_plugin_configurations(client, queryset=None):
return get_api_sync_engine().plugins().synchronize(client, queryset=queryset, delete=True)
def synchronize_plugin_configuration(client, obj, toggle=False):
obj.enabled = not obj.enabled if toggle ... |
dom96/MDSBot | modules/base.py | Python | gpl-2.0 | 539 | 0.009276 | #!/usr/bin/env python
'''
Example module
Take a look | at the test module to check how events are handled.
'''
about = "About message goes here."
def main(server, initOnChannel, usrManager):
# This gets called when the module is initialized.
# InitOnChannel is the channel this module was loaded. Or nothing
# if it was loaded at start | up.
def destroy(server):
# This gets called when the module get's unloaded.
def cmd(server, word, word_eol, usrManager):
# This is called when a command is received(|cmd or |whatever)
|
Ghost-script/Online-FIR-General-Diary-lodging-System | Web_App/Web_App/models.py | Python | mit | 2,567 | 0.005454 | from django.db import models
from django.contrib.auth.models import User
from police.models import Stationdata
class general_diary(models.Model):
ref_id = models.CharField(max_length=40,unique=True,default="00000")
firstname = models.CharField(max_length=20)
lastname = models.CharField(max_length=20)
m... | idType_1_value = models.CharField(max_length=15)
idType_2 = models.CharField(max_length=20)
idType_2_value = models.CharField(max_length=15)
StationCode = models.ForeignKey(Stationdata)
Subject = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
detail = model... | s.BooleanField(default=False)
def __str__(self): # __unicode__ on Python 2
return self.Subject
class Fir(models.Model):
ref_id = models.CharField(max_length=40,unique=True,default="00000")
firstname = models.CharField(max_length=20)
lastname = models.CharField(max_length=20)
mo... |
qtproject/pyside-shiboken | tests/otherbinding/extended_multiply_operator_test.py | Python | gpl-2.0 | 2,230 | 0.010762 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#############################################################################
##
## Copyright (C) 2016 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the test suite of PySide2.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial Lice... | oint(2, 7)
num = 3
pt2 = Point(pt1.x() * num, pt1.y() * num)
self.assertEqual(pt1 * num, pt2)
def testIntTimesPoint(self):
'''int * sample.Point'''
pt1 = Point(2, 7)
num = 3
pt2 = | Point(pt1.x() * num, pt1.y() * num)
self.assertEqual(num * pt1, pt2)
def testPointTimesNumber(self):
'''sample.Point * other.Number'''
pt = Point(2, 7)
num = Number(11)
self.assertEqual(pt * num, pt * 11)
if __name__ == '__main__':
unittest.main()
|
vianney-g/python-exercices | eulerproject/pb0027.py | Python | gpl-2.0 | 793 | 0.006305 | #!/usr/bin/env python
# *-* coding:utf-8 *-*
"""
Date :
Author : Vianney Gremmel loutre.a@gmail.com
"""
def memo(f):
class Memo(dict):
def __missing__(self, key):
r = self[key] = f(key)
return r
return Memo().__getitem__
@memo
def isprime(n):
for d in xrange(2, int(n**0.5)... |
if n % d == 0:
return False
return True
def maxi_primes():
for a in xrange(-1000, 1001):
for b in xrange(-999, 1001, 2):
n = 0
while True:
if not isprime(abs(n*n + a*n + b)) and n:
yield (n, a, b)
break... | |
pastpages/savepagenow | savepagenow/api.py | Python | mit | 4,446 | 0.002474 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import click
import requests
from .exceptions import (
CachedPage,
WaybackRuntimeError,
BlockedByRobots
)
from urllib.parse import urljoin
from requests.utils import parse_header_links
def capture(
target_url,
user_agent="savepagenow (https://github.co... | /savepagenow)"
):
"""
Archives the provided URL using archive.org's Wayback Machine, u | nless
the page has been recently captured.
Returns a tuple with the archive.org URL where the capture is stored,
along with a boolean indicating if a new capture was conducted.
If the boolean is True, archive.org conducted a new capture. If it is False,
archive.org has returned a recently cached c... |
chfoo/wpull | wpull/urlrewrite_test.py | Python | gpl-3.0 | 6,269 | 0.002393 | import unittest
from wpull.url import URLInfo
from wpull.urlrewrite import URLRewriter, strip_path_session_id, \
strip_query_session_id
class TestURLRewrite(unittest.TestCase):
def test_rewriter(self):
rewriter = URLRewriter(hash_fragment=True, session_id=True)
self.assertEquals(
... | self.assertEqual(
| strip_query_session_id(url),
'one=two&x=y',
"With prefix too."
)
url = "one=two&phpsessid=" + str32id
self.assertEqual(
strip_query_session_id(url),
'one=two&',
"With only prefix"
)
url = "sid=9682993c8daa2c549799611... |
CLLKazan/iCQA | qa-engine/forum/settings/users.py | Python | gpl-3.0 | 4,093 | 0.02321 | from forms import CommaStringListWidget
from django.forms import CheckboxSelectMultiple
from django.forms.widgets import RadioSelect
from base import Setting, SettingSet
from django.utils.translation import ugettext as _
USERS_SET = SettingSet('users', _('Users settings'), _("General settings for the iCQA users."), 20... | type.')),
('pg', _('may contain rude gestures, provocatively dressed individuals, the lesser swear words, or mild violence.')),
('r', _('may contain such things as harsh profanity, intense violen | ce, nudity, or hard drug use.')),
('x', _('may contain hardcore sexual imagery or extremely disturbing violence.')),
)
GRAVATAR_ALLOWED_RATING = Setting('GRAVATAR_ALLOWED_RATING', 'g', USERS_SET, dict(
label = _("Gravatar rating"),
help_text = _("Gravatar allows users to self-rate their images so that they can ind... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/db/models/signals.py | Python | bsd-3-clause | 658 | 0.00304 | from django.dispatch import Signal
class_prepared = Signal(providing_args=["class"])
pre_init = Signal(providing_args=["instance", "args", | "kwargs"])
post_init = Signal(providing_args=["instance"])
pre_save = Signal(providing_args=["instance", "raw", "using"])
post_save = Signal(providing_args=["instance", "raw", "created", "using"])
| pre_delete = Signal(providing_args=["instance", "using"])
post_delete = Signal(providing_args=["instance", "using"])
post_syncdb = Signal(providing_args=["class", "app", "created_models", "verbosity", "interactive"])
m2m_changed = Signal(providing_args=["action", "instance", "reverse", "model", "pk_set", "using"])
|
SteveRyherd/pyRenamer | src/pyrenamer_menu_cb.py | Python | gpl-2.0 | 2,231 | 0.000897 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.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... | tion, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
If you find any bugs or have any suggestions email: code@infinicode.org
"""
class PyrenamerMenuCB:
def __init__(self, main):
self.main = main
def on_menu_undo_activate(self, widget):
self.main.undo_manager.undo()
... | sitive(True)
def on_menu_redo_activate(self, widget):
self.main.undo_manager.redo()
self.main.dir_reload_current()
self.main.menu_undo.set_sensitive(True)
self.main.menu_redo.set_sensitive(False)
def on_menu_refresh_activate(self, widget):
self.main.file_browser.create_... |
belokop/indico_bare | indico/modules/admin/__init__.py | Python | gpl-3.0 | 2,175 | 0.004138 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE... | 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core import signals
from indico.util.i18n import ... |
diarmuidcwc/GTSVideoDecom | VideoGTSDecom.py | Python | gpl-2.0 | 3,209 | 0.009037 | # -------------------------------------------------------------------------------
# Name:
# Purpose:
#
# Copyright 2014 Diarmuid Collins dcollins@curtisswright.com
# https://github.com/diarmuid
#
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of th... | "Transmitting vid {} to address {} on port {}\n".format(self.mpegTS[vid].name,self.mpegTS[vid].dstip,self.mpegTS[vid].dstudp))
|
def bufferCallBack(self,timeStamp,pwords,wordCount,puserInfo):
'''The callback method that is run on every frame'''
# This method will take a full PCM frame and return a dict of buffers
# one for each VID in the PCM frame
self._debugcount += 1
#print "Received frame ... |
MingfeiPan/leetcode | math/168.py | Python | apache-2.0 | 448 | 0.004566 | class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
| ret = ''
while n / 26 > 1:
temp = n % 26
n = n // 26
| print(n)
print(temp)
#考虑z的情况
if temp == 0:
temp = 26
n -= 1
ret = chr(temp+64)+ret
ret = chr(n+64)+ret
return ret
|
pkoutsias/SickRage | sickbeard/browser.py | Python | gpl-3.0 | 4,389 | 0.002278 | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io/
# Git: https://github.com/SickRage/SickRage.git
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p | ublished by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage 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 Gene... | th SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import os
import string
from sickbeard import logger
from sickrage.helper.encoding import ek
# adapted from http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python/827... |
okusama27/kametwi | kametwi/twitter.py | Python | apache-2.0 | 3,518 | 0.008243 | from requests_oauthlib import OAuth1Session
import argparse
import json
from datetime import datetime
#import dateutil.tz
import pytz
import logging
import sys
from kametwi.settings import Settings
"""
This is a command line tool of watching twitter timelines
"""
__status__ = "production"
__date__ = "11 Apr 2015"... | nfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzlocal())
created_at = tz_tokyo.fromutc(dt).strftime('%Y-%m-%d %H:%M:%S')
print('[{created_at}] @{screen_name}: {message}'.format(created_at=cr | eated_at,
screen_name=tweet["user"]["screen_name"],
message=tweet["text"]))
def post_tweet(oauth,args):
params = {"status":args.tweet}
req = oauth.post(POST_STATUS_UPDATE, params = p... |
Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_shared/http_challenge_cache.py | Python | mit | 2,520 | 0.001587 | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import threading
try:
import urllib.parse as parse
except ImportError:
import urlparse as parse # type: ignore
try:
from typing import TYPE_CHECKING
excep... | URL the challenge is cached for.
:rtype: HttpBearerChallenge """
if not url:
raise ValueError("URL cannot be None")
key = _get_cache_key(url)
with _lock:
return _cache.get(key)
def _get_cache_key( | url):
"""Use the URL's netloc as cache key except when the URL specifies the default port for its scheme. In that case
use the netloc without the port. That is to say, https://foo.bar and https://foo.bar:443 are considered equivalent.
This equivalency prevents an unnecessary challenge when using Key Vault'... |
karkhaz/tuscan | toolchains/install_bootstrap/android/setup.py | Python | apache-2.0 | 2,742 | 0 | #!/usr/bin/python3
#
# Copyright 2015 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 b... | run_cmd(cmd, as_root=True)
for f in os.listdir("/sysroot"):
if os.path.isdir(os.path.join("/sysroot", f)):
shutil.copytree(os.path.join("/sysroot", f),
os.path.join("/toolchain | _root", f))
elif os.path.isfile(os.path.join("/sysroot", f)):
shutil.copy(os.path.join("/sysroot", f), "/toolchain_root")
recursive_chown("/toolchain_root")
|
joke2k/faker | faker/providers/date_time/id_ID/__init__.py | Python | mit | 861 | 0 | from .. import Provider as DateTime | Provider
cla | ss Provider(DateTimeProvider):
def day_of_week(self) -> str:
day = self.date("%w")
DAY_NAMES = {
"0": "Senin",
"1": "Selasa",
"2": "Rabu",
"3": "Kamis",
"4": "Jumat",
"5": "Sabtu",
"6": "Minggu",
}
r... |
cbare/Etudes | python/binary_tree.py | Python | apache-2.0 | 5,399 | 0.003704 | """
Binary Tree
"""
import sys,random
class Tree:
def __init__(self, item, left=None, right=None):
self.item = item
self.left = left
self.right = right
def __repr__(self):
return "Tree(%s)" % str(self.item)
def insert(tree, a):
"""
Insert an item into the tree. This is... | af node
repl = None
if parent:
if a < parent.item:
parent.left = repl
else:
parent.right = repl
else:
## replace a root node, perhaps with None
root = repl
break
... | tree = tree.left
else:
parent = tree
tree = tree.right
else:
raise KeyError("Key %s not found" % str(a))
return root
def print_in_order(tree):
if tree:
sys.stdout.write('(')
print_in_order(tree.left)
sys.stdout.write(str(tree.item))
... |
davegoopot/rube-mc-pi | rube_mc_pi/scratchplug.py | Python | gpl-2.0 | 3,671 | 0.00681 | """
Adaptor for scratch using the scratchpy interface
To function as a source, the scratch program should just broadcast a block state
e.g. broadcast 41,0
To function as a target, the scratch program should listen for broadcasts saying
either BLOCK_PRESENT or BLOCK_ABSENT. Implementation of individual block types
ha... | cratch_ex
class ScratchplugSource(rube.Source): #pylint: disable=R0903
"""Wait for a broadcast from scratch showing that the block has changed
The standard scratch.receive() method blocks until a message is received.
This implementation wraps the call in a multiprocessing loop to give up
if nothing is... | ived before a time out
"""
def __init__(self, attribs):
super(ScratchplugSource, self).__init__()
self.scratch_link = ScratchLink(attribs)
self.last_block_state = block.AIR
self.from_scratch = None
def receive_from_scratch(self, queue):
"""Look for a "x,y" broadcast ... |
openstack/murano | murano/tests/unit/packages/versions/test_mpl_v1.py | Python | apache-2.0 | 1,639 | 0 | #
# 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
# ... | age_dir = os.path.abspath(
| os.path.join(__file__, '../../test_packages/test.mpl.v1.app')
)
package = load_utils.load_from_dir(package_dir)
self.assertIsNotNone(package.supplier)
self.assertEqual('Supplier Name', package.supplier['Name'])
self.assertEqual({'Link': 'http://example.com',
... |
amsehili/auditok | tests/test_AudioSource.py | Python | mit | 31,465 | 0 | """
@author: Amine Sehili <amine.sehili@gmail.com>
"""
from array import array
import unittest
from genty import genty, genty_dataset
from auditok.io import (
AudioParameterError,
BufferAudioSource,
RawAudioSource,
WaveAudioSource,
)
from auditok.signal import FORMAT
from test_util import PURE_TONE_DICT... | dioSource(file)
audio_source.open()
data_read_all = audio_source.read(-10)
audio_source.close()
self.assertEqual(data_read_all, expected)
@genty
class TestBufferAudioSource_SR10_SW1_CH1(unittest.TestCase):
def setUp(self):
self.data | = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
self.audio_source = BufferAudioSource(
data=self.data, sampling_rate=10, sample_width=1, channels=1
)
self.audio_source.open()
def tearDown(self):
self.audio_source.close()
def test_sr10_sw1_ch1_read_1(self):
block = se... |
seba3c/scamera | notifications/migrations/0002_auto_20161014_0113.py | Python | gpl-3.0 | 656 | 0.001524 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 01:13
from __future__ import unicode_li | terals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0001_initial'),
| ]
operations = [
migrations.AddField(
model_name='telegrambot',
name='module_name',
field=models.CharField(max_length=25, null=True),
),
migrations.AlterField(
model_name='telegrambot',
name='name',
field=models.CharF... |
labordoc/labordoc-next | modules/bibrank/lib/bibrank_tag_based_indexer_unit_tests.py | Python | gpl-2.0 | 1,743 | 0.010327 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the... | ag_based_indexer')
split_ranges = lazy_import('invenio.bibrank:split_ranges')
class TestListSetOperations(InvenioTestCase):
"""Test list set operations."""
def test_union_dicts(self):
"""bibrank tag based indexer - union dicts"""
self.assertEqual({1: 5, 2: 6, 3: 9, 4: 10, 10: 1}, bibrank_tag_... | elf.assertEqual([[0, 500], [600, 1000]], split_ranges("0-500,600-1000"))
TEST_SUITE = make_test_suite(TestListSetOperations,)
if __name__ == "__main__":
run_test_suite(TEST_SUITE)
|
NSLS-II-XPD/ipython_ophyd | profile_collection_germ/acceptance_tests/01-count-pe1.py | Python | bsd-2-clause | 109 | 0 | from bluesky.plans | import count
from bluesky.callbacks import LiveTable
RE(count([pe1]), LiveTable([pe1 | ]))
|
jonathon-love/snapcraft | snapcraft/_schema.py | Python | gpl-3.0 | 2,896 | 0.000345 | #!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is d... | aft, self._schema, format_checker=format_check)
except jsonschema.ValidationError as e:
messages = [e.message]
| path = []
while e.absolute_path:
element = e.absolute_path.popleft()
# assume numbers are indices and use 'xxx[123]' notation.
if isinstance(element, int):
path[-1] = '{}[{}]'.format(path[-1], element)
else:
... |
ewindisch/nova | nova/tests/compute/test_virtapi.py | Python | apache-2.0 | 7,425 | 0 | # Co | pyright 2012 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 by applicable law or agreed to in... | is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
import mox
from nova.compute import manager as compute_manager
from nova import con... |
nareshppts/account_chart_update | currency_rate_update/currency_rate_update.py | Python | agpl-3.0 | 29,434 | 0.00683 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 Camptocamp SA
# @author Nicolas Bessi
# @source JBA and AWST inpiration
# @contributor Grzegorz Grzelak (grzegorz.grzelak@birdglobe.com), Joel Grand-Guillaume
# Copyright (c) 2010 Alexis de Latt... | 'res.company',
'linked company',
),
# #note fileds that will be used as a logger
'note':fields.text('update notice'),
'max_delta_days': fields.integer('Ma... | lue, then the currency rate is not updated in OpenERP."),
}
_defaults = {
'max_delta_days': lambda *a: 4,
}
_sql_constraints = [
(
'curr_service_unique',
'unique (service, company_id)',
... |
Azure/azure-sdk-for-python | sdk/databoxedge/azure-mgmt-databoxedge/azure/mgmt/databoxedge/v2020_09_01/operations/_users_operations.py | Python | mit | 21,208 | 0.004762 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_data_box_edge_device.metadata['url'] # type: ignore
path_format_arguments = {
... | tr'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
}
url = self._client.format_url(url, **pa... |
jmacmahon/lumberjack | lumberjack/actions.py | Python | gpl-3.0 | 7,907 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Lumberjack.
# Copyright 2014 CERN.
#
# Lumberjack is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) an... | len(actions))
def run(self):
"""The main method for the ActionQueue thread.
Called by the ``start()`` method. Not to be called directly.
"""
while (self.running or len(self.que | ue) > 0):
try:
self._flush()
except Exception as exc:
self.logger.error(
'Unexpected exception in actions thread. ' +
'Continuing anyway.',
exc_info=True)
self.exceptions.append(exc)
... |
catmaid/CATMAID | django/applications/catmaid/tests/apis/test_messages.py | Python | gpl-3.0 | 3,008 | 0.001662 | # -*- coding: utf-8 -*-
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class MessagesApiTests(CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}... | 'id': 2,
'text': 'Contents of message 2.',
'time': '2011-12-20 16:46:01.360422+00:00',
'title': 'Message 2'
},
| '2': {
'action': 'http://www.example.com/message1',
'id': 1,
'text': 'Contents of message 1.',
'time': '2011-12-19 16:46:01+00:00',
'title': 'Message 1'
},
'3': {
... |
canvasnetworks/canvas | website/drawquest/apps/whitelisting/tests.py | Python | bsd-3-clause | 2,635 | 0.004934 | import time
from django.conf import | settings
from drawquest.tests.tests_helpers import (CanvasTestCase, create_content, create_user, | create_group,
create_comment, create_staff, create_quest, create_quest_comment,
create_current_quest)
from canvas.redis_models import redis
from services import Services, override_service
from drawquest.apps.whitelisting.models import... |
ilogue/niprov | niprov/formatfactory.py | Python | bsd-3-clause | 1,093 | 0 | from niprov.dependencies import Dependencies
from niprov.formatjson import JsonFormat
from niprov.formatxml import XmlFormat
from niprov.formatnarrated import NarratedFormat
from niprov.formatsimple import SimpleFormat
from niprov.formatdict import DictFormat
from niprov.formatobject import ObjectFormat
from niprov.pic... | res import Pict | ureCache
class FormatFactory(object):
def __init__(self, dependencies=Dependencies()):
self.dependencies = dependencies
def create(self, formatName):
if formatName == 'json':
return JsonFormat(self.dependencies)
if formatName == 'xml':
return XmlFormat(self.de... |
mpaulweeks/exploitable-comic | py/current.py | Python | mit | 883 | 0 |
import os
import requests
import shutil
from bs4 import BeautifulSoup
from datetime import datetime
from .s3 import upload_file
def current():
url = 'http://intelligentlifecomics.com'
req = requests.get(url)
if(req.status_code != 200):
return
soup = BeautifulSoup(req.text, 'html.parser')
... | strip()
date_object = datetime.strptime(date_str, '%B %d, %Y')
date_fmt = date_object.strftime('%Y-%m-%d')
file_path = "temp/%s.gif" % date_fmt
img_url = soup.find(id='comicpanel').find('img').get('src')
r = requests.get(img_url, stream=True)
if r.status_code == 200:
with open(file_path... | decode_content = True
shutil.copyfileobj(r.raw, f)
upload_file(file_path)
os.remove(file_path)
if __name__ == "__main__":
current()
|
fastinetserver/portage-idfetch | pym/portage/_selinux.py | Python | gpl-2.0 | 3,723 | 0.028472 | # Copyright 1999-2009 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# Don't use the unicode-wrapped os and shutil modules here since
# the whole _selinux module itself will be wrapped.
import os
import shutil
import portage
from portage import _encodings
from portage import _uni... | rs='strict')
(rc, ctx) = selinux.lgetfilecon(src)
if rc < 0:
src = _unicode_decode(src, encoding=_encodings['fs'], errors='replace')
raise OSError(_("rename: Failed getting context of \"%s\".") % src)
| setfscreate(ctx)
try:
os.rename(src,dest)
finally:
setfscreate()
def settype(newtype):
ret = getcontext().split(":")
ret[2] = newtype
return ":".join(ret)
def setexec(ctx="\n"):
ctx = _unicode_encode(ctx, encoding=_encodings['content'], errors='strict')
if selinux.setexeccon(ctx) < 0:
ctx = _unicode_deco... |
devurandom/portage | pym/portage/_sets/dbapi.py | Python | gpl-2.0 | 14,306 | 0.029568 | # Copyright 2007-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
import time
from portage import os
from portage.versions import best, catsplit, vercmp
from portage.dep import Atom
from portage.localization import _
from portage._sets.base import PackageSet
from portage._sets... | tion = "Package set which contains all packages " + \
"for which the highest visible ebuild version is lower than " + \
"the currently installed version."
def __init__(self, portdb=None, vardb=None):
super(DowngradeSet, self).__init__()
self._portdb = portdb
self._vardb = | vardb
def load(self):
atoms = []
xmatch = self._portdb.xmatch
xmatch_level = "bestmatch-visible"
cp_list = self._vardb.cp_list
aux_get = self._vardb.aux_get
aux_keys = ["SLOT"]
for cp in self._vardb.cp_all():
for cpv in cp_list(cp):
slot, = aux_get(cpv, aux_keys)
slot_atom = "%s:%s" % (cp, s... |
coder006/BinPy | BinPy/tools/powersource.py | Python | bsd-3-clause | 1,962 | 0.005097 | from BinPy.Gates import *
class PowerSource:
"""
Models a Power Source from which various connectors can tap by connecting to it.
taps: The list of all connectors connected to this power source.
connect(): Takes in one or more connectors as input and connects them to the power source.
disconne... | alue of None.
A message | is printed if a specified connector is not already tapping from this source.
"""
for connector in connectors:
if isinstance(connector, Connector):
try:
self.taps.remove(connector)
connector.state = None
connector.c... |
jobovy/apogee-maps | py/get_agetables.py | Python | bsd-3-clause | 3,237 | 0.0173 | import os, os.path
import pexpect
import subprocess
from astropy.io import fits
import numpy as np
from optparse import OptionParser
import sys
import tempfile
from ftplib import FTP
import shutil
_ERASESTR= " "
def get_agetables(args,opti... | ath.join(filePath,catalogname))
downloading= False
if interrupted:
raise KeyboardInterrupt
except:
raise
if not downloading: #Assume KeyboardInterrupt
raise
elif ntries > _MAX_NTRIES:
raise IOError('File ... | )
finally:
if os.path.exists(tmp_savefilename):
os.remove(tmp_savefilename)
ntries+= 1
sys.stdout.write('\r'+_ERASESTR+'\r')
sys.stdout.flush()
return None
def get_options():
usage = "usage: %prog [options] <outpath>"
parser = OptionParser(usage=... |
Lucas-C/pre-commit | pre_commit/languages/script.py | Python | mit | 444 | 0 | from __future__ import unicode_literals
from pre_commit.languages import helpers
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(repo_cmd_runner, hook, file_args):... | )
| |
justinwp/croplands | migrations/versions/4986e64643f4_.py | Python | mit | 1,023 | 0.01173 | """empty message
Revision ID: 4986e64643f4
Revises: 175003d01257
Create Date: 2015-04-15 12:16:41.965765
"""
# revision identifiers, used by Alembic.
revision = '4986e64643f4'
down_revision = '175003d01257'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
... | re_id', sa.String(), nullable=False))
op.alter_column('tile', 'date_acquired',
existing_type=postgresql | .TIMESTAMP(),
nullable=False)
op.create_unique_constraint(None, 'tile', ['feature_id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'tile', type_='unique')
op.alter_column('tile', 'date_acquired',... |
khosrow/metpx | columbo/lib/cs/missingFile.py | Python | gpl-2.0 | 1,981 | 0.007067 | #!/usr/bin/python2
#!/software/pub/python-2.3.3/bin/python
"""
MetPX Copyright (C) 2004-2006 Environment Canada
MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file
named COPYING in the root of the source directory tree.
"""
##########################################################################... | t>
</head>
<body text="#000000" bgcolor="#3b87a9" link="#00ff00" vlink="ff00ff" >
<center>
"""
if image:
template.printMainImageCenter()
#print "<br>"
#for key in keys:
# print "%s = %s <br>" % (key, os.environ[key])
print """
<table width="100%%" border="0" cell | padding="0" cellspacing="0">
<tr>
<td valign="top" align="center" bgcolor="#cccccc">
<br>
</td>
</tr>
<tr>
<td valign="top" align="center" bgcolor="#cccccc">
<blockquote>
<font size="6"><b><pre>Missing File (%s)</pre></b></font>
<font size="7" color="red"><b><pre>Con... |
mandshaw/lethe | lethe/rollardex.py | Python | mit | 2,314 | 0.002593 | import os
import csv
from datetime import datetime
lethe_dir = os.path.dirname(__file__)
class PersonNotFoundError(BaseException):
pass
class Person(object):
"""
Class to store details of each person
"""
def __init__(self, name, email, dob, organiser, checksum):
"""
Constructor t... | checksum):
with open(self.rollardex_source, 'wb') as rollardex_csv:
rollardex_reader = csv.writer(rollardex_csv, delimiter=',')
birthday_boy = self.find(birthday_boy.name)
birthday_boy.organiser = organiser
birthday_boy.checksum = checksum
for person i... | er, person.checksum])
|
Jumpscale/jumpscale_core8 | lib/JumpScale/tools/realitycapture/Monitor.py | Python | apache-2.0 | 3,119 | 0.000641 |
class Monitor:
def __init__(self, controller, redis_address):
self.controller = controller
self.redis_address = redis_address
def _schedule(self, gid, nid, domain, name, args={}, cron='@every 1m'):
"""
Schedule the given jumpscript (domain/name) to run on the specified node ac... | : Node id
:param args: ju | mpscript arguments
:param cron: cron specs
:return:
"""
pass
def virtual_machine(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the vm monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript ar... |
Haikson/sitemap-generator | pysitemap/db.py | Python | apache-2.0 | 852 | 0.002347 | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.sql import ClauseElement
DB_URI = 'sqlite:///stuff.db'
db_endine = create_engine(DB_URI)
session = scoped_session(
sessionmaker(
autocommit=... | create(session, model, defaults=None, **kwargs):
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
params = dict((k, v) for k, v in kwargs.items() if not isinstance(v, ClauseElement))
params.update(defaults or {})
instance =... | session.commit()
return instance, True
|
zzzsochi/includer | setup.py | Python | bsd-3-clause | 659 | 0.001517 | from setuptools import setup
setup(name='includer',
| version='1.0.2',
description='Include and run callables',
classifiers=[
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX",
"Programming Language :: Python :: 3",
"Development Status :: 5 - Production/Stable",
],
author='Alexande | r Zelenyak',
author_email='zzz.sochi@gmail.com',
license='BSD',
url='https://github.com/zzzsochi/includer',
keywords=['include', 'configure', 'pyramid'],
py_modules=['includer'],
install_requires=['zope.dottedname'],
tests_require=['pytest'],
)
|
waylonflinn/asv | test/test_dev.py | Python | bsd-3-clause | 3,311 | 0.000302 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
import re
from os.path import abspath, dirname, join
import shutil
import pytest
import six
from a... | gs(argv)
assert args.python is None
def test_run_steps_arg():
parser, subparsers = mak | e_argparser()
argv = ['run', '--steps=20', 'ALL']
args = parser.parse_args(argv)
assert args.steps == 20
if __name__ == '__main__':
test_dev('/tmp')
|
emulbreh/vacuous | vacuous/backends/__init__.py | Python | mit | 995 | 0.007035 | import threading
from django.conf import settings
from django.utils.importlib import import_module
from django.core.signals import request_finished
_cache = threading.local()
def __init():
if not hasattr(_cache, 'backends'):
_cache.backends = {}
def load_backend(flavor, path, cache=True):
__init()
... | module_path, cls_name = import_path.rsplit('.', 1)
cls = getattr(import_module(module_path), cls_name)
backend = cls(path)
backend.flavor = flavor
if not cache:
return backend
_cache.backends[key] = backend
return _cache.backends[key]
def purge_backe... | *kwargs: purge_backend_cache())
|
willowd878/nca47 | nca47/api/hooks/auth_token.py | Python | apache-2.0 | 1,716 | 0.001166 | import re
from keystonemiddleware import auth_token
from oslo_log import log
from nca47.common import exception
from nca47.common.i18n import _
from nca47.common import utils
LOG = log.getLogger(__name__)
class AuthTokenMiddleware(auth_token.AuthProtocol):
"""A wrapper on Keystone auth_token middleware.
D... | self.public_api_routes = [re.compile(route_pattern_tpl % route_tpl)
for route_tpl in pu | blic_api_routes]
except re.error as e:
msg = _('Cannot compile public API routes: %s') % e
LOG.error(msg)
raise exception.ConfigInvalid(error_msg=msg)
super(AuthTokenMiddleware, self).__init__(app, conf)
def __call__(self, env, start_response):
path = u... |
amwelch/a10sdk-python | a10sdk/core/A10_file/file_ssl_cert_key.py | Python | apache-2.0 | 1,981 | 0.007572 | from a10sdk.common.A10BaseClass import A10BaseClass
class SslCertKey(A10BaseClass):
""" :param action: {"optional": true, "enum": ["create", "import", "export", "copy", "rename", "check", "replace", "delete"], "type": "string", "description": "'create': create; 'import': import; 'export': export; 'copy': ... | n": "ssl certificate file size in byte", "format": "number", "type": "number", "maximum": 2147483647, "minimum": 0, "optional": true}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
Class Description::
ssl certificate and key file inform | ation and management commands.
Class ssl-cert-key supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/file/ssl-cert-key`.
"""
def __init__(self, *... |
gandalfcode/gandalf | tests/paper_tests/jeanstest.py | Python | gpl-2.0 | 9,111 | 0.01339 | #==============================================================================
# jeanstest.py
# Run Noh test using initial conditions file 'noh.dat'.
#==============================================================================
from gandalf.analysis.facade import *
import time
import matplotlib.pyplot as plt
import ... | jeans_stable_solution(x, omega, rhofit):
# return rhofit*(1.0 + amp*np.sin(2.0*math.pi*x/wavelength)*np.cos(omega*tend))
#def jeans_unstable_solution(x, omega, rhofit):
# return rho0*(1.0 + amp*np.sin(2.0*math.pi*x/wavelength)*np.cosh(omega*tend))
def oscillation_period(lambda_jeans):
return np.sqrt(np.pi/... | 0/np.pi/rho0)*wavelength/np.sqrt(wavelength*wavelength - lambda_jeans*lambda_jeans)
# Quick sims to generate
periodic_sim = newsim('jeans.dat')
periodic_sim.SetParam('tsnapfirst', 0.0)
periodic_sim.SetParam('temp0', 0.1)
periodic_sim.SetParam('amp', 0.15)
periodic_sim.SetParam('Nstepsmax',1)
setupsim()
run()
# Get g... |
jomolinare/kobocat | onadata/apps/logger/models/__init__.py | Python | bsd-2-clause | 437 | 0 | from onadata.apps.logger.models.attachment import Attachment # flake8: noqa
from onadata.apps.logger.models.instance import Instance
from onadata.apps.logger.models.survey_type import SurveyType
from | onadata.apps.logger.models.xform import XForm
from onadata.apps.logger.xform_instance_parser import Instance | ParseError
from onadata.apps.logger.models.ziggy_instance import ZiggyInstance
from onadata.apps.logger.models.note import Note
|
CobwebOrg/cobweb-django | core/admin_inlines.py | Python | mit | 489 | 0 | from dja | ngo.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from core.models import Organization, Note, CrawlScope
class OrganizationInline(admin.TabularInline):
model = Organization
class NoteInline(GenericStackedInline):
model = Note
fields = ('when_created', 'author',... | extra = 0
class CrawlScopeInline(admin.StackedInline):
model = CrawlScope
extra = 0
|
LorenaCapo/1DAW_Python | Práctica 2/practica2_exercici8.py | Python | gpl-3.0 | 263 | 0.007605 | #Pràctica 2 - Exercici 8
# Fer un programa on l'usuari introdueixi un preu del producte i aquest
# calcu | li el preu amb IVA (IVA 16%)
precio = int(raw_input("¿Qué precio tiene el producto? "))
total = precio * | 1.16
print "El precio total es: " , total
|
jdepoix/goto_cloud | goto_cloud/urls.py | Python | mit | 767 | 0 | """goto_cloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | ls import url, include
2. Add a URL to urlpatterns: url(r'^blo | g/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
jaeilepp/mne-python | mne/beamformer/tests/test_dics.py | Python | bsd-3-clause | 13,250 | 0 | from __future__ import print_function
import warnings
import os.path as op
import copy as cp
from nose.tools import assert_true, assert_raises, assert_equal
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
import mne
from mne.datasets import testing
from mne.beamformer import... | picks=picks, baseline=(None, 0), preload=True,
reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
epochs.resample(200, npad=0, n_jobs=2)
evoked = epochs.average().crop(0, None)
# Computing the data and noise cross-spectral den | sity matrices
if compute_csds:
data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.045,
tmax=None, fmin=8, fmax=12,
mt_bandwidth=72.72)
noise_csd = csd_epochs(epochs, mode='multitaper', tmin=None,
tmax=0.0... |
hankcs/HanLP | plugins/hanlp_demo/hanlp_demo/zh/tf/train/train_ptb_dep_sa_albert_topk.py | Python | apache-2.0 | 1,269 | 0.001576 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-03-07 23:48
from hanlp.metrics.parsing import conllx_eval
from hanlp.datasets.parsing.ptb import PTB_SD330_DEV, PTB_SD330_TRAIN, PTB_SD330_TEST, PTB_TOKEN_MAPPING
from hanlp.components.parsers.biaffine_parser_tf import BiaffineTransformerDependencyParserTF, \
St... | ng_rate_transformer=1e-5,
# alpha=1,
# early_stopping_patience=10,
| # num_decoder_layers=2,
)
parser.load(save_dir)
# output = f'{save_dir}/test.predict.conll'
parser.evaluate(PTB_SD330_TEST, save_dir, warm_up=False)
# uas, las = conllx_eval.evaluate(PTB_SD330_TEST, output)
# print(f'Official UAS: {uas:.4f} LAS: {las:.4f}')
print(f'Model saved in {save_dir}')
|
elena/django | tests/postgres_tests/test_operations.py | Python | bsd-3-clause | 19,320 | 0.002381 | import unittest
from unittest import mock
from migrations.test_base import OperationTestBase
from django.db import NotSupportedError, connection
from django.db.migrations.state import ProjectState
from django.db.models import Index
from django.db.utils import ProgrammingError
from django.test import modify_settings, ... | .app_label, editor, project_state, new_state)
self.assertEqual(len(captured_queries), 0)
# Reversal.
with CaptureQueriesContext(connecti | on) as captured_queries:
with connection.schema_editor(atomic=False) as editor:
operation.database_backwards(self.app_label, editor, new_state, project_state)
self.assertEqual(len(captured_queries), 0)
def test_allow_migrate( |
jonathanmorgan/reddit_data | migrations/0006_auto__add_field_subreddit_time_series_data_create_date__add_field_subr.py | Python | gpl-3.0 | 20,772 | 0.00804 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Subreddit_Time_Series_Data.create_date'
db.add_column(u'reddit_data_subreddit_time_series_da... | ),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'display_name': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'filter_1': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'f... | default': 'False'}),
'filter_2': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'filter_3': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'filter_4': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'filter_5':... |
sorenh/cc | vendor/Twisted-10.0.0/twisted/lore/man2lore.py | Python | apache-2.0 | 7,773 | 0.003988 | # -*- test-case-name: twisted.lore.test.test_man2lore -*-
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
man2lore: Converts man page source (i.e. groff) into lore-compatible html.
This is nasty and hackish (and doesn't support lots of real groff), but is good
enough for converti... | lf.write('<dt>')
if self.tp == 2:
self.write('<dd>')
self.paraCheck()
bits = line.split('\\')
self.write(escape(bits[0]))
for bit | in bits[1:]:
if bit[:2] == 'fI':
self.write('<em>' + escape(bit[2:]))
self.state = 'em'
elif bit[:2] == 'fB':
self.write('<strong>' + escape(bit[2:]))
self.state = 'strong'
elif bit[:2] == 'fR':
self.writ... |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/attribute_specification/test_rule_500.py | Python | gpl-3.0 | 2,176 | 0.003676 |
import os
import unittest
from vsg.rules import attribute_specification
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_500_test_input.vhd'))
lExpected_lower = []
lExpected_lower.append('')
utils.read_... |
oRule.analyze(self.oFile)
self.assertEqual(utils.extract_violation_lines_from_violation_object(oRule.violations), lExpected)
def test_rule_500_upper(self):
oRule = attribute_specification.rule_500()
oRule.case = 'upper | '
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'attribute_specification')
self.assertEqual(oRule.identifier, '500')
lExpected = [4]
oRule.analyze(self.oFile)
self.assertEqual(utils.extract_violation_lines_from_violation_object(oRule.violations), lExpected)
de... |
susingha/0x_tools | programs/pycharm/py_classptr.py | Python | gpl-2.0 | 701 | 0.002853 | import random
class node:
def __init__(self, val):
self.val = val
self.random = random.randint(20, 50)
self.ptr = None
arr = []
arr.append(node(0))
arr.append(node(1))
arr.append(node(2))
arr.append(node(3))
arr.append(node(4))
# check the list
print "before modification"
for n in arr:
... | ble
n = hasht[2]
n.random = 100
# change a value on a node in the hashtable directly
hasht[1].random = 500
print
print "after modifica | tion in hashtable 1"
# check the list again
for n in arr:
print n.val, n.random, n.ptr, n
|
LinkageIO/LocusPocus | tests/test_Chromosome.py | Python | mit | 1,038 | 0 | import pytest
from locuspocus import Chromosome
@pytest.fixture
def chr1():
return Chromosome("chr1", "A" * 500000)
@pytest.fixture
def chr2():
return Chromosome("chr1", "C" * 500000)
def test_init(chr1):
assert chr1
def test_init_from_seq():
x = Chromosome("chr1", ["a", "c", "g", "t"])
asse... |
Chromo | some("test", "abcd")
assert True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.