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
OpenTouch/night-watch
src/nw/providers/Ping.py
Python
apache-2.0
8,878
0.01194
# Copyright (c) 2014 Alcatel-Lucent Enterprise # 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 # # Un...
ion if the Provider' configuration is valid. def _isConfigValid(self): Provider._isConfigValid(self) # If requested_data is provided, check if it is managed by Ping provider if self._config.get('requested_data') and not (self._config.get('requested_data') in _data_available): get...
ider Ping is not allowed. Allowed conditions are: ' + str(_data_available)) return False return True class PingData: """ Class extracting ping statistics data using regexps on ping command response. /!\ Warning: regexp used to extract information applies on string returned by p...
richardliaw/ray
rllib/agents/trainer_template.py
Python
apache-2.0
8,307
0
import logging from typing import Callable, Iterable, List, Optional, Type from ray.rllib.agents.trainer import Trainer, COMMON_CONFIG from ray.rllib.env.env_context import EnvContext from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.execution.rollout_ops import ParallelRollouts, ConcatBatches from ...
returned, will use `default_policy` (which must be provided then). validate_env (Optional[Callable[[EnvType, EnvContext], None]]): Optional callable to validate the generated environment (only on worker=0). before_init (Opt
ional[Callable[[Trainer], None]]): Optional callable to run before anything is constructed inside Trainer (Workers with Policies, execution plan, etc..). Takes the Trainer instance as argument. after_init (Optional[Callable[[Trainer], None]]): Optional callable to ...
cuckoobox/cuckoo
cuckoo/data/analyzer/android/lib/core/config.py
Python
mit
881
0.001135
# Copyright (C) 2014-2016 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. # Originally contributed by Check Point Software Technologies, Ltd. import ConfigParser class Conf
ig: def __init__(self, cfg): """@param cfg: configuration file.""" config = ConfigParser.ConfigParser(allow_no_value=True) config.read(cfg) for section in config.sections(): for name, raw_value in config.items(section): try: value = co...
ame) except ValueError: value = config.get(section, name) setattr(self, name, value)
nagyv/python-api-library
kayako/core/lib.py
Python
bsd-2-clause
5,597
0.001787
# -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (c) 2011, Evan Leis # # Distributed under the terms of the Lesser GNU General Public License (LGPL) #----------------------------------------------------------------------------- ''' Created on May 5, 2011...
)' def __str__(self):
return '??' class _forever(object): def __int__(self): return 0 def __repr__(self): return '0' def __str__(self): return '<Forever>' UnsetParameter = _unsetparameter() FOREVER = _forever() class ParameterObject(object): ''' An object used to build a dictionary ar...
beyond-content/python-pdf-paper-saver
src/pdfpapersaver/__init__.py
Python
bsd-2-clause
2,516
0.001192
from P
yPDF2 import PdfFileReader, PdfFileWriter from rect import Rec
t from rect.packer import pack from reportlab.lib import pagesizes from reportlab.lib.units import mm __version__ = "0.1.0" class PDFPagePacker(object): def __init__(self, pdf_file, canvas_size=pagesizes.A4, padding=5 * mm): super(PDFPagePacker, self).__init__() self.pdf_file = pdf_file s...
graingert/sqlalchemy
lib/sqlalchemy/dialects/postgresql/__init__.py
Python
mit
2,432
0
# postgresql/__init__.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import base from . import pg8000 # noqa from . import psycopg2 # noq...
.ranges import TSTZRANGE base.dialect = dialect = psycopg2.dialect __all__ = ( "INTEGER", "BIGINT", "SMALLINT", "VARCHAR", "CHAR", "TEXT", "NUMERIC", "FLOAT", "REAL", "INET", "CIDR", "UUID", "BIT", "MACADDR", "MONEY", "OID", "REGCLASS", "DOUBLE...
"BOOLEAN", "INTERVAL", "ARRAY", "ENUM", "dialect", "array", "HSTORE", "hstore", "INT4RANGE", "INT8RANGE", "NUMRANGE", "DATERANGE", "TSVECTOR", "TSRANGE", "TSTZRANGE", "JSON", "JSONB", "Any", "All", "DropEnumType", "CreateEnumType", "...
dana-i2cat/felix
modules/resource/orchestrator/src/extensions/sfa/trust/speaksfor_util.py
Python
apache-2.0
18,996
0.005159
#---------------------------------------------------------------------- # Copyright (c) 2014 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including witho...
file(cred.save_to_string()) cert_args = [] if trusted_roots: for x in trusted_roots: cert_args += ['--trusted-pem', x.filename] # FIXME: Why do we not need to specify the --node-id option as credential.py does? xmlsec1_args = [cred.xmlsec_path, '--verify'] + cert_args + [ cred_file] ...
# FIXME # xmlsec errors have a msg= which is the interesting bit. # But does this go to stderr or stdout? Do we have it here? verified = "" mstart = verified.find("msg=") msg = "" if mstart > -1 and len(verified) > 4: mstart = mstart + 4 m...
zwChan/VATEC
~/eb-virt/Lib/site-packages/werkzeug/local.py
Python
apache-2.0
14,275
0.003853
# -*- coding: utf-8 -*- """ werkzeug.local ~~~~~~~~~~~~~~ This module implements context-local objects. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import copy from functools import update_wrapper from werkzeug.wsgi impo...
ge[ident] = {name: value} def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) class LocalStack(object): """This class work
s similar to a :class:`Local` but keeps a stack of objects instead. This is best explained with an example:: >>> ls = LocalStack() >>> ls.push(42) >>> ls.top 42 >>> ls.push(23) >>> ls.top 23 >>> ls.pop() 23 >>> ls.top 42 ...
firebitsbr/termineter
framework/core.py
Python
gpl-3.0
18,028
0.023408
# framework/core.py # # Copyright 2011 Spencer J. McIntyre <SMcIntyre [at] SecureState [dot] net> # # 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 # (a...
import logging import logging.hand
lers import os import re import serial import sys from c1218.connection import Connection from c1218.errors import C1218IOError, C1218ReadTableError from framework.errors import FrameworkConfigurationError, FrameworkRuntimeError from framework.options import AdvancedOptions, Options from framework.templates import Ter...
quiubas/quiubas-python
quiubas/quiubas.py
Python
mit
1,137
0.05277
import re import urllib from network import network from balance import balance from sms import sms class Quiubas: def __init__( self ): self.lib_version = '1.1.1' self.api_key = None self.api_private = None self.base_url = 'https://api.quiubas.com' self.version = '2.1' self.network = network( se...
self.api_key = api_key self.api_private = api_private def getAuth( self ): return { 'api_key': self.api_key, 'api_private': self.api_private } def format(self, path, vars = None): if not vars: vars = dict() parsed_vars = dict() for k in vars.keys(): if vars[k] is not None: parsed_vars[...
d_vars.keys()))) if len(parsed_vars) != 0: return regex.sub(lambda mo: str(parsed_vars[mo.string[mo.start():mo.end()]]), path) else: return path
AfricaChess/lichesshub
lichesshub/settings.py
Python
mit
4,754
0.001052
""" Django settings for lichesshub project. Generated by 'django-admin startproject' using Django 1.11.6. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import...
ITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$3+$70f7z6kyjb^=u26flklf^&%fso+)lrc27)i-_rzjf@@tt@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HO
STS = ['africachess.everyday.com.ng', 'localhost', '127.0.0.1', '138.197.117.2'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '...
makinacorpus/django
django/db/models/sql/compiler.py
Python
bsd-3-clause
49,723
0.001589
import datetime from django.conf import settings from django.core.exceptions import FieldError from django.db.backends.util import truncate_name from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import select_related_descend, QueryWrapper from django.db.models.sql.constants import (SI...
== self.query.high_mark: return '', () self.pre_sql_setup() # After executing the query, we must get rid of any joins the query # setup created. So, take note of alias counts before the query ran. #
However we do not want to get rid of stuff done in pre_sql_setup(), # as the pre_sql_setup will modify query state in a way that forbids # another run of it. self.refcounts_before = self.query.alias_refcount.copy() out_cols, s_params = self.get_columns(with_col_aliases) ordering,...
fbradyirl/home-assistant
tests/components/homematicip_cloud/__init__.py
Python
apache-2.0
49
0
"""Tests
for the HomematicIP Cloud compo
nent."""
hzj123/56th
pombola/south_africa/bin/people-json/committees.py
Python
agpl-3.0
2,683
0.011182
import csv import re import unicodedata from utils import * def initialise(name): return re.sub('[^A-Z]', '', name) def asciify(name): return unicodedata.normalize('NFKD', unicode(name)).encode('ascii', 'ignore') def parse(data): orgs_by_id = dict([ (x['id'], x) for x in data['organizations'].values() ])...
], row['Party'] + orgs_by_id[party]['name'] mship = { 'organization_id': data['organizations'][row['Committee']]['id'] } if row['IsAlternative?'] == 'True': mship['role'] = 'Alternate Member' if row['IsChairperson?'] == 'True': mship['role'] = 'Chairp...
, mship) return data
GISPPU/GrenadaLandInformation
geonode/people/migrations/0003_link_users_to_account.py
Python
gpl-3.0
10,196
0.007846
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.auth.models import User from account.models import Account class Migration(DataMigration): def forwards(self, orm): # we need to associate each user to an account o...
ttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) },
'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 14, 4, 17, 6, 974570)'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), ...
cirosantilli/python-utils
bin/find_path_sha1.py
Python
mit
2,436
0.010673
#!/usr/bin/env python #------------------------------------------------------------ # # Ciro D. Santilli # # Prints a list of paths which are files followed by their inodes and sha1 s
ums. # # Useful to make a backup of paths names before mass renaming them, # supposing your files are distinct by SHA1 and that SHA1 has not changed, # or that the inodes have not changed. # #------------------------------------------------------------ import os impor
t os.path import stat import hashlib import sys SHA1_MAX_BYTES_READ_DEFAULT = float("inf") # defaults to read entire file def sha1_hex_file(filepath, max_bytes=None): """ Returns the SHA1 of a given filepath in hexadecimal. Opt-args: * max_bytes. If given, reads at most max_bytes bytes from the file...
ylcrow/poweron
src/thirdparty/Ping.py
Python
mit
5,859
0.008875
''' @author: [email protected] A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On...
for i in xrange(count): try: delay = self.do_one(dest_addr, timeout, psize) except socket.gaierror, e: print 'FAILED. (socket error: "%s")' % e[1] break if delay != None: delay
= delay * 1000 plist.append(delay) # Find lost package percent percent_lost = 100 - (len(plist)*100/count) # Find max and avg round trip time if plist: mrtt = max(plist) artt = sum(plist)/len(plist) return percent...
madAsket/levitin_algorithms
src/sieve_eratosphene.py
Python
gpl-3.0
1,323
0.004242
# -*- coding: utf-8 -*- # Алгоритм решето Эратосфена. Нахождение последовательности простых чисел, не превышающе заданной дли
ны. from math import sqrt, floor def sieve(len): # Генерируем массив начальных значен
ий от 2 до len; init_array = [a for a in range(0, len+1)] # 1 - не простое число! init_array[1] = 0 # Идет проход по значениям, не превышающих квадрат len for z in range(2, int(floor(sqrt(len))) + 1): # Элемент еще не удален из начального массива if init_array[z] != 0: # ...
jorge-marques/wagtail
wagtail/wagtailadmin/tests/test_pages_views.py
Python
bsd-3-clause
93,571
0.003377
from datetime import timedelta import unittest import mock from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, Permission from django.core import mail from django.core.paginator import Paginator from ...
response = self.client.get(reverse('wagtailadmin_pages_create', args=('tests', 'standardindex', self.root_page.id))) self.assertEqual(response.status_code, 200) self.assertContains(response, '<a href="#content" class="active">Conte
nt</a>') self.assertNotContains(response, '<a href="#promote" class="">Promote</a>') def test_create_page_with_custom_tabs(self): """ Test that custom edit handlers are rendered """ response = self.client.get(reverse('wagtailadmin_pages_create', args=('tests', 'standardchild...
pastgift/object-checker-py
test/test.py
Python
mit
14,685
0.009465
# -*- coding: utf-8 -*- import unittest from objectchecker import ObjectChecker # Config options = { 'messageTemplate': { 'invalid' : "Value of Field `{{fieldName}}` is not valid. Got `{{fieldValue}}`, but require {{checkerName}} = {{checkerOption}}", 'missing' : "Missing {{fieldName}}", ...
} }; obj = { 'foo': 8 }; self.assertEqual(False, checker.is_valid(obj, opt)) def test_invalid_object_9(self): opt = { 'foo': { '$isInteger': True } }; obj = {
'foo': 'a' }; self.assertEqual(False, checker.is_valid(obj, opt)) def test_invalid_object_10(self): vopt = { 'foo': { '$isPositiveZeroInteger': True } }; obj = { 'foo': -1 }; self.assertEqual(False, checker.is_va...
lifemapper/LmQGIS
lifemapperTools/tools/newExperiment.py
Python
gpl-2.0
17,776
0.024415
# -*- coding: utf-8 -*- """ @author: Jeff Cavner @contact: [email protected] @license: gpl2 @copyright: Copyright (C) 2014, University of Kansas Center for Research Lifemapper Project, lifemapper [at] ku [dot] edu, Biodiversity Institute, 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, US...
EPSG code" valid = False else: self.setMapUnitsFromEPSG(epsg=epsg) if sel
f.mapunits is None or self.mapunits == 'UnknownUnit': message = "Invalid EPSG Code" valid = False if not valid: msgBox = QMessageBox.information(self, "Problem...", message, ...
dexy/cashew
example/usage2.py
Python
mit
581
0.018933
import pprint ### "import" from example.classes import Data ### "plugins" Data.plugins import example.classes2 Data.plugins ### "example-data" example_data = [{ "foo" : 123, "bar" : 456 }] ### "csv-example" csv_data = Data.create_instance('csv', example_data) csv_data.present() csv_data.update_settin...
_header' : False }) csv_data.present() csv_data.setting('lineterminator')
pprint.pprint(csv_data.setting_values()) ### "json-example" json_data = Data.create_instance('json', example_data) json_data.present()
JaredKotoff/100Doors
100Doors.py
Python
mit
3,198
0.002814
import random # Simply picks the winning door at random def door_picker(): winner = random.randrange(1, doors+1) return winner # This opens all the other doors and allows the user to swich or stay def door_opener(choice, winner, switch, enable_auto): if enable_auto == "n": switch = None if cho...
total_games = input("How many games?: ") while keep_playing == "y": choice = "0" if enable_auto == "y": choice = str(random.randrange(1, doors+1)) print("There are 10
0 doors in front of you.\nOne contains a prize.\n") if enable_auto == "n": while not (choice.isdigit() and 0 < int(choice) < doors+1): choice = input("Pick one: ") winner = door_picker() choice, switch = door_opener(int(choice), winner, switch, enable_auto) wi...
homeworkprod/byceps
byceps/permissions/site.py
Python
bsd-3-clause
334
0
""" byceps.permissions.site ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2
021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` fi
le for details) """ from ..util.authorization import create_permission_enum SitePermission = create_permission_enum( 'site', [ 'create', 'update', 'view', ], )
thelabnyc/wagtail_blog
blog/utils.py
Python
apache-2.0
2,644
0.000378
# https://djangosnippets.org/snippets/690/ import re from django.template.defaultfilters import slugify def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): """ Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_nam...
ator with the new separator. """ separator = separator or '' if separator == '-' or not separator: re_sep = '-' else: re_sep = '(?:-|%s)' % re.escape(separator) # Remove multiple instances and if an alternate
separator is provided, # replace the default '-' separator. if separator != re_sep: value = re.sub('%s+' % re_sep, separator, value) # Remove separator from the beginning and end of the slug. if separator: if separator != '-': re_sep = re.escape(separator) value = re....
vecnet/om
website/apps/ts_om/tests/test_run_new.py
Python
mpl-2.0
1,914
0.000522
# -*- coding: utf-8 -*- # # This file is part of the VecNet OpenMalaria Portal. # For copyright and licensing information about this package,
see the # NOTICE.txt and LICENSE.txt files in its top-level directory; they are # available at https://github.com/vecnet/om # # This Source Code Form is subject to the terms of the Mozilla Public # License (MPL), version 2.0. If a copy of the MPL was
not distributed # with this file, You can obtain one at http://mozilla.org/MPL/2.0/. import os from django.test.testcases import TestCase from django.conf import settings import run from website.apps.ts_om.models import Simulation class RunNewTest(TestCase): def test_failure(self): simulation = Simulati...
petersterling1/poke-qr-viewer
main/migrations/0005_auto_20161129_1044.py
Python
gpl-3.0
633
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-29 10:44 fr
om __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Mig
ration): dependencies = [ ('main', '0004_auto_20161129_0947'), ] operations = [ migrations.AlterField( model_name='pokemon', name='qr_code', field=models.TextField(default=''), ), migrations.AlterField( model_name='pokemon', ...
paoloRais/lightfm
examples/movielens/data.py
Python
apache-2.0
3,559
0.000281
import itertools import os import zipfile import numpy as np import requests import scipy.sparse as sp def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip') def _download...
continue uid, iid, rating, timestamp = [int(x) for x in line.split('\t')] yield uid, iid, rating, timestamp def _build_interaction_matrix(rows, cols, data): """ Build the training matrix (no_users, no_items), with ratings >= 4.0 being marked as positive and the rest as negative. ...
mat[uid, iid] = -1.0 return mat.tocoo() def _get_movie_raw_metadata(): """ Get raw lines of the genre file. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return datafile.read('ml-100k/u...
rogst/drainomote
drainomote/views.py
Python
gpl-3.0
115
0
from django.shortc
uts import render, redirect def index(request):
return redirect('status/', permanent=True)
tweemeterjop/thug
thug/DOM/W3C/HTML/TAnimateColor.py
Python
gpl-2.0
948
0.005274
#!/usr/bin/env python import string import logging from .HTMLElement import HTMLElement log = logging.getLogger("Thug") class TAnimateColor(HTMLElement): def __init__(self, doc, tag): self.doc = doc self.tag = tag self._values = "" def get_values(self): return self._values ...
"Microsoft Internet Explorer", "Microsoft Internet Explorer CButton Object Use-After-Free Vulnerability (CVE-2012-4792)", cve = 'CVE-2012-4792', forward = True) log....
self._values = values values = property(get_values, set_values)
zstackio/zstack-woodpecker
integrationtest/vm/virtualrouter/scheduler/test_delete_local_backupstorage.py
Python
apache-2.0
5,456
0.003116
import zstackwoodpecker.operations.scheduler_operations as sch_ops import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.tag_operations as tag_ops import zstackwoodpecker.operations.backupstorage_operations as bs_ops import zstackwoodpecker.test_lib as test_lib import zsta...
cleanup(): global job1,job2,job_group,trigger1,trigger2 test_lib.lib_error_cleanup(test_obj_dict) if job1: sch_ops.del_scheduler_job(job1.uuid) if job2: sch_ops.del_scheduler_job(job2.uuid) if job_group: sch_ops.del_scheduler_job_group(job_group.uuid) if trigger1: ...
igger(trigger1.uuid) if trigger2: sch_ops.del_scheduler_trigger(trigger2.uuid)
ppwwyyxx/tensorflow
tensorflow/python/training/checkpoint_utils.py
Python
apache-2.0
19,434
0.005557
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache
.org/licenses/LICENSE-2.0 # # Unless required by applicable law
or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ======================================...
guillemborrell/Thermopy
test/test_iapws.py
Python
bsd-3-clause
9,460
0.00222
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 09:29:56 2015 @author: monteiro """ from thermopy.iapws import Water from thermopy.units import Pressure, Temperature def test_iapws(): """ Tests are given inside the IAPWS document. See references for more details. """ #test Tsat given P assert r...
alpy(),6) == 184.142828 # assert round(Water(3e6, 500).enthalpy(),6) == 975.542239 # #assert speed of sound assert round(Water(3e6, 300, massic_basis=True).speed_of_sound(),
5) == 1507.73921 assert round(Water(80e6, 300, massic_basis=True).speed_of_sound(), 5) == 1634.69054 assert round(Water(3e6, 500, massic_basis=True).speed_of_sound(), 5) == 1240.71337 #region 2 #assert specific volume assert round(Water(3500, 300, mas...
faust64/ansible
lib/ansible/modules/windows/win_robocopy.py
Python
gpl-3.0
4,902
0.00204
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Corwin Brown <[email protected]> # # This file is part of Ansible # # Ansible 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 Lic...
by': 'community', 'version': '1.0'} DOCUMENTATION = r''' --- module: win_roboc
opy version_added: "2.2" short_description: Synchronizes the contents of two directories using Robocopy. description: - Synchronizes the contents of two directories on the remote machine. Under the hood this just calls out to RoboCopy, since that should be available on most modern Windows Systems. options: src: ...
MPI-IS/bilateralNN
bilateralnn_code/examples/tile_segmentation/predict.py
Python
bsd-3-clause
710
0.002817
import numpy as np from config import * from get_tile_data import get_tile_data from compute_accuracy_iou import compute_accuracy_and_iou [test_x, test_y] = get_tile_data(NUM_DATA['TEST'], RAND_SEED['TEST']) def predict(prototxt, caffe_model): net = caffe.Net(prototxt, caffe_model, caffe.TEST) dinputs = {} ...
ward_all(**dinputs)['conv_result'] [accuracy, iou] = compute_accuracy_and_iou(p
redictions, test_y) print([accuracy, iou]) return [accuracy, iou] if __name__ == '__main__': if len(sys.argv) < 3: print('Usage: ' + sys.argv[0] + ' <prototxt> <caffe_model>') else: predict(sys.argv[1], sys.argv[2])
timmyshen/Guide_To_Data_Mining
Chapter2/SharpenYourPencil/distance.py
Python
mit
4,916
0.003662
__author__ = 'Benqing' users = { "Angelica": {"Blues Traveler": 3.5, "Broken Bells": 2.0, "Norah Jones": 4.5, "Phoenix": 5.0, "Slightly Stoopid": 1.5, "The Strokes": 2.5, "Vampire Weekend": 2.0}, "Bill": {"Blues Traveler": 2.0, "Broken Bells": 3.5, "Deadmau5": 4.0, "Phoenix": 2.0, "Slightly St...
for user in users_in: if user != username: distance = minkowski_dist(users_in[user], users_in[username], 2) distances.append((distance, user)) # sort based on distance -- closest first distances.sort() return distances def pearson(user_ratings1, user_ratings2): """...
0 # This actually could happen # if vals1_len != vals2_len: # exit() sum_of_products = 0.0 sum_of_user1 = 0.0 sum_of_user2 = 0.0 sum_of_user1_sqr = 0.0 sum_of_user2_sqr = 0.0 for k in user_ratings1: if k in user_ratings2: sum_of_products += user_ratings1[k]...
slashdd/sos
sos/report/plugins/mpt.py
Python
gpl-2.0
732
0
# Copyright (C) 2015 Red Hat, Inc., Bryn M. Reeves <[email protected]>
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distributio...
chnology' files = ('/proc/mpt',) profiles = ('storage', ) plugin_name = 'mpt' def setup(self): self.add_copy_spec("/proc/mpt") # vim: set et ts=4 sw=4 :
shizeeg/pyicqt
src/debug.py
Python
gpl-2.0
3,058
0.039568
# Copyright 2004-2006 Daniel Henninger <[email protected]> # Licensed for distribution under the GPL version 2, check COPYING for details from twisted.python import log import sys, time import config def observer(eventDict): try: observer2(eventDict) except Exception, e: printf("CRITICAL: Traceback in debug....
entDict['isError'] and eventDict.has_key('failur
e'): if config.debugLevel < 1: return text = eventDict['failure'].getTraceback() elif eventDict.has_key('format'): if config.debugLevel < 3: return text = eventDict['format'] % eventDict else: return # Now log it! timeStr = time.strftime("[%Y-%m-%d %H:%M:%S]", time.localtime(eventDict['time'])) ...
nkgilley/home-assistant
tests/components/atag/test_init.py
Python
apache-2.0
1,472
0.000679
"""Tests for the ATAG integration.""" import aiohttp from homeassistant.components.atag import DOMAIN from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.components.atag import init_integration from tests.test_util...
pClientMocker ) -> None: """Test configuration entry not ready on library error.""" aioclient_mock.get("http://127.0.0.1:10000/retrieve", exc=aiohttp.ClientError) entry = await init_integration(hass, aioclient_mock) assert entry.state == ENTRY_STATE_SETUP_RETRY async def test_config_entry_empty_reply(...
eady when library returns False.""" with patch("pyatag.AtagOne.update", return_value=False): entry = await init_integration(hass, aioclient_mock) assert entry.state == ENTRY_STATE_SETUP_RETRY async def test_unload_config_entry( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None...
YannickJadoul/Parselmouth
tests/resource_fixtures.py
Python
gpl-3.0
1,735
0.006916
# Copyright (C) 2018-2022 Yannick Jadoul # # This file is part of Parselmouth. # # Parselmouth 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 ...
spectrogram(sound): yield sound.to_spectrogram() @combined_fixture('intensity', 'pitch', 'spectrogram', 'sound') def sampled(request): yield request.param @combined_fixture('sampled') def thing(request): yield request.param @pytest.fixture def text
_grid_path(resources): yield resources["the_north_wind_and_the_sun.TextGrid"] @pytest.fixture def text_grid(text_grid_path): yield parselmouth.read(text_grid_path) @pytest.fixture def script_path(resources): yield resources["script.praat"]
otron/zenodo
zenodo/shell.py
Python
gpl-3.0
3,274
0
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2012, 2013, 2014, 2015 CERN. # # Zenodo 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 o...
e, \ DepositionStorage, DepositionType from invenio.modules.formatter import format_record from invenio.modu
les.pidstore.models import PersistentIdentifier from invenio.modules.pidstore.tasks import datacite_delete, \ datacite_register, datacite_sync, datacite_update from invenio.modules.records.api import get_record from invenio.utils.serializers import ZlibPickle as Serializer from zenodo.modules.deposit.workflows.uplo...
laborautonomo/opps
opps/core/__init__.py
Python
mit
4,511
0
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from appconf import AppConf trans_app_label = _('Core') class OppsCoreConf(AppConf): DEFAULT_URLS = ('127.0.0.1', 'localhost',) SHORT = 'googl' SHORT_URL = 'googl.short.GooglUrlShort' CHANNEL_CONF = {} VIEWS_LIMIT =...
e para visualizar a home page do site' }, ] } ] SHORTCUTS_SETTINGS = { 'hide_app_list': True, 'open_new_window': False, } SHORTCUTS_CLASS_MAPPINGS_EXTRA = [ ('blogs_blogpost', 'blog') ] class Meta: prefix = 'ADMIN' class St...
f(AppConf): CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', } } class Meta: prefix = 'haystack' class ThumborConf(AppConf): SERVER = 'http://localhost:8888' MEDIA_URL = 'http://localhost:8000/media' SECURITY_KEY = '' ...
WING-NUS/corpSearch
mongo.py
Python
lgpl-3.0
56
0
from pymongo import MongoCl
ient client = Mong
oClient()
dillmann/rscs
lib/DeviceManager.py
Python
mit
1,683
0.026738
# author: brian dillmann # for rscs from Devices.Input import Input from Devices.Timer import Timer from Devices.AnalogInput import AnalogInput from Devic
es.Output import Output class DeviceManager: def __init__(self): self.inputs
= {} self.outputs = {} def addSimpleInput(self, name, location, invert = False): if name in self.inputs: raise KeyError('Cannot create device with name %s because input with that name already exists' % name) self.inputs[name] = Input(name, location, invert) def addTimer(self, name, interval = 's'): if na...
openstack/murano
murano/policy/modify/actions/action_manager.py
Python
apache-2.0
3,403
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 re...
cted action spec format is ' '"action-name: {{p1: v1, ...}}" ' 'but got "{action_spec}"' .format(action_spec=action_spec)) for name, kwargs in actions.items(): LOG.debug('Executing action {name}, params {params}' ...
# loads action class action_class = self.load_action(name) # creates action instance action_instance = action_class(**kwargs) # apply action on object model action_instance.modify(obj)
namgivu/shared-model-FlaskSqlAlchemy-vs-SQLAlchemy
python-app/model/user.py
Python
gpl-3.0
1,292
0.026316
from base_model import BaseModel import sqlalchemy as db class User(BaseModel): #table mapping __tablename__ = "users" ##region column mapping id = db.Column(db.Integer, primary_key=True) user_name = db.Column(db.Te
xt) primary_email_id = db.Column(db.Integer, db.ForeignKey('user_emails.id') ) #Use model class instead of physical table name for
db.ForeignKey() ref. http://stackoverflow.com/a/41633052/248616 from model.address import Address billing_address_id = db.Column(db.Integer, db.ForeignKey(Address.__table__.c['id'] )) shipping_address_id = db.Column(db.Integer, db.ForeignKey(Address.__table__.c['id'] )) ##endregion column mapping ##region ...
ngokevin/cyder
cyder/core/cyuser/models.py
Python
bsd-3-clause
730
0.00274
from django.contrib.auth.models import User from django.db i
mport models from django.db.models import signals from cyder.core.cyuser import backends from cyder.core.ctnr.models import Ctnr class UserProfile(models.Model): user = models.OneToOneField(User) default_ctnr = models.ForeignKey(Ctnr, default=2) phone_number = models.IntegerFi
eld(null=True) has_perm = backends.has_perm class Meta: db_table = 'auth_user_profile' def create_user_profile(sender, **kwargs): user = kwargs['instance'] if (kwargs.get('created', True) and not kwargs.get('raw', False)): profile = UserProfile(user=user) profile.save() si...
astanin/python-tabulate
test/test_regression.py
Python
mit
16,317
0.000741
# -*- coding: utf-8 -*- """Regression tests.""" from __future__ import print_function from __future__ import unicode_literals from tabulate import tabulate, _text_type, _long_type, TableFormat, Line, DataRow from common import assert_equal, assert_in, skip def test_ansi_color_in_table_cells(): "Regression: ANSI...
] ) print("expected: %r\n\ngot: %r\n" % (expected, formatted)) assert_equal(expected, formatted) def test_alignment_of_link_cells(): "Regression: Align links as if they were colorless." linktable = [ ("test", 42, "\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\"), ("test", 101, ...
d = tabulate(linktable, linkheaders, "grid") expected = "\n".join( [ "+--------+--------+--------+", "| test | \x1b]8;;target\x1b\\test\x1b]8;;\x1b\\ | test |", "+========+========+========+", "| test | 42 | \x1b]8;;target\x1b\\test\x1b]8;;\x1b\\ ...
marchon/Debug-Dokku.alt-Mongodb-Flask-Python
todo.py
Python
mit
2,262
0.014147
from datetime import datetime from flask import Flask, request, render_template, redirect, url_for from flask.ext.mongokit import MongoKit, Document, Connection import os app = Flask(__name__) class Task(Document): __collection__ = 'tasks' structure = { 'title': unicode, 'text': unicode, ...
_not_found.html',d=d) """ @app.route('/<ObjectId:task_id>') def show_task(task_id): task = db
.Task.get_from_id(task_id) return render_template('task.html', task=task) @app.route('/new', methods=["GET", "POST"]) def new_task(): if request.method == 'POST': try: task = db.Task() asdf except Exception, e: error = {} error['error'] = e.message ...
dwinings/promptool
preferences.py
Python
gpl-3.0
3,585
0.006974
# promptool - A tool to create prompts for POSIX shells, written in python and GTK # Copyright (C) 2011 - David Winings # # promptool 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 Found- # ation, either version 3 of...
"Reset text color after prompt") self.fg_reset_toggle.active = se
lf.pref_global.text_reset def toggle_handler(widget, data=None): self.pref_local.text_reset = self.fg_reset_toggle.get_active() print self.pref_local.text_reset self.fg_reset_toggle.connect('toggled', toggle_handler) self.fg_reset_toggle.show() return self.fg_rese...
mburgs/asanorm
asana/entities/entity.py
Python
apache-2.0
6,721
0.031394
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re class EntityException(Exception): """Wrap entity specific errors""" pass class Entity(object): """Base implementation for an Asana entity containing common funcitonality""" # Keys which are filtered as part of the HTTP request _filter_k...
he assumption is if there is no ID set this is a creation request """ if self.id: return self._do_update() else: #performing create - post return self._do_create
() def _do_update(self): data = {} for key in self._dirty: data[key] = self._data[key] if not data: return return self._get_api().put(self._get_item_url(), data=data) def _do_create(self): return self._init(self._get_api().post(self._get_api_endpoint(), data=self._data)) def delete(self): """...
mick-d/nipype_source
nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py
Python
bsd-3-clause
2,420
0.032645
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.camino.convert import AnalyzeHeader def test_AnalyzeHeader_inputs(): input_map = dict(args=dict(argstr='%s', ), cen
tre=dict(argstr='-centre %s', units='mm', ), data_dims=dict(argstr='-datadims %s', units='voxels', ), datatype=dict(argstr='-data
type %s', mandatory=True, ), description=dict(argstr='-description %s', ), environ=dict(nohash=True, usedefault=True, ), greylevels=dict(argstr='-gl %s', units='NA', ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='< %s', mandator...
PhonologicalCorpusTools/PyAnnotationGraph
polyglotdb/utils.py
Python
mit
1,770
0.001695
from contextlib import contextmanager import sys from . import CorpusContext from .client.client import PGDBClient, ClientError, ConnectionError def get_corpora_list(config): with CorpusContext(config) as c: statement = '''MATCH (n:Corpus) RETURN n.name as name ORDER BY name''' results = c.execute...
tatement) return [x['name'] for x in res
ults] @contextmanager def ensure_local_database_running(database_name, port=None, token=None): if port is None: port = 8080 host = 'http://localhost:{}'.format(port) client = PGDBClient(host, token=token) databases = client.list_databases() try: response = client.create_database(...
cdondrup/strands_qsr_lib
qsr_lib/src/qsrlib_qsrs/qsr_rcc8.py
Python
mit
1,237
0.003234
# -*- coding: utf-8 -*- from __future__ import print_function, division from qsrlib_qsrs.qsr_rcc_abstractclass import QSR_RCC_Abstractclass class QSR_RCC8(QSR_RCC_Abstractclass): """Symmetrical RCC5 relations. Values of the abstract properties * **_unique_id** = "rcc8" * **_all_possible_relat...
possible relations of the QSR.""" def __init__(self): """Constructor.""" super(QSR_RCC8, self).__init__() def _convert_to_req
uested_rcc_type(self, qsr): """No need for remapping. :param qsr: RCC8 value. :type qsr: str :return: RCC8 value. :rtype: str """ return qsr
fuzhouch/amberalertcn
server/amberalertcn/api/__init__.py
Python
bsd-3-clause
47
0.021277
#!/usr
/bin/env python # -*- cod
ing: utf-8 -*_
asridharan/dcos
packages/dcos-history/extra/history/statebuffer.py
Python
apache-2.0
6,354
0.001731
import json import logging import os import threading from collections import deque from datetime import datetime, timedelta from typing import Optional import requests logging.getLogger('requests.packages.urllib3').setLevel(logging.WARN) FETCH_PERIOD = 2 FILE_EXT = '.state-summary.json' STATE_SUMMARY_URI = os.gete...
init__(self, buffer_dir): self.buffers = { 'minute': Histor
yBuffer(60, 2, path=buffer_dir + '/minute'), 'hour': HistoryBuffer(60 * 60, 60, path=buffer_dir + '/hour'), 'last': HistoryBuffer(FETCH_PERIOD, FETCH_PERIOD)} def dump(self, name): return self.buffers[name].dump() def add_data(self, timestamp, data): for buf in self.buf...
pythonindia/junction
junction/conferences/migrations/0009_conferenceproposalreviewer_nick.py
Python
mit
534
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("conferences", "0008_auto_20150601_1436"), ] operations = [ migrations.AddField( model_name="confe
renceproposalreviewer",
name="nick", field=models.CharField( default="Reviewer", max_length=255, verbose_name="Nick Name" ), preserve_default=True, ), ]
tomsilver/nupic
examples/network/network_api_demo.py
Python
gpl-3.0
7,557
0.009528
#!/usr/bin/env python # ---------------------------------------------------------------------- # 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 ...
n.setParameter("learningMode", True) # We want temporal anomalies so disable anomalyMode in the SP. This mode is # used for computing anomalies in a non-temporal model. spatialPoolerRegion.setParameter("anomalyMode", False) temporalPoolerRegion = network.regions["temporalPoolerRegion"] # Enable topDownMode ...
ing is enabled (this is the default) temporalPoolerRegion.setParameter("learningMode", True) # Enable inference mode so we get predictions temporalPoolerRegion.setParameter("inferenceMode", True) # Enable anomalyMode to compute the anomaly score. This actually doesn't work # now so doesn't matter. We instead ...
nlloyd/SubliminalCollaborator
libs/twisted/test/test_randbytes.py
Python
apache-2.0
3,309
0.003022
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases for L{twisted.python.randbytes}. """ import os from twisted.trial import unittest from twisted.python import randbytes class SecureRandomTestCaseBase(object): """ Base class for secureRandom test cases. """ def...
.factory.secureRandom, 18) def wrapper(): return self.factory.secureRandom(18, fallback=True) s = self.assertWarns( RuntimeWarning, "urandom unavailable - " "proceeding with non-cryptographically secure random source", __file__, wra...
ndom test cases. """ def test_normal(self): """ Test basic case. """ self._check(randbytes.insecureRandom) def test_withoutGetrandbits(self): """ Test C{insecureRandom} without C{random.getrandbits}. """ factory = randbytes.RandomFactory() ...
mykespb/pythoner
quicksorts.py
Python
apache-2.0
1,354
0.008124
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # quicksorts.py (C) myke, 2015 # 2015-11-08 1.1 # various versions of quicksort alogo import random TIMES = 10 SIZE = 10 RANGE = 10 # ----------------------------------------------- def qs1 (al): """ Algo quicksort for a list """ if not al: return ...
------------------------------ def main (): """ dispatcher: tests make and sort """ for i in range(TIMES): sa = [random.randi
nt(1, RANGE) for e in range(SIZE)] print (sa, "-->", qs (sa)) main() # ----------------------------------------------- # used: http://stackoverflow.com/questions/18262306/quick-sort-with-python
britny/djangocms-blog
djangocms_blog/admin.py
Python
bsd-3-clause
5,791
0.000691
# -*- coding: utf-8 -*- from copy import deepcopy from cms.admin.placeholderadmin import FrontendEditableAdminMixin, \ PlaceholderAdminMixin from django import forms from django.conf import settings from django.contrib import admin from django.contrib.auth import get_user_model from parler.admin import Translatable...
l', 'main_image_full'),), 'classes': ('collapse',) }), ('SEO', { 'fields': [('meta_description', 'meta_
title', 'meta_keywords')], 'classes': ('collapse',) }), ] def formfield_for_dbfield(self, db_field, **kwargs): field = super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'meta_description': original_attrs = field.widget.attrs ...
Alexx-G/tastypie-example
src/config/urls.py
Python
mit
771
0
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings apipatterns = [ url(r'^', include('cars.api.urls')), ] urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url( r'^manufacturer/', include('man...
from django.conf.url
s.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
freshplanet/AppEngine-Counter
counter/views.py
Python
apache-2.0
1,493
0.004019
# -*- coding: utf-8 -*- ''' Copyright 2014 FreshPlanet (http://freshplanet.com | [email protected]) 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/L...
implied. See the Licen
se for the specific language governing permissions and limitations under the License. ''' import datetime import random from google.appengine.ext import ndb import webapp2 from counter.models import Counter class SampleHandler(webapp2.RequestHandler): @ndb.toplevel def get(self): """ In...
akshayka/bft2f
start_client.py
Python
gpl-2.0
10,155
0.006302
import sys, glob sys.path.append('gen-py') from auth_service import Auth_Service from auth_service.ttypes import * from bft2f_pb2 import * from argparse import ArgumentParser from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from time import sleep, time from Crypto.PublicKey...
for rep in reps: sign_in_certs.append(Sign_In_Cert(node_pub_key=rep.res.sign_in_cert.node_pub_key, sig=rep.res.sign_in_cert.sig)) return Auth_Service_Sign_In_Res(status=Auth_Service_Res_Status.Success, user_id=use...
enc=reps[0].res.user_priv_key_enc, sign_in_certs=sign_in_certs) def sign_up(self, user_id, user_pub_key, user_priv_key_enc): req_id = user_id USER_REQUESTS[req_id] = [threading.Event(), [], False] # Make a call to bft2f twisted_client.bft2f_si...
kobtea/gof
strategy.py
Python
mit
2,642
0
#!/usr/bin/env python import random class WinningStrategy: def __init__(self): self.won =
False self.prev_hand = 0 def next_hand(self): if not self.won: self.prev_hand = random.randint(0, 2) return self.prev_hand def study(self, is_win): self.won = is_win class ProbStrategy: def __init__(self): self.prev_ha
nd = 0 self.curr_hand = 0 # history[previous_hand][current_hand] = won_size self.history = [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] def next_hand(self): bet = random.randint(0, sum(self.history[self.prev_hand])) if bet < self.history[se...
elifesciences/builder
src/buildvars.py
Python
mit
6,259
0.004474
from buildercore.bvars import encode_bvars, read_from_current_host from buildercore.command import remote_sudo, upload from io import StringIO from decorators import requires_aws_stack from buildercore.config import BOOTSTRAP_USER from buildercore.core import stack_all_ec2_nodes, current_node_id from buildercore.contex...
def _fix_single_ec2_node(stackname): LOG.info("checking build vars on node %s", current_node_id()) try: buildvars = _retrieve_build_vars() LOG.info("valid bvars found, no fix necessary: %s", buildvars) return except AssertionError: LOG.info("inv...
) except (ValueError, JSONDecodeError): LOG.info("bad JSON data found, regenerating from context") context = load_context(stackname) # some contexts are missing stackname context['stackname'] = stackname node_id = current_node_id() new_vars = trop.build_vars(...
jmhal/elastichpc
beta/trials/evolving/System.py
Python
mit
1,945
0.028792
#!/usr/bin/python import ctypes import sys import logging from multiprocessing import Process, Pipe, Value, Manager, Lock from Platform import platform_unit as platform_unit from Computation import computation_unit as computation_unit # configure logging logging.basicConfig(filename='computational_system.log',level...
d(["sensors"]) return self.computation_conn.recv() if __name__ == "__ma
in__": # The information of the virtual cluster url = sys.argv[1] stack_name = sys.argv[2] stack_id = sys.argv[3] computation_input = sys.argv[4] # A port for communication between components reconfiguration_port = ReconfigurationPort() log("Starting Platform.") platform = Process(target =...
schilduil/suapp
suapp/simple_json.py
Python
mit
2,757
0.000363
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from pony.orm.core import Entity, SetInstance, Required, Optional import suapp.orm __all__ = ["to_json", "dumps"] def to_json(object_to_serialize): """ Adding simple serialization for objects. If standard json.dumps fails and it is a real ob...
["_pk_"] = object_to_serialize._pk_ # result['__str__'] = "%s" % (object_to_serialize) # Checking for foreign keys for column, value in result.items(): if isinstance(value, Entity): value = value._pk_ # Setting it # If is a Set or tuple it will be set again below....
if isinstance(value, SetInstance): # An empty dictonary signals a Set. result[column] = {} elif isinstance(value, tuple): # On json a tuple = list, so might as well use a list. converted_tuple = [] for subvalue in value: # Finding...
galbramc/gpkit
gpkit/posyarray.py
Python
mit
7,110
0.000563
# -*coding: utf-8 -*- """Module for creating PosyArray instances. Example ------- >>> x = gpkit.Monomial('x') >>> px = gpkit.PosyArray([1, x, x**2]) """ import numpy as np from .small_classes import Numbers from . import units as ureg from . import DimensionalityError Quantity = ureg.Quantity clas...
else: return str(self.flatten()[0]) def __hash__(self): return getattr(self, "_hashvalue", hash(self.tostring())) def __new__(cls, input
_array): "Constructor. Required for objects inheriting from np.ndarray." # Input array is an already formed ndarray instance # cast to be our class type obj = np.asarray(input_array).view(cls) return obj def __array_finalize__(self, obj): "Finalizer. Required for obj...
w01230/test
python/numpy/np_index2.py
Python
gpl-3.0
197
0
# -*- coding: utf-8 -*- imp
ort numpy as np x = np.array([3, 2, 1, 0]) print(x[[0, 1, 2]]) print(x
[[-1, -2, -3]]) y = np.array([[1, 2], [3, 4], [5, 6]]) print(y[[0, 1]]) print(y[[0, 1], [0, 1]])
OCA/partner-contact
partner_address_street3/hooks.py
Python
agpl-3.0
919
0
# Copyright 2016-2020 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). def post_init_hook(cr, registry): """ Add street3 to address format """ query = """ UPDATE res_country SET address_format = replace( address_format, E'%(street2)s\n', E'%(stree...
ll_hook(cr, registry): """ Remove street3 from address format """ # Remove %(street3)s\n from address_format query = """ UPDATE r
es_country SET address_format = replace( address_format, E'%(street3)s\n', '' ) """ cr.execute(query) # Remove %(street3)s from address_format query = """ UPDATE res_country SET address_format = replace( address_format, E'%(street3...
atantet/transferPlasim
statistics/plotIndices.py
Python
gpl-2.0
4,841
0.005784
import os import numpy as np from scipy import stats import matplotlib.pyplot as plt from matplotlib import cm import atmath # Define the observable srcDir = '../runPlasim/postprocessor/indices/' # SRng = np.array([1260, 1360, 1380, 1400, 1415, 1425, 1430, 1433, # 1263, 1265, 1270, 1280, 1300, 1330, ...
ve spinup period from time-series spinup = spinupYears * daysPerYear sampFreq = 1 # (days^{-1}) # Plot settings fs_default = 'x-large' fs_latex = 'xx-large' fs_xlabel = fs_default fs_ylabel = fs_default fs_xticklabels = fs_default fs_yticklabels = fs_default fs_legend_title = fs_default fs_legend_labels = fs_default f...
) skewRng = np.empty((SRng.shape[0],)) kurtRng = np.empty((SRng.shape[0],)) lagMax = 80 #lagMax = daysPerYear * 5 ccfRng = np.empty((SRng.shape[0], lagMax*2+1)) for k in np.arange(SRng.shape[0]): S = SRng[k] restartState = restartStateRng[k] # Create directories resDir = '%s_%s/' % (restartState, S) ...
V3ckt0r/Quickspin
Quickspin/quickspin.py
Python
lgpl-3.0
8,275
0.005317
#! /usr/bin/python import boto3 import argparse import sys import inspect import getpass import os.path import time from os.path import expanduser # Set up acceptable arguments def create_parser(): parser = argparse.ArgumentParser() parser.add_argument("-u","--up", nargs='+', help="List of EC2 ids to bring up...
DryRun" # Bring down from a
list of instances ids def downIt(instance_list, DryRun=False): client = boto3.client('ec2') try: response = client.stop_instances( InstanceIds=instance_list, Force=False, DryRun=DryRun) responseCheck(response) except boto3.exceptions.botocore.exceptions.ClientError: print "Instances ...
CCS-Lab/hBayesDM
Python/tests/test_gng_m3.py
Python
gpl-3.0
198
0
import pytest from hbayesdm.models import gng_m3 def test_gng_m3(): _ = gng_m3( da
ta="example", niter=10, nwarmup
=5, nchain=1, ncore=1) if __name__ == '__main__': pytest.main()
ProjectALTAIR/Simulation
mdp/tm.py
Python
gpl-2.0
825
0.024242
""" The Transition Model. Init: State object with information about current location & ground velocity, the action which will be taken, and an environment object containing wind information and simulation parameters. This is done as an object so that multiple models may be used at the s
ame time for reinforcement learning techniques. For example, learning the true environment given an approximation. The AI could learn from a predicted weather environment, but the tm could uses the real data. """ class Tm: def __init__(self,state,action,environment): """ update() computes the n+1 state and upda...
ef update(self,state,action,environment): return state
grimfang/panda3d
direct/src/wxwidgets/WxPandaShell.py
Python
bsd-3-clause
9,624
0.010183
import wx from wx.lib.agw import fourwaysplitter as FWS from panda3d.core import * from direct.showbase.ShowBase import * from direct.directtools.DirectGlobals import * try: base except NameError: base = ShowBase(False, windowType = 'none') from .WxAppShell import * from .ViewPort import * ID_FOUR_VIEW = 40...
["_le_lef_%s"%x for x in base.direct.mouseEvents] +\ ["_le_top_%s"%x for x in base.direct.mouseEvents] base.direct.mouseEvents = newMouseEvents base.direct.enableMouseEvents() base.direct.disableKeyEvents() keyEvents ...
ase.direct.keyEvents] +\ ["_le_fro_%s"%x for x in base.direct.keyEvents] +\ ["_le_lef_%s"%x for x in base.direct.keyEvents] +\ ["_le_top_%s"%x for x in base.direct.keyEvents] base.direct.keyEvents = keyEvents ...
nebw/cgt
cgt/core.py
Python
mit
122,515
0.013329
import sys, numpy as np, hashlib, copy, cPickle, ctypes, os, os.path as osp from collections import defaultdict,namedtuple import __builtin__ import traceback import cgt from . import utils # ================================================================ # Datatypes # ================================================...
Output type of a floating point operation involving these input types """ d1 = typ1[0] s1 = typ1[1:] d2 = typ2[0] s2 = typ2[1:] if d1 == 'c' or d2 == 'c': return cgt.complexX elif d1 == 'f' or d2 == 'f': return cgt.floatX elif d1
== 'i' and d2 == 'i': assert d1 == d2 return d1 + __builtin__.max(s1,s2) else: raise ValueError("Don't know what to do with dtypes %s,%s"%(typ1, typ2)) def _promote_multi(xtypes): """ _promote with multiple operands """ return reduce(_promote, xtypes) def dtype_kind(dtype):...
sotlampr/theano-wrapper
tests/test_layers.py
Python
mit
18,340
0
import unittest import numpy as np import theano import theano.tensor as T from tests.helpers import (SimpleTrainer, SimpleClf, SimpleTransformer, simple_reg) from theano_wrapper.layers import (BaseLayer, HiddenLayer, MultiLayerBase, BaseEstimator, BaseTra...
den_layer_has_input(self): base = HiddenLayer(100, 10) self.assertTrue(hasattr(base, 'X')) def test_hidden_layer_input_is_theano_variable(self): base = HiddenLayer(100, 10) self.assertIsInstance(base.X, theano.tensor.TensorVariable) def test_hidden_layer_weights_shape(self): ...
def test_hidden_layer_bias_shape(self): base = HiddenLayer(100, 10) self.assertEqual(base.b.get_value().shape, (10,)) def test_hidden_layer_weights_shape_single_output(self): base = HiddenLayer(100, 1) self.assertEqual(base.W.get_value().shape, (100,)) def test_hidden_layer_bia...
akeym/cyder
cyder/cydhcp/supernet/forms.py
Python
bsd-3-clause
417
0
from dja
ngo import forms from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.supernet.models import Supernet class SupernetForm(forms.ModelForm, UsabilityFormMixin): class Meta: m
odel = Supernet exclude = ('start_lower', 'start_upper', 'end_lower', 'end_upper') widgets = {'ip_type': forms.RadioSelect, 'description': forms.Textarea}
BrainTech/openbci
obci/gui/frontend/main_gui.py
Python
gpl-3.0
4,516
0.005316
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: # Łukasz Polak <[email protected]> # """This is main file for whole GUI part of OpenBCI - main window of whole application, along with loading all needed modules GUIs""" # We are using newer version of QVariant through our GUI, so we might as well # set it...
ctionary self.processModules(MODULES_LIST) # TODO: main gui should be made in designer, and not in code here self.pluginsList = QtGui.QTreeWidget() self.pluginsList.setMaximumWidth(200
) self.pluginsList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.pluginsList.setHeaderLabels(["Nazwa"]) for i_plugin in self.modules.values(): l_item = QtGui.QTreeWidgetItem([i_plugin.name]) l_item.plugin = i_plugin self.pluginsList.addTopLevelItem(l...
schwa-lab/lsh
lsh/hashes.py
Python
mit
2,098
0.025262
#!/usr/bin/python3 import numpy, sys #from test.generate_test_vectors import TestVectorGenerator import pyximport; pyximport.install() from lsh import bits class Projection: def __init__(self, n_bits, n_feats): self.n_bits = n_bits self.n_feats = n_feats self.vectors = numpy.random.randn(se...
f_space |= set(bow.keys()) f_space = filter(lambda x: x, f_space) # remove empty strings # vectors are sparse so we want to lookup into them directly f_space = dict(((v, k) for k, v in enumerate(f_space))) length = len(f_space.keys()) proj = Projection(BITS, length) for id, name, bow in docs: ...
rings, again continue vec[f_space[word]] = count print(id, "{0:064b}".format(proj.hash(vec))) if __name__ == '__main__': #main(int(sys.argv[1])) test_json(sys.argv[1])
OpenACalendar/OpenACalendar-Tools-Social
example-facebook-post-weekly/facebook-post-weekly.py
Python
bsd-3-clause
2,695
0.007421
#!/usr/bin/env python import logging from pdb import set_trace import requests import simplejson from time import time import os import facebook # MY_API_URL # MY_SITE_MSG # MY_GROUP_NAME # POST_TO_ID = None def run(): data = get_from_cal_json() msg = create_msg(data) p
ost(msg) def get_from_cal_json(): print "Getting data from OpenACalendar" r = requests.get(MY_API_URL) if r.status_code != requests.codes
.ok: r.raise_for_status() j = simplejson.loads(r.text) now = time() inaweek = now + 60 * 60 * 24 * 7 data = [ x for x in j['data'] if x['start']['timestamp'] > now and x['start']['timestamp'] < inaweek and not x['deleted'] ] print "Got Data From OpenAC...
enthought/etsproxy
enthought/envisage/developer/developer_plugin.py
Python
bsd-3-clause
104
0
# proxy module fr
om __future__ import absolute_import from envisage.developer.developer_plugin impo
rt *
dchabot/ophyd
examples/scaler.py
Python
bsd-3-clause
1,039
0
import time import config from ophyd import scaler from ophyd.utils import enum ScalerMode = enum(ONE_SHOT=0, AUTO_COUNT=1) loggers = ('ophyd.signal', 'ophyd.scaler', ) config.setup_loggers(loggers) logger = config.logger sca = scaler.EpicsScaler(config.scalers[0]) sca.preset_time.put(5.2, ...
r...') sca.count.put(0) logger.info('Set mode to AutoCount') sca.count_mode.put(ScalerMode.AUTO_COUNT, wait=True) sca.trigger() logger.info('Begin auto-counting (aka "background count
ing")...') time.sleep(2) logger.info('Set mode to OneShot') sca.count_mode.put(ScalerMode.ONE_SHOT, wait=True) time.sleep(1) logger.info('Stopping (aborting) auto-counting.') sca.count.put(0) logger.info('read() all channels in one-shot mode...') vals = sca.read() logger.info(vals) logger.info('sca.channels.get() sho...
oblalex/txinvoke
setup.py
Python
mit
1,351
0
# -*- coding: utf-8 -*- import os from setuptools import setup __here__ = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(__here__, 'README.rst')).read() REQUIREMENTS = [ i.strip() for i in open(os.path.join(__here__, 'require
ments.txt')).readlines() ] # Get VERSION version_file = os.path.join('txinvoke', 'version.py') # Use exec for compabibility with Python 3 exec(open(version_file).read()) setup( name='txinvoke', version=VERSION, description="Run inline callbacks from Twisted as Invoke tasks", long_description=README, ...
thor='Alexander Oblovatniy', author_email='[email protected]', packages=[ 'txinvoke', ], install_requires=REQUIREMENTS, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'License ::...
ufieeehw/IEEE2015
ros/ieee2015_vision/src/object_detection/test_functions/ss_find_button_test.py
Python
gpl-2.0
1,759
0.03809
import cv2 import ss_get_axis_points import math import numpy as np import ss_get_lit_button #now we don't care about what color the button is #just care about location of bright center relative to major axis def find_button(img, mean_cols, mean_rows): #testing cv2.circle(img, (mean_cols, mean_rows), 2, (255, 255, ...
e/right #2 is red/up #3 is gre
en/left #4 is yellow/down if (degs > 0 and degs < 50) or degs > 315: print "we have a blue thing" color = 1 elif degs >= 50 and degs <= 130: color = 2 print "we have a red thing" elif degs >130 and degs <= 225: color = 3 print "we have a green thing" elif degs > 225 and degs <= 315: color = 4 prin...
pyocd/pyOCD
pyocd/cache/register.py
Python
apache-2.0
7,288
0.001921
# pyOCD debugger # Copyright (c) 2016-2020 Arm Limited # SPDX-License-Identifier: Apache-2.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...
he(): return self._context.read_core_registers_raw(reg_list) reg_list = self._convert_and_check_registers(reg_list) reg_set = set(reg_list) # Get list of values we have cached. cached_set = set(r for r in reg_list if r in self._cache) self._metrics.hits += len(cache...
for r in read_list if r in self.CFBP_REGS) reading_xpsr = any(r for r in read_list if r in self.XPSR_REGS) if reading_cfbp: if not self.CFBP_INDEX in read_list: read_list.append(self.CFBP_INDEX) cfbp_index = read_list.index(self.CFBP_INDEX) if reading_xps...
zhaw/Poker-Bot-Reformed
pokerstars/move_catcher.py
Python
mit
10,977
0.006013
from pokerstars.screen_scraper import ScreenScraper from public import map_card_string_to_tuple from public import change_terminal_color import re import time import json import copy class MoveCatcher(): def __init__(self, to_act, game_driver): self.to_act = to_act#{{{ self.game_driver ...
return False return True#}}} def make_even(self): amount = max(self.betting)#
{{{ actions = list() for i in xrange(6): player = (self.to_act+i) % 6 if self.active[player] < 1: continue if self.screen_scraper.has_fold(player): actions.append([player, 'fold']) elif self.betting[player] < max(self.bettin...
OpenELEC/service.openelec.settings
src/service.py
Python
gpl-2.0
4,695
0.002343
################################################################################ # This file is part of OpenELEC - http://www.openelec.tv # Copyright (C) 2009-2017 Stephan Raue ([email protected]) # Copyright (C) 2013 Lutz Fiebach ([email protected]) # # This program is dual-licensed; you can redistri...
'MESSAGE:' + repr(message), 1) conn.close() if message == 'openConfigurationWindow':
if not hasattr(self.oe, 'winOeMain'): threading.Thread(target=self.oe.openConfigurationWindow).start() else: if self.oe.winOeMain.visible != True: threading.Thread(target=self.oe.openConfigurationWindow).start()...
dereneaton/ipyrad
ipyrad/analysis/raxml.py
Python
gpl-3.0
9,380
0.00565
#!/usr/bin/python """ wrapper to make simple calls to raxml """ import os import sys import glob import subprocess from ipyrad.analysis.utils import Params from ipyrad.assemble.utils import IPyradError # alias OPJ = os.path.join class Raxml(object): """ RAxML analysis utility function. This tool makes it ...
(-s seq.phy) The .phy formatted sequence file. o: str or list (-o tax1,tax2) A list of outgroup sample names or a string. Attributes: ----------- params: dict parameters for this raxml run command:
returns the command string to run raxml Functions: ---------- run() submits a raxml job to locally or on an ipyparallel client cluster. """ # init object for params def __init__( self, data, name="test", workdir="analysis-raxml", *a...
jumoconnect/openjumo
jumodjango/etc/func.py
Python
mit
1,840
0.004934
# -*- coding: utf8 -*- import re from unidecode import unidecode import os, sys from hashlib import md5 as hasher import binascii import settings def gen_flattened_list(iterables): for item in iterables: if hasattr(item, '__iter__'): for i in item: yield i else: ...
= re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.;:]+') htmlCodes = ( ('&amp;', '&'), ('&lt;', '<'), ('&gt;', '>'), ('&quot;', '"'), ('&#39;', "'"), ) def escape_html(s): for bad, good in htmlCodes: s = s.replace(bad, good) return s def slugify(text, delim='', lowercase=True): ...
t=text.lower() for word in _punct_re.split(text): decoded = _punct_re.split(unidecode(word)) result.extend(decoded) result = unicode(delim.join(result)) return result.lower() if lowercase else result def salted_hash(val): hash = hasher(settings.CRYPTO_SECRET) hash.update(unicode(va...
Blimeo/Java
out/production/matthew/Contests/CodeForces/pset6/President's Office.py
Python
apache-2.0
684
0.023392
inp = input().split() n = int(inp[0]) m
= int(inp[1]) c = inp[2] k = [] for i in range(n): k.append(list(input())) lt = (-1, -1) rt = (-1, -1) for i in range(n): for j in range(m): if k[i][j] == c: rt = (i, j) if lt[0] < 0: lt = (i, j) ans = set() for i in range(lt[0], rt[0] + 1): for j in range(lt[1], rt[1] + 1): if i > 0 and k[i - 1]...
.add(k[i - 1][j]) if i < n - 1 and k[i + 1][j] != c and k[i + 1][j] != '.': ans.add(k[i + 1][j]) if j > 0 and k[i][j - 1] != c and k[i][j - 1] != '.': ans.add(k[i][j - 1]) if j < m - 1 and k[i][j + 1] != c and k[i][j + 1] != '.': ans.add(k[i - 1][j + 1]) print(len(ans))
mahabuber/erpnext
erpnext/patches/v4_0/split_email_settings.py
Python
agpl-3.0
2,172
0.02302
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): print "WARNING!!!! Email Settings not migrated. Please setup your email again." # this will happen if you are migrating...
autoreply", "support_autoreply"): if isinstance(fieldname, tuple): from_field
name, to_fieldname = fieldname else: from_fieldname = to_fieldname = fieldname support_email_settings.set(to_fieldname, email_settings.get(from_fieldname)) support_email_settings._fix_numeric_types() support_email_settings.save() def get_email_settings(): ret = {} for field, value in frappe.db.sql("select...
OCA/OpenUpgrade
openupgrade_framework/odoo_patch/odoo/addons/base/models/__init__.py
Python
agpl-3.0
48
0
from . imp
ort ir_model from . imp
ort ir_ui_view
plaid/plaid-python
plaid/model/recurring_transaction_frequency.py
Python
mit
7,155
0.000699
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
ter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that ...
discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminat...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/security/cmd/permissions/tasking_dsz.py
Python
unlicense
507
0.009862
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62
211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: tasking_dsz.py import mcl.framework import mcl.tasking class dsz: INTERFACE = 16842801 PFAM = 4169
PROVIDER_ANY = 4169 PROVIDER = 16846921 RPC_INFO_QUERY = mcl.tasking.RpcInfo(mcl.framework.DSZ, [INTERFACE, PROVIDER_ANY, 0]) RPC_INFO_MODIFY = mcl.tasking.RpcInfo(mcl.framework.DSZ, [INTERFACE, PROVIDER_ANY, 1])
mlperf/inference_results_v0.7
open/Inspur/code/rnnt/tensorrt/preprocessing/convert_rnnt_data.py
Python
apache-2.0
11,154
0.004931
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
ne, type=int, help="default is pad to value as specified in model configurations. if -1 pad to maximum duration. If > 0 pad batch to next multiple of value") return parser.parse_args() def eval( data_layer, audio_processor, args): if not os.path.exist
s(args.output_dir): os.makedirs(args.output_dir) if not os.path.exists(args.output_dir + 'fp16'): os.makedirs(args.output_dir + "fp16") if not os.path.exists(args.output_dir + 'fp32'): os.makedirs(args.output_dir + "fp32") if not os.path.exists(args.output_dir + 'int32'): os....
PW-Sat2/PWSat2OBC
integration_tests/emulator/beacon_parser/scrubbing_telemetry_parser.py
Python
agpl-3.0
445
0.002247
from parser import CategoryParser class ScrubbingTelemetryParser(CategoryParser): def __init__(self, reader, store): CategoryParser.__init__(self, '05: Scrubbing State', reader, store) def get_bit_count(self): return 3 + 3 + 32 def parse(self): self.append("Primary Flash Scrubbin...
er", 3) self.app
end_dword("RAM Scrubbing pointer")
disqus/django-old
tests/regressiontests/forms/localflavor/co.py
Python
bsd-3-clause
1,661
0.000602
from django.contrib.localflavor.co.forms import CODepartmentSelect from utils import LocalFlavorTestCase class COLocalFlavorTests(LocalFlavorTestC
ase): def test_CODepartmentSelect(self):
d = CODepartmentSelect() out = u"""<select name="department"> <option value="AMA">Amazonas</option> <option value="ANT">Antioquia</option> <option value="ARA">Arauca</option> <option value="ATL">Atl\xe1ntico</option> <option value="DC">Bogot\xe1</option> <option value="BOL">Bol\xedvar</option> <option valu...
dev-coop/meancoach
meancoach_project/settings/test.py
Python
mit
136
0
from base im
port * DATABASES = { 'de
fault': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }