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
BeamNG/crashrpt
processing/scripts/basic_stats.py
Python
bsd-3-clause
1,335
0.020225
# This script calculates how many error reports are in each subdirectory # and how many error reports are in total. # Edit in_dir and out_file parameters as you need. import os in_dir = "D:/Projects/CrashRpt/valid_reports" out_file = "stats.txt" f = open(out_file, "w") def get_txt_file_count(dirname): count = 0...
(root, dir) report_count_in_dir = get_txt_file_count(dir_name) if report_count_in_dir in multimap.keys(): multimap[report_count_in_dir].append(dir)
else: multimap[report_count_in_dir] = [dir] ordered_list = list(multimap.keys()) ordered_list.sort() ordered_list.reverse() total_count = 0 total_groups = 0 for count in ordered_list: total_groups += len(multimap[count]); total_count += count * len(multimap[count]) f.write("Total %d reports (100%%) ...
ASzc/nagoya
cfg/koji-builder/setup.py
Python
lgpl-3.0
1,421
0.000704
#!/usr/bin/env python2 # References: # https://fedoraproject.org/wiki/Koji/ServerHowTo # https://github.com/sbadakhc/kojak/blob/master/scripts/install/install import util.cfg as cfg import util.pkg as pkg import util.cred as cred from util.log import log # # Setup # log.info("General update") pkg.clean() pkg.update...
with cfg.mod_ini("/etc/koji.conf") as i: i.koji.server = koji_url["hub"] i.koji.weburl = koji_url["web"] i.koji.topurl = koji_url["top"] i.koji.topdir = "/mnt/koji" i.koji.cert = cred.user["kojiadmin"].pem i.koji.ca = c
red.ca_crt i.koji.serverca = cred.ca_crt pkg.clean()
isaachenrion/jets
src/architectures/nmp/adjacency/__init__.py
Python
bsd-3-clause
399
0.002506
from .simple import SIMPLE_AD
JACENCIES from .combo import ComboAdjacency, LearnedComboAdjacency def construct_adjacency(matrix, **kwargs): if isinstance(matrix, (list,)): if kwargs.get('learned_tradeoff', False): return LearnedComboAdjacency(adj_list=matrix, **kwargs) return ComboAd
jacency(adj_list=matrix, **kwargs) return SIMPLE_ADJACENCIES[matrix](**kwargs)
AutorestCI/azure-sdk-for-python
azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/name_availability.py
Python
mit
1,227
0
# 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 ...
'message': {'key': 'message', 'type': 'str'}, 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, } def __init__(self, message=None, name_available=None, reaso
n=None): self.message = message self.name_available = name_available self.reason = reason
jlazovskis/conditioning
examples/examples-curves-surfaces.py
Python
gpl-3.0
1,355
0.04428
# Name: Examples for using conditioning number finders for curves and surfaces # Description: Contains some examples with descriptions of how to use the functions # Created: 2016-08-18 # Author: Janis Lazovskis # Navigate to the conditioning directory # Run Python 2 # Example (curve) execfile('curves.py') x = variety...
= x0*x1 - x2*x3 x.points = [[1,1
,1,1], [0,1,1,0], [0,1,0,1], [2,1,1,2]] cnumsurface(x) # Non-example (surface) execfile('surfaces.py') x = variety() x0,x1,x2,x3 = sp.var('x0,x1,x2,x3') x.varlist = [x0,x1,x2,x3] x.func = x0*x0*x1 - x2*x3*x3 + x0*x1*x2 +x2*x2*x2 x.points = [[0,1,1,1], [1,0,1,1], [1,0,2,2], [1,1,-1,1]] # This will raise an error becaus...
FR4NK-W/osourced-scion
python/test/lib/path_store_test.py
Python
apache-2.0
22,153
0.000135
# Copyright 2015 ETH Zurich # # 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, sof...
} dict_['BestSetSize'] = "best_set_size" dict_['CandidatesSetSize'] = "candidates_set_size" dict_['HistoryLimit'] = "history_limit" dict_['UpdateAfterNumber'] = "update_after_number" dict_['UpdateAfterTime'] = "update_after_time" dict_['UnwantedASes'] = "1-11,2-12" ...
['PropertyWeights'] = "property_weights" pth_pol2 = PathPolicy() pth_pol2.parse_dict(dict_) ntools.eq_(pth_pol2.best_set_size, "best_set_size") ntools.eq_(pth_pol2.candidates_set_size, "candidates_set_size") ntools.eq_(pth_pol2.history_limit, "history_limit") ntools.eq_(p...
alrusdi/leadwerks-blender-exporter
io_scene_leadwerks/leadwerks/constants.py
Python
gpl-3.0
700
0.001429
# -*- coding: utf-8 -*- MDL_BYTE = 1 MDL_UNSIGNED_BYTE = 2 MDL_SHORT = 3 MDL_UNSIGNED_SHORT = 4 MDL_HALF = 5 MDL_INT = 6 MDL_UNSIGNED_INT = 7 MDL_FLOAT = 8 MDL_DOUBLE = 9 MDL_FILE = 1 MDL_NODE = 2 MDL_MESH = 3 MDL_BONE = 4 MDL_VERTEXARRAY = 5 MDL_INDICEARRAY = 6 MDL_PROPERTIES = 7 MDL_ANIMATIONKEYS = 8 MDL_AABB = 9 M...
ANGENT = 5 MDL_BINORMAL = 6 MDL_BONEINDICE = 7 MDL_BONEWEIGHT = 8 MDL_POINTS = 1 MDL_LINE_STRIP = 2 MDL_LINE_LOOP = 3 MDL_LINES = 4 MDL_TRIANGLE_STRIP = 5 MDL_TRIANGLE_FAN = 6 MDL_TRIANGLES = 7 MDL_QUAD_STRIP = 8 M
DL_QUADS = 9 MDL_POLYGON = 10 MDL_VERSION = 2
genome/dindel-tgi
python/utils/Fasta.py
Python
gpl-3.0
2,034
0.013766
import sys, os class FastaTarget: def __init__(self): self.tid = '' self.len = '' self.offset = -1 self.blen = -1 self.llen = -1 class FastaIndex: def __init__(self, fname=''): self.f = open(fname, 'r') self.ft = {} for line in self.f.readlines(...
["%d" % c for c in range(1,23)] autosomal.extend(['X','Y']) for chrom in autosomal: if chrom in fachr: chromosomes.append(chrom) chromosomes.extend( l
ist (set(fachr) - set(autosomal))) return chromosomes
stifoon/navitia
source/sindri/sindri/saver/edsaver.py
Python
agpl-3.0
4,169
0.000481
# encoding: utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility...
AlchemyError as e: logger.exception('error durring transaction') if not hasattr(e, 'connection_invalidated') \ or not e.connection_invalidated: transaction.rollback() raise TechnicalError('problem with databases: ' + str(e)) except: ...
except: pass raise finally: if conn: conn.close()
ksh/gpirecertification
tools/etl/remote_edited.py
Python
apache-2.0
6,082
0.002466
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
'SERVER_SOFTWARE'] value tha
t indicates we're running under # the test environment. TEST_SERVER_SOFTWARE = 'Test' class Error(Exception): """Base error type.""" class EnvironmentAuthenticationError(Error): """Raised when establishing an environment fails due to bad credentials.""" class Environment(object): """Sets up the execut...
carlochess/proyectoComplejidad
Organizar/segundaParte.py
Python
apache-2.0
4,712
0.004244
from __future__ import print_function from lector import * from lpSolv import * import sys import math def generarRestriccionesTipo(matriz, tipo): numeroRestricciones = (n* (n-1)) / 2 if tipo == 0 or tipo == 1: for j in range(0, n): restriccionCanecaI = [] for k in range(0, i * ...
+= it
ems[i].getPeso() for i in range(len(items)): sumaVolumenes += items[i].getVolumen() pesos = math.ceil(sumaPesos / float(caneca.getPeso())) volumenes = math.ceil(sumaVolumenes / float(caneca.getVolumen())) if(pesos >= volumenes): return pesos else: return volumenes param = (s...
toway/towaymeetups
mba/resources.py
Python
gpl-3.0
34,486
0.008427
# coding: utf-8 import os from UserDict import DictMixin from fnmatch import fnmatch from datetime import datetime from datetime import date import pytz from pyramid.threadlocal import get_current_registry from pyramid.traversal import resource_path from sqlalchemy import Boolean from sqlalchemy import Column from sq...
one: obj = City(name=name) # print 'cannt find city create one' #return cls(city=obj) return obj class UserBetween(Base): city_id
= Column(Integer, ForeignKey('city.id'), primary_key=True) user_id = Column(Integer, ForeignKey('mba_users.id'), primary_key=True) user = relationship("MbaUser", backref=backref("user_between", cascade="all, delete-orphan") ...
Richert/BrainNetworks
CMC/config/AdEx_net.py
Python
apache-2.0
2,934
0.008521
from pyrates.utility import grid_search_annarchy, plot_timeseries from ANNarchy import Projection, Population, TimedArray, setup, Network, Monitor, Uniform, Normal, \ EIF_cond_exp_isfa_ista from pyrates.utility import pyrates_from_annarchy import matplotlib.pyplot as plt import numpy as np # parameters ###########...
post=I, target='exc', name='EI
') C_ie = Projection(pre=I, post=E, target='inh', name='IE') #C_ee = Projection(E, E, 'exc', name='EE') #C_ii = Projection(I, I, 'inh', name='II') C_ei.connect_fixed_probability(0.1, weights=Uniform(c_min, c_max)) C_ie.connect_fixed_probability(0.1, weights=Uniform(c_min, c_max)) #C_ee.connect_fixed_probability(0.3, we...
candywater/ProCon
aoj/volumn5/0532/0532aoj.py
Python
mit
390
0.097436
#python3 ''' ''' imp
ort sys while 1: try: h1,m1,s1,h2,m2,s2=map(int,input().split()) except EOFError: break '''<- this is /* in c/c++ m1=input() s1=input() h2=input() m2=input() s2=input() ''' s1=s2+60-s1 s2=s1%60 s1=s1/60 m1=m2+60-1-m1+s1 m2=m1%60 m1=m1/60 h2=h2-h1-1+m1 #print("d d d"%(h,m,s))...
d'%m2,'%d'%s2)
googleapis/python-aiplatform
samples/generated_samples/aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py
Python
apache-2.0
1,664
0.001803
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1beta1.SuggestTrialsRequest(
parent="parent_value", suggestion_count=1744, client_id="client_id_value", ) # Make the request operation = client.suggest_trials(request=request) print("Waiting for operation to complete...") response = operation.result() # Handle the response print(response) # [END a...
sonnykr/blog
SignUps/views.py
Python
apache-2.0
389
0.010283
from django.shortcuts import render, render_to_response, RequestContext from .forms import SignUpForm
# Create your views here. def home(request): form = SignUpForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() return render_to_response("signup.html", locals(), context_instance=Reque
stContext(request))
ad-m/foundation-manager
foundation/cases/migrations/0002_auto_20160512_1041.py
Python
bsd-3-clause
888
0.002252
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-12 08:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations
.Migration): initial = True dependencies = [ ('cases', '0001_initial'), ('offices', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField(
model_name='case', name='created_by', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='case', name='office', field=models.ForeignKey(on_delete=django...
SpamExperts/SpamPAD
tests/functional/test_plugins/test_header_eval.py
Python
gpl-2.0
87,077
0.002516
#coding:utf8 """Tests the HeaderEval Plugin""" from __future__ import absolute_import import datetime import unittest import tests.util # Load plugin and report matched RULES and SCORE PRE_CONFIG = """ loadplugin Mail::SpamAssassin::Plugin::HeaderEval report _SCORE_ report _TESTS_ """ class TestFunctionalCheckForF...
]) by rly-ip01.mx.aol.com " "(8.8.8/8.8.8/AOL-5.0.0) with ESMTP id NAA08955 for " "<sapient-alumni@yahoogroups.com>; Thu, 4 Apr 2002 13:11:20 " "-0500 (EST)") self.setup_conf(config=config, pre_config=PRE_CONFIG) result = self.check_pad(email) ...
e_aol_relay_in_rcvd()" email = ("Received: by 10.28.54.13 with SMTP id d13csp1785386wma; Mon, " "28 Nov 2016 07:40:07 -0800 (PST)") self.setup_conf(config=config, pre_config=PRE_CONFIG) result = self.check_pad(email) self.check_report(result, 0, []) class TestFuncti...
anandology/pyjamas
library/gwt/ui/VerticalPanel.py
Python
apache-2.0
1,733
0.001731
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # 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/...
ass VerticalPanel(CellPanel): def insert(self, widget, beforeIndex): widget.removeFromParent() tr = DOM.createTR() td = DOM.createTD() DOM.insertChild(self.getBody(), tr, beforeIndex) DOM.appendChild(tr, td) CellPanel.insert(self, widget, td, beforeIndex) ...
f.setCellHorizontalAlignment(widget, self.horzAlign) self.setCellVerticalAlignment(widget, self.vertAlign) def remove(self, widget): if isinstance(widget, int): widget = self.getWidget(widget) if widget.getParent() != self: return False td = DOM.getParent(w...
jbaayen/reinteract
lib/reinteract/base_notebook_window.py
Python
bsd-2-clause
10,711
0.00112
# Copyright 2008-2009 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import os import re import sys import gtk from...
itial_editor: self.__initial_editor = None self.editors.remove(editor) editor.widget._notebook_window_editor = None editor.close() self.__update_title() self._update_open_files() self.update_sensitivity() def _update_editor_state(self, editor): s...
ate_sensitivity() def _update_editor_title(self, editor): if editor == self.current_editor: self.__update_title() ####################################################### # Overrides ####################################################### def _add_actions(self, action_group): ...
OpenDroneMap/OpenDroneMap
opendm/osfm.py
Python
gpl-3.0
22,421
0.004906
""" OpenSfM related utils """ import os, shutil, sys, json, argparse import yaml from opendm import io from opendm import log from opendm import system from opendm import context from opendm import camera from opendm.utils import get_depthmap_resolution from opendm.photo import find_largest_photo_dim from opensfm.larg...
"feature_min_frames: %s" % args.min_num_features, "processes: %s" % args.max_concurrency, "matching_gps_neighbors: %s
" % args.matcher_neighbors, "matching_gps_distance: %s" % args.matcher_distance, "depthmap_method: %s" % args.opensfm_depthmap_method, "depthmap_resolution: %s" % depthmap_reso
biocore/american-gut-web
amgut/lib/data_access/ag_data_access.py
Python
bsd-3-clause
57,541
0
from __future__ import division # ----------------------------------------------------------------------------- # Copyright (c) 2014--, The American Gut Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # --------...
'Soil', 'Sole of shoe', 'Water'] ##################################### # Users ##################################### def authenticateWebAppUser(self, username, password): """ Attempts to validate authenticate the supplied username/pass...
a dict with user innformation is returned. If not, the function returns False. """ with TRN: sql = """SELECT cast(ag_login_id as varchar(100)) as ag_login_id, email, name, address, city, state, zip, country,kit_password ...
denis-vilyuzhanin/selenium-fastview
py/selenium/webdriver/firefox/firefox_binary.py
Python
apache-2.0
8,338
0.002998
#!/usr/bin/python # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "Li...
it for details.") count += 1 time.sleep(1) return True def _find_exe_in_registry(self): try: from _w
inreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER import shlex keys = ( r"SOFTWARE\Classes\FirefoxHTML\shell\open\command", r"SOFTWARE\Classes...
gdorion/advent-of-code
2015/python/Day3/houses.py
Python
mit
2,174
0.0046
import math class Point(object): X = 0 Y = 0 def __init__(self, x, y): self.X = x self.Y = y def getX(self): return self.X def getY(self): return self.Y def __str__(self): return "Point(%s,%s)" % (self.X, self.Y) def __eq__(self, other): ...
HousesCountVisitedOnce(self): uniquePoints = [] for point1 in self.trail: found = False for point2 in uniquePoints: if point1.X == point2.X and point1.Y == point2.Y : found = True if found == False: uniquePoints.ap...
ain(): # # Entry point # origin = Point(0,0) # Where Santa starts it's run. trail = Trail() # The gifts delivery trail. trail.extend(origin) with open('data.txt') as f: for c in f.read(): if c == "<": origin = Point(origin.X, origin.Y) ori...
phyng/python-google-proxy
proxy/wsgi.py
Python
mit
387
0
""" WSGI config for proxy project. It exposes the WSGI callable as a module-level variable named
``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_app
lication os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proxy.settings") application = get_wsgi_application()
ennoborg/gramps
gramps/gen/proxy/cache.py
Python
gpl-2.0
6,358
0.000472
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (c) 2016 Gramps Development Team # # 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 ...
version. """ return getattr(self.db, attr) def clear_cache(self, handle=None):
""" Clears all caches if handle is None, or specific entry. """ if handle: del self.cache_handle[handle] else: self.cache_handle = LRU(100000) def get_person_from_handle(self, handle): """ Gets item from cache if it exists. Co...
sysbot/OpenClos
jnpr/openclos/ztp.py
Python
apache-2.0
4,984
0.008427
''' Created on Sep 10, 2014 @author: moloyc ''' import os import logging from jinja2 import Environment, PackageLoader from netaddr import IPNetwork import util from model import Pod from dao import Dao from writer import DhcpConfWriter moduleName = 'ztp' logging.basicConfig() logger = logging.getLogger(moduleName)...
cpConfFile(self): pods = self.dao.getAll(Pod) if len(pods) > 0: confWriter = DhcpConfWriter(self.conf, pods[0], self.dao) confWriter.writeSingle(self.generateSingleDhcpConf()) ''' def generateSingleDhcpConf(self): if util.isPlatformUbuntu(): ztp =...
emplateEnv.get_template('dhcp.conf.ubuntu') return dhcpTemplate.render(ztp = self.populateDhcpDeviceSpecificSettingForAllPods(ztp)) def createPodSpecificDhcpConfFile(self, podName): pod = self.dao.getUniqueObjectByName(Pod, podName) confWriter = DhcpConfWriter(self.conf, pod, self.dao)...
wooga/airflow
backport_packages/import_all_provider_classes.py
Python
apache-2.0
4,232
0.001654
#!/usr/bin/env python3 # 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 # "L...
module_name = package_name + "." + file[:-3] if file != "__init__.py" else package_name if print_imports: print(f"Importing module: {module_name}") # noinspection PyBroadException try: _module = importlib.import_module(module_na...
e + "." + attribute_name attribute = getattr(_module, attribute_name) if isclass(attribute): if print_imports: print(f"Imported {class_name}") imported_classes.append(class_name) ...
photoninger/ansible
lib/ansible/modules/network/f5/bigip_gtm_facts.py
Python
gpl-3.0
31,508
0.001016
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
ule_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import fqdn_name from library.module_utils.network.f5.common import f5_argument_spec try: from library.module_utils.network.f5.comm...
ortError: # Upstream Ansible from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5Client from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible...
Coops1980/Logbook
Main.py
Python
unlicense
2,472
0.033981
import tkinter as tk import tkinter.ttk as ttk def NewFlight(): from Controller import LoadNewFlightPage LoadNewFlightPage(mainPage) def LogBook(): from Controller import LoadLogBookPage LoadLogBookPage(mainPage) def CreateMainPage(): global mainPage mainPage = tk.Tk() m...
abel(text = "RAF Flight Logbook v1", fg="steel blue", font=("Comic Sans MS", 10),width=50) FrameTitle.grid(row=0,column=0,columnspan=4) TopSpace = tk.L
abel(text = "", bg="midnight blue") TopSpace.grid(row=1,columnspan=4,sticky='ew') LogBook_btn = tk.Button(text = "Log Book", fg ="black",command=LogBook) LogBook_btn.grid(row=2,column=1,columnspan=2,) MidTopSpace = tk.Label(text = "", bg="midnight blue") MidTopSpace.grid(row=3,col...
MicrosoftLearning/Django
Demos/MusicStore/app/models.py
Python
mit
582
0.024055
""" Definition of models. """ from django.db import models from django import forms; # Create your models here. class Artist(models.
Model): name = models.CharField(max_length=50); year_formed = models.PositiveIntegerField(); class ArtistForm(forms.ModelForm): class Meta: model = Artist;
fields = ['name', 'year_formed']; class ArtistForm(forms.ModelForm): class Meta: model = Artist; fields = ['name', 'year_formed']; class Album(models.Model): name = models.CharField(max_length=50); artist = models.ForeignKey(Artist);
kartoza/jakarta-flood-maps
django_project/flood_mapper/migrations/0004_auto_20141216_1042.py
Python
bsd-2-clause
665
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('flood_mapper', '0003_data_migration_20141201_0218'), ] operations = [ migrations.AlterField( model_name='floodst...
l=True, blank=True), preserve_default=True, ), migrations.AlterField( model_name='village', name='slug', field=models.SlugField(unique=True, max_length=100),
preserve_default=True, ), ]
google/ffn
train.py
Python
apache-2.0
27,262
0.006383
# Copyright 2017-2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
eholder(
tf.float32, [1] + eval_shape + [1], name='eval_labels') self.eval_preds = tf.placeholder( tf.float32, [1] + eval_shape + [1], name='eval_preds') self.eval_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits=self.eval_preds, labels=self.eval_labels)) self.r...
nasseralkmim/SaPy
sapy/load.py
Python
gpl-3.0
342
0
import numpy as np def P_vector(model, nodal_load): """Return the load vector """ P = np.zeros(model.nt) for n, p in nodal_load.items(): if n not in model.CON: raise Except
ion('Not a valid DOF for the applied load!') for i, d in enumerate(model.DOF[n]): P[d] =
p[i] return P
sampathweb/game_app
card_games/test/test_blackjack.py
Python
mit
917
0.001091
#!/usr/bin/env python """ Test code for blackjack game. Tests can be run with py.test or nosetests """ from __future__ import print_function from unittest import TestCase from card_games import blackjack from card_games.blackjack import BlackJack print(blackjack.__file__) class TestRule(TestCase): def setUp(se...
e = BlackJack() self.assertEqual(len(mygame.player_hand), 2) # Initial hand for Player
self.assertEqual(len(mygame.dealer_hand), 2) # Initial hand for Dealer def test_player_bust(self): mygame = BlackJack() for cnt in range(10): # Draw 10 cards - Sure to loose mygame.draw_card_player() self.assertEqual(len(mygame.player_hand), 12) # Twelve cards in Player's ...
lmazuel/azure-sdk-for-python
azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/account/models/add_data_lake_store_parameters.py
Python
mit
943
0
# 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 ...
s(Model): """The parameters used to add a new Data Lake Store account. :param suffix: The optional suffix for the Data Lake Store account. :type suffix: str """ _attribute_map = {
'suffix': {'key': 'properties.suffix', 'type': 'str'}, } def __init__(self, suffix=None): super(AddDataLakeStoreParameters, self).__init__() self.suffix = suffix
numenta/htmresearch
htmresearch/frameworks/pytorch/modules/k_winners.py
Python
agpl-3.0
9,177
0.007083
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2019, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
erenceFactor: During infere
nce (training=False) we increase k by this factor. :type kInferenceFactor: float :param boostStrength: boost strength (0.0 implies no boosting). :type boostStrength: float :param boostStrengthFactor: Boost strength factor to use [0..1] :type boostStrengthFactor: float :param dutyC...
facebookexperimental/eden
eden/hg-server/edenscm/hgext/highlight/highlight.py
Python
gpl-2.0
3,008
0.000997
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # highlight.py - highlight extension implementation file # # Copyright 2007-2009 Adam Hupp <adam@hupp.org> and others # # This software may be...
om edenscm.mercurial import demandimport, encoding, util demandimport.ignore.extend(["pkgutil", "pkg_resources", "__main__"]) with demandimport.deactivated(): import pygments import pygments.formatters import pygments.lexers import pygments.util highlight = pygments.highlight ClassNotFound = pygme...
rs.guess_lexer_for_filename TextLexer = pygments.lexers.TextLexer HtmlFormatter = pygments.formatters.HtmlFormatter SYNTAX_CSS = '\n<link rel="stylesheet" href="{url}highlightcss" ' 'type="text/css" />' def pygmentize(field, fctx, style, tmpl, guessfilenameonly=False): # append a <link ...> to the syntax highli...
SnowWalkerJ/quantlib
quant/data/wind/tables/asharebalancesheet.py
Python
gpl-3.0
18,744
0.018408
from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE VARCHAR2 = VARCHAR class AShareBalanceSheet(BaseModel): """ 4.45 中国A股资产负债表 Attributes ---------- object_id: VARCHAR2(100) 对象ID s_info_windcode: VARCHAR2(40) Wind代码 ...
cur_liab: NUMBER(20,4) 非流动负债合计 liab_dep_oth_banks_fin_inst: NUMBER(20,4) 同业和其它金融机构存放款项 derivative_fin_liab: NUMBER(20,4) 衍生金融负债 cust_bank_dep: NUMBER(20,4) 吸收存款 agency_bus_liab: NUMBER(20,4) 代理业务负债 oth_liab: NUMBER(20,4) 其他负债
prem_received_adv: NUMBER(20,4) 预收保费 deposit_received: NUMBER(20,4) 存入保证金 insured_deposit_invest: NUMBER(20,4) 保户储金及投资款 unearned_prem_rsrv: NUMBER(20,4) 未到期责任准备金 out_loss_rsrv: NUMBER(20,4) 未决赔款准备金 life_insur_rsrv: NUMBER(20,4) 寿险...
Noirello/bonsai
src/bonsai/tornado/__init__.py
Python
mit
53
0
from .tor
nadoconnection import TornadoLDAPCon
nection
deni-zen/csvelte
docs/_contrib/apigenrole.py
Python
mit
2,618
0.002292
from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes # I cant figure out how the hell to import this so I'm just gonna forget it for now def apigen_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to API Docs page. Returns 2 part tuple containing lis...
ApiGen API docs page. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Item type (class, namespace, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func. """ # try: base = app...
t AttributeError, err: raise ValueError('apigen_docs_uri configuration value is not set (%s)' % str(err)) # Build API docs link slash = '/' if base[-1] != '/' else '' ref = base + slash + type + '-' + slug + '.html' set_classes(options) node = nodes.reference(rawtext, type + ' ' + utils.unes...
note35/sinon
sinon/lib/util/ErrorHandler.py
Python
bsd-2-clause
2,133
0.016409
""" Copyright (c) 2016-2017, Kir Chou https://github.com/note35/sinon/blob/master/LICENSE A set of functions for handling known error """ def __exception_helper(msg, exception=Exception): #pylint: disable=missing-docstring raise exception(msg) def mock_type_error(obj): #pylint: disable=missing-docstring erro...
already been declared".format(name) return __exception_helper(error_msg) def called_with_empty_error(): #pylint: disable=missing-docstring error_msg = "There is no argument" return __exception_helper(error_msg) def is_not_spy_error(obj): #pylint: disable=missing-docstring e
rror_msg = "[{}] is an invalid spy".format(str(obj)) return __exception_helper(error_msg) def matcher_type_error(prop): #pylint: disable=missing-docstring error_msg = "[{}] is an invalid property, it should be a type".format(prop) return __exception_helper(error_msg, exception=TypeError) def matcher_insta...
tapomayukh/projects_in_python
modeling_new_tactile_skin/polynomial_model_fitting/force_area_output_model/force_area_output_model2.py
Python
mit
3,444
0.009582
import sys, os import math, numpy as np import matplotlib.pyplot as pp import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu import scipy.optimize as scp # Params area = 0.0 # For one push and pull: def force_one_push_pull(d): ft_l = d['ft'...
_push_pull(d) area = math.sqrt(d['contact_area']) y_fit = p_lsq[0][0]*area*(x)**3 + p_lsq[0][1]*area*(x)**2 + p_lsq[0][2]*area*(x)**1 + p_lsq[0][3]*area pp.plot(x, y_fit, color=color, linewidth = 3.0) # Calculate RMS Error rmse = math.sqrt(float(np.sum((np.array(y_meas) - np.array(y_fit))**2))/...
pkl, c in zip(pkl_list, color_list): d = ut.load_pickle(pkl) adc, ft = force_one_push_pull(d) force_vs_adc(pkl, adc, ft, c) pp.xlim((0,1000)) pp.ylim((-10,80)) fit_the_data(pkl_list, 'k') pp.show()
1uk/LPTHW
ex26.py
Python
bsd-3-clause
1,313
0.002285
from ex25 import * print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love n
or comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 2 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates =...
d beans, %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) sentence = "All good things come to those who wait." words = break_words(sentence) sorted_words = sort_wor...
lpfann/fri
fri/tests/test_parameter_searcher.py
Python
mit
1,221
0
import numpy as np import pytest from sklearn.preprocessing import StandardScaler from sklearn.utils import check_random_state import fri from fri import genLupiData from fri.parameter_searcher import find_best_model @pytest.fixture(scope="session") def randomstate(): return check_random_state(1337) @pytest.ma...
tate=randomstate, ) X, X_priv, y = data X = StandardScaler().fit(X).transform(X) X_priv = StandardScaler().fi
t(X_priv).transform(X_priv) combined = np.hstack([X, X_priv]) iter = 50 best_model, best_score = find_best_model( template, params, (combined, y), randomstate, iter, verbose=1, n_jobs=-2, lupi_features=X_priv.shape[1], ) assert best_...
littlejo/Libreosteo
libreosteoweb/migrations/0022_therapeutsettings_invoice_footer.py
Python
gpl-3.0
504
0.001984
# -*- coding: utf-8 -*- from __future__ impor
t unicode_literals from django.db import models, migrations class Migration
(migrations.Migration): dependencies = [ ('libreosteoweb', '0021_therapeutsettings_siret'), ] operations = [ migrations.AddField( model_name='therapeutsettings', name='invoice_footer', field=models.TextField(null=True, verbose_name='Invoice footer', blan...
brianhang/tritonscheduler
docs/conf.py
Python
mit
11,786
0.000085
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # tritonschedule documentation build configuration file, created by # sphinx-quickstart on Wed Jun 22 11:40:06 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in th...
rnings = False # If true, `todo` and `todo
List` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific...
yutiansut/QUANTAXIS
QUANTAXIS/QASetting/cache.py
Python
mit
4,703
0.001701
# coding:utf-8 # # The MIT License (MIT) # # Copyright (c) 2016-2021 yutiansut/QUANTAXIS # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation th...
ct.""" if CACHE is None: _init(config_file) return CACHE class Cache(): """This object is used to interface with the job cache. It uses a SQLite3 database to store the information. :param str cache_file: The path to the cache file. This will be created if it does not already exi...
.filename) self.conn = sqlite3.connect(self.filename) self.cur = self.conn.cursor() self.cur.execute("PRAGMA foreign_keys = ON") def __del__(self): """Commit the changes and close the connection.""" if getattr(self, "conn", None): self.conn.commit() ...
LLNL/spack
var/spack/repos/builtin/packages/py-kiwisolver/package.py
Python
lgpl-2.1
1,376
0.00436
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack
Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyKiwisolver(PythonPackage): ""
"A fast implementation of the Cassowary constraint solver""" homepage = "https://github.com/nucleic/kiwi" pypi = "kiwisolver/kiwisolver-1.1.0.tar.gz" version('1.3.2', sha256='fc4453705b81d03568d5b808ad8f09c77c47534f6ac2e72e733f9ca4714aa75c') version('1.3.1', sha256='950a199911a8d94683a6b10321f9345d5a3...
google-research/motion_imitation
mpc_controller/torque_stance_leg_controller.py
Python
apache-2.0
7,722
0.006346
# Lint as: python3 """A torque based stance controller framework.""" from __future__ import absolute_import from __future__ import division #from __future__ import google_type_annotations from __future__ import print_function import os import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspec...
f._gait_generator.desired_leg_state], dtype=np.int32) # We use the body yaw aligned world frame for MPC computation. com_roll_pitch_yaw = np.array(self._robot.GetBaseRollPitchYaw(), dtype=np.float
64) com_roll_pitch_yaw[2] = 0 #predicted_contact_forces=[0]*self._num_legs*_FORCE_DIMENSION # print("Com Vel: {}".format(self._state_estimator.com_velocity_body_frame)) # print("Com RPY: {}".format(self._robot.GetBaseRollPitchYawRate())) # print("Com RPY Rate: {}".format(self._robot.GetBaseRollPitc...
MishtuBanerjee/xaya
xaya/xayanet.py
Python
mit
22,529
0.011718
#!/usr/bin/env python """ BeginDate:20071001 CurrentRevisionDate:20071001 Development Version : net 001 Release Version: pre-release Author(s): Mishtu Banerjee Contact: mishtu@harmeny.com Copyright: The Authors License: Distributed under MIT License [http://opensource.org/licenses/mit-license.html] ...
o shelfObject; deal with case of emptygraph via get fn #return shelfObject """ #DATASETS FOR FIND COMPONENTS a
network = {'a': [1,2,3], 'b' : [4,5,6], 1 : ['d', 'e', 'f']} nothernetwork = {'a': [1,2,3], 'b' : [4,5,6], 1 : ['d', 'e', 'f'], 4: ['e', 'f', 'g'], 'x': [9, 10,11], 11: [12, 13, 14]} loopnetwork = {'a': [1,2,3], 'b' : [4,5,6], 1 : ['d', 'e', 'f'], 4: ['e', 'f', 'g'], 12: [13], 13...
valvy/miniqubit
examples/python/executefile/main.py
Python
mit
714
0.009804
#!/usr/bin/env python from PyMiniQbt import getVersion, getName, QasmAsyncInterpreter import sys def main(arguments): if(not len(arguments) == 2): print("which file?"
) sys.exit(-1) print("Using", getName(), "version:", getVersion()) with open(arguments[1]) as dat: src = dat.read() interpreter = QasmAsyncInterpreter()
interpreter.interpret(src) while interpreter.hasErrors(): print(interpreter.getError()) print("results:") for register in interpreter.getRegisters(): print(register,":",interpreter.readClassicResult(register).dataToString()) if __name__ == "__m...
erg0dic/hipshare
hipshare/lib/xmpp.py
Python
bsd-2-clause
1,321
0.003785
import logging from sleekxmpp import ClientXMPP log = logging.getLogger(__name__) class HipshareXMPP(ClientXMPP): def __init__(self, jid, password): ClientXMPP.__init__(self, jid, password) self.add_event_handler("session_start", self.session_start, threaded=True) def session_start(self
, event): self.send_presence() self.get_roster() class Client(object): def __init__(self, config): self.config = config self.xmpp = HipshareXMPP(config.strategy['jid'], config.strategy['password']) for plugin in config.options['plugins']: self.xmpp.register_plug...
onnect(self, *args, **kwargs): return self.xmpp.connect(*args, **kwargs) def disconnect(self, *args, **kwargs): return self.xmpp.disconnect(*args, **kwargs) def get_plugin(self, plugin): return self.xmpp.plugin[plugin] def process(self, *args, **kwargs): return self.xmpp.p...
SUSE/teuthology
teuthology/test/test_repo_utils.py
Python
mit
9,075
0.000882
import logging import unittest.mock as mock import os import os.path from pytest import raises, mark import shutil import subprocess import tempfile from teuthology.exceptions import BranchNotFoundError, CommitNotFoundError from teuthology import repo_utils from teuthology import parallel repo_utils.log.setLevel(loggi...
_path, ).split() assert result self.commit = result[0].decode() def teardown_method(self, method): shutil.rmtree(self.dest_path, ignore_errors=True) def test_clone_repo_existing_branch(self): repo_utils.clone_repo(self.repo_url, self.dest_path, 'master', sel...
utils.clone_repo(self.repo_url, self.dest_path, 'nobranch', self.commit) assert not os.path.exists(self.dest_path) def test_fetch_no_repo(self): fake_dest_path = self.temp_path + '/not_a_repo' assert not os.path.exists(fake_dest_path) with raises(OSError): repo_utils.fet...
hacktyler/hacktyler_crime
config/settings.py
Python
mit
4,568
0.005035
#!/usr/bin/env python import os import django # Base paths DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__)) SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # Debugging DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS =...
it with anybody. SECRET_KEY = '+ei7-2)76sh$$dy^5h4zmkglw#ey1d3f0cj^$r+3zo!wq9j+_*' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Lo...
ontext_processors.media', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', ) ROOT_URLCONF = 'config.urls' TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'templates') ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django....
cactorium/UCFBrainStuff
seniordesign/emokit/gyro_plot.py
Python
mit
1,625
0.007385
# This is an example of popping a packet from the Emotiv class's packet queue # and printing the gyro x and y values to the console. from emokit.emotiv import Emotiv import platform if platform.system() == "Windows": import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459) impor...
te(rb): print "Animation!" print rb line.set_ydata(rb) return line, def counter(): i = 0 while is_running: yield i i = i +
1 ani = animation.FuncAnimation(fig, animate, evt_wrapper(), init_func=init, interval=20, blit=True) plt.show() # gevent.Greenlet.spawn(evt_main, test_buf) while True: gevent.sleep(0)
khalidm/VarPub
src/mytest.py
Python
gpl-2.0
181
0.005525
import pybedtools a = pybedtools.example_bedtool('a.bed') b = pybedtools.exampl
e_bedtool('b.bed') print "cat a.bed\n" + str(a) print "cat b.bed\n" + str(b) pri
nt a.intersect(b)
emersonmx/ippl
ippl/genetic_algorithm/chromosome.py
Python
gpl-3.0
852
0.001174
# # Copyright (C) 2013-2014 Emerson Max de Medeiros Silva # # This file is part of ippl. # # ippl 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 optio
n) any later version. # # ippl is distributed in the hope tha
t it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ippl. If not, see <http://www.gnu.org/l...
jazztpt/edx-platform
lms/djangoapps/instructor/tests/test_services.py
Python
agpl-3.0
3,469
0
""" Tests for the InstructorService """ import json from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory from courseware.models import StudentModule from instructor.services import InstructorService from instructor.tests.test_tools import ...
ent from student.tests.factories import UserFactory @attr('shard_1') class InstructorServiceTests(ModuleStoreTestCase)
: """ Tests for the InstructorService """ def setUp(self): super(InstructorServiceTests, self).setUp() self.course = CourseFactory.create() self.student = UserFactory() CourseEnrollment.enroll(self.student, self.course.id) self.problem_location = msk_from_probl...
Yubico/yubioath-desktop-dpkg
yubioath/core/legacy_otp.py
Python
gpl-3.0
7,391
0
# Copyright (c) 2014 Yubico AB # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
except NeedsTouchError: self.touch = True raise
else: if self.touch is None: self.touch = False def delete(self): self._legacy.delete(self._slot) def __repr__(self): return self.name # Keep track of YK_KEY references. _refs = [] def open_otp(): key = ykpers.yk_open_first_key() if key: ke...
arq5x/poretools
poretools/metadata.py
Python
mit
641
0.031201
import Fast5File def run(parser, args): if args.read: for i, fast5 in enumerate(Fast5File.Fast5FileSet(args.files)): for metadata_dict in fast5.read_metadata: if i == 0: header = metadata_dict.keys() print "\t".join(["filename"] + header) print "\t".join([fast5.filename] + [str( metadata_dict[...
asic_temp = fast5.get_asic_temp() asic_id = fast5.get_asic_id() heatsink_temp
= fast5.get_heatsink_temp() print "%s\t%s\t%s" % (asic_id, asic_temp, heatsink_temp) fast5.close()
elsehow/moneybot
moneybot/market/scrape.py
Python
bsd-3-clause
5,485
0.000547
# -*- coding: utf-8 -*- import time import requests from datetime import datetime from logging import getLogger from typing import Optional from typing import Dict from typing import Iterable from funcy import compose from funcy import partial from pandas import DataFrame from pandas import to_datetime from pandas imp...
s = None for key, vals in hist_ticke
r.items(): if ts is None: ts = [to_datetime(t[0] * 1000000) for t in vals] r[key] = [t[1] for t in vals] return DataFrame(r, index=ts) coin_history = compose(market_cap, historical) def marshall(hist_df): btc_to_usd = hist_df['price_usd'] / hist_df['price_btc'] # volume in BT...
moeskerv/ABElectronics_Python_Libraries
ADCDACPi/demo-dacsinewave.py
Python
gpl-2.0
3,862
0.000777
#!/usr/bin/python from ABE_ADCDACPi import ADCDACPi import time import math """ ================================================ ABElectronics ADCDAC Pi 2-Channel ADC, 2-Channel DAC | DAC sine wave generator demo Version 1.0 Created 17/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format run with...
8, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046
, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, ...
ActiveState/code
recipes/Python/577484_PRNG_Test/recipe-577484.py
Python
mit
1,669
0.009587
# PRNG (Pseudo-Random Number Generator) Test # PRNG info: # http://en.wikipedia.org/wiki/Pseudorandom_number_generator # FB - 201012046 # Compares output distribution of any given PRNG # w/ an hypothetical True-Random Number Generator (TRNG) import math import time global x x = time.clock() # seed for the PRNG # PRNG ...
: return 0 return c(n - 1, k - 1) + c(n - 1, k) ### combination by multiplicative method ##def c_(n, k): ## mul = 1.0 ## for i in range(k): ## mul = mul * (n - k + i + 1) / (i + 1) ## return mul # MAIN n = 20 # number of bits in each trial print 'Test in progress...' print cnk = [] # array to hold...
(2 ** n): # generate n-bit pseudo-random number and count the 0's in it # num = '' ctr = 0 for i in range(n): b = int(round(prng())) # generate 1 pseudo-random bit # num += str(b) if b == 0: ctr += 1 # print num # increase bit count in the array cnk[ctr] += 1 print '...
PyCQA/pylint
tests/functional/u/unused/unused_variable_py38.py
Python
gpl-2.0
1,000
0.006
"""Tests for the unused-variable message in assignment expressions""" def typed_assignment_in_function_default( # [unused-variable] param: str = (typed_default := "walrus"), # [unused-variable] ) -> None: """An unused annotated assignment expression in a default parameter should emit""" return param de...
_function_scope( # [unused-variable] param=(function_default := "walrus"), ) -> None: """An used assignment expression in a default parameter should not emit""" print(function_default) return param def assignment_used_in_global_scope( # [unused-variable] param=(global_default := "walrus"), ) -> No
ne: """An used assignment expression in a default parameter should not emit""" return param print(global_default)
scottbarstow/iris-python
iris_sdk/models/maps/subscriptions.py
Python
mit
131
0.015267
#!/usr/bin
/env python from iris_sdk.mode
ls.maps.base_map import BaseMap class SubscriptionsMap(BaseMap): subscription = None
hydraplatform/hydra-base
hydra_base/lib/HydraTypes/Types.py
Python
lgpl-3.0
9,393
0.005642
""" Types that can be represented by a dataset are defined here Each Hydra type must subclass DataType and implement the required abstract properties and methods. The form of each class' constructor is not part of the interface and is left to the implementer. """ import json import math import six import nu...
): return str(self._value) def set_value(self, val): self._value = val value = property(get_value, set_value) class Array(DataType): tag = "ARRAY" name = "Array" skeleton = "[%f, ...]" json = ArrayJSON() def __init__(self, encstr): super(Array, self)...
date() @classmethod def fromDataset(cls, value, metadata=None): return cls(value) def validate(self): j = json.loads(self.value) assert len(j) > 0 # Sized assert iter(j) is not None # Iterable assert j.__getitem__ # Container assert not isi...
mmilata/atomic-reactor
atomic_reactor/plugins/post_import_image.py
Python
bsd-3-clause
2,151
0
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals import json import os from osbs.api import OSBS from osbs.conf import Configuration from atomic_re...
verify_ssl=self.verify_ssl) osbs = OSBS(osbs_conf, osbs_conf) metadata = build_json.get("metadata", {}) kwargs = {} if 'namespace' in metadata: kwargs['namespace'] = metadata['namespace'] labels = metadata.get("labels", {}) try: imagest...
gestream"] except KeyError: self.log.error("No imagestream label set for this Build") raise self.log.info("Importing tags for %s", imagestream) osbs.import_image(imagestream, **kwargs)
meisterkleister/erpnext
erpnext/setup/doctype/email_digest/email_digest.py
Python
agpl-3.0
11,804
0.027702
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frapp
e from frappe import _ from frappe.utils import fmt_money, formatdate, format_time, now_datetime, \ ge
t_url_to_form, get_url_to_list, flt from datetime import timedelta from dateutil.relativedelta import relativedelta from frappe.core.doctype.user.user import STANDARD_USERS import frappe.desk.notifications from erpnext.accounts.utils import get_balance_on user_specific_content = ["calendar_events", "todo_list"] from ...
RedHatQE/cfme_tests
cfme/storage/object_store_object.py
Python
gpl-2.0
6,631
0.001206
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute from widgetastic.widget import NoSuchElementException from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patte...
e Object page""" t
oolbar = View.nested(ObjectStoreObjectToolbar) search = View.nested(Search) including_entities = View.include(BaseEntitiesView, use_parent=True) @property def is_displayed(self): return ( self.in_object and self.title.text == 'Cloud Object Store Objects') @View.nest...
QInfer/python-qinfer
src/qinfer/domains.py
Python
bsd-3-clause
19,964
0.002655
#!/usr/bin/python # -*- coding: utf-8 -*- ## # domains.py: module for domains of model outcomes ## # © 2017, Chris Ferrie (csferrie@gmail.com) and # Christopher Granade (cgranade@cgranade.com). # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the...
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWA...
uture__ import absolute_import from builtins import range from future.utils import with_metaclass from functools import reduce from operator import mul from scipy.special import binom from math import factorial from itertools import combinations_with_replacement, product import numpy as np from .utils import join_str...
falgore88/command_manager
manage.py
Python
bsd-2-clause
187
0
# -*
- coding: utf-8 -*- from __future__ import unicode_literals if __name__ == '__main__': from command_manager import Manager manager = Manager(["commands"]) manager.run()
ebrahimraeyat/civilTools
section/filehandling/slenders.py
Python
gpl-3.0
3,474
0.014105
# -*- coding: utf-8 -*- slenderParameters = {'notPlate': {'beam': {'M': {'BF': '2*bf', 'tfCriteria': True, 'TF': ('2*tf', ''), 'D': 'd', 'twCriteria': True, 'TW': ('(D-2*TF)/(d-2(tf+r))*tw', '')}, 'H': {'BF': '2*bf', 'tfCriteria': True, 'TF': ('2*0.55*tf/.6', ''), 'D': 'd', ...
bf'), 'D': 'd+2*t1', 'twCriteria': 't2<(d*tw)/(d-2(tf+r))', 'TW': ('t2*(D-2*TF)/d', 'tw*(D-2*TF)/(d-2*(tf+r))')}},
'column': {'M': {'BF': 'c+bf+2*tf', 'tfCriteria': 't1<(.76*B1*tf)/(1.12*bf)', 'TF': ('(1.12*BF*t1)/(.76*B1)', '(BF*tf)/bf'), 'D': 'd+2*t1', 'twCriteria': 't2<(d*tw)/(d-2(tf+r))', 'TW': ('t2*(D-2*TF)/d', 'tw*(D-2*TF)/(d-2*(tf+r))')}, '...
ResearchSoftwareInstitute/MyHPOM
hs_tracking/__init__.py
Python
bsd-3-clause
60
0
def
ault_app_config = 'hs_
tracking.apps.HSTrackingAppConfig'
google/vimdoc
vimdoc/parser.py
Python
apache-2.0
3,977
0.012321
"""The vimdoc parser.""" from vimdoc import codeline from vimdoc import docline from vimdoc import error from vimdoc import regex def IsComment(line): return regex.comment_leader.match(line) def IsContinuation(line): return regex.line_continuation.match(line) def StripContinuator(line): assert regex.line_c...
ne(regex.comment_leader.sub('', line)) elif IsComment(line): yield i,
ParseCommentLine(line) else: vimdoc_mode = False yield i, ParseCodeLine(line) def ParseCodeLine(line): """Parses one line of code and creates the appropriate CodeLine.""" if regex.blank_code_line.match(line): return codeline.Blank() fmatch = regex.function_line.match(line) if fmatch: n...
sinotradition/meridian
meridian/tst/acupoints/test_zhimai44.py
Python
apache-2.0
297
0.006734
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @license: ''' import unittest from meridian.acupoints import zhimai44 class TestZhimai44Functions(unittest.TestCase): def setUp(self): pass def test_xxx(s
elf): pass if __n
ame__ == '__main__': unittest.main()
noemis-fr/old-custom
account_cutoff_base/account_cutoff.py
Python
agpl-3.0
18,694
0.000053
# -*- encoding: utf-8 -*- ############################################################################## # # Account Cut-off Base module for OpenERP # Copyright (C) 2013 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free software: you can re...
return context.get('type') def _inherit_default_cutoff_account_id(self, cr, uid, context=None): '''Function designed to be inherited by other cutoff modules''' return None def _default_cutoff_account_id(self, cr, uid, context=None): '''This function can't be inherited, so we use a sec...
turn self._inherit_default_cutoff_account_id( cr, uid, context=context) _defaults = { 'state': 'draft', 'company_id': lambda self, cr, uid, context: self.pool['res.users'].browse( cr, uid, uid, context=context).company_id.id, 'cutoff_journal_id': _get_default...
briehl/narrative
src/biokbase/narrative/tests/test_jobmanager.py
Python
mit
6,949
0.002446
""" Tests for job management """ import unittest from unittest import mock import biokbase.narrative.jobs.jobmanager from biokbase.narrative.jobs.job import Job from .util import TestConfig import os from IPython.display import HTML from .narrative_mock.mockclients import get_mock_client, get_failing_mock_client from b...
l = jobs_html.data print(html) self.assertIn("<td>5d64935ab215ad4128de94d6</td>", html
) self.assertIn("<td>NarrativeTest/test_editor</td>", html) self.assertIn("<td>2019-08-26 ", html) self.assertIn(":54:48</td>", html) self.assertIn("<td>fake_test_user</td>", html) self.assertIn("<td>completed</td>", html) self.assertIn("<td>Not started</td>", html) ...
saintdragon2/python-3-lecture-2015
civil_mid_final/2johack/source/Stage.py
Python
mit
25,316
0.008532
import pygame import Vector2, BaseObject, Enemy, Resources, Menu # Classe que gerencia as fases do jogo class Stage(BaseObject.BaseObject): # param: manager - instancia do ScreenManager def __init__(self, manager): # sempre lembrar de chamar o 'super' BaseObject.BaseObject.__init__(self, m...
se if self.flCount == 0: pygame.mixer.music.stop() self.finishLevelSound.play() elif self.flCount > self.screenManager.resolution[0]: self.finishLevelSound.fadeout(900) # depois de terminar a f
ase abre o menu de fase self.screenManager.setBaseObjectToUpdate(Menu.StagesMenu(self.screenManager)) pygame.mixer.music.load("res/sound/title.ogg") pygame.mixer.music.play(-1) self.flCount += 20 el...
duomarket/openbazaar-test-nodes
qa/complete_direct_online.py
Python
mit
9,485
0.004428
import requests import json import time from collections import OrderedDict from test_framework.test_framework import OpenBazaarTestFramework, TestFailure class CompleteDirectOnlineTest(OpenBazaarTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 def run_test(self): ...
se TestFailure("CompleteDirectOnlineTest - FAIL: Alice incorrectly saved as funded") # fund order spend = { "address": payment_address, "amount": payment_amount, "feeLevel": "NORMAL" } api_url = bob["gateway_url"] + "wallet/spend
" r = requests.post(api_url, data=json.dumps(spend, indent=4)) if r.status_code == 404: raise TestFailure("CompleteDirectOnlineTest - FAIL: Spend post endpoint not found") elif r.status_code != 200: resp = json.loads(r.text) raise TestFailure("CompleteDirectOn...
david81brs/seaport
l4_vogais.py
Python
gpl-2.0
159
0.062893
#!/usr/bin/python3 def vogal(v): lis
ta = ['a','e','i','o','u','A','E','
I','O','U'] if v in lista: return True else: return False
gmorph/MAVProxy
MAVProxy/modules/mavproxy_map/__init__.py
Python
gpl-3.0
27,717
0.005773
#!/usr/bin/env python ''' map display module Andrew Tridgell June 2012 ''' import sys, os, math import functools import time from MAVProxy.modules.mavproxy_map import mp_elevation from MAVProxy.modules.lib import mp_util from MAVProxy.modules.lib import mp_settings from MAVProxy.modules.lib import mp_module from MAVPr...
p import mp_slipmap self.missi
on_list = self.module('wp').wploader.view_list() polygons = self.module('wp').wploader.polygon_list() self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('Mission')) for i in range(len(polygons)): p = polygons[i] if len(p) > 1: popup = MPMenuSubMenu('Pop...
vadimadr/python-algorithms
tests/test_disjoint_set.py
Python
mit
407
0
from algorithms.structures.disjoint_set import DisjointSet def test_disjoint_set(): a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ds = DisjointSet(a) assert d
s.find_set(1) != ds.find_set(2) ds.union(1, 2) assert ds.find_set(1) == ds.find_set(2) assert
ds.find_set(1) != ds.find_set(3) ds.union(2, 3) assert ds.find_set(1) == ds.find_set(2) assert ds.find_set(2) == ds.find_set(3)
frohoff/Empire
lib/modules/powershell/code_execution/invoke_shellcodemsil.py
Python
bsd-3-clause
3,462
0.009821
import re from lib.common import helpers class Module: def __init__(self, main
Menu, params=[]): self.info = { 'Name': 'Invoke-ShellcodeMSIL', 'Author': ['@mattifestation'], 'Description': ('Execute shellcode within the context of the running PowerShell ' 'process without making any Win32 function calls. Warning: This scri...
code must end in a ret (0xC3) and maintain proper stack ' 'alignment or PowerShell will crash!'), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : True, 'Language' : 'powershell', ...
sadboyzvone/8080py
bin/8080.py
Python
gpl-3.0
13,651
0.002051
#!/usr/bin/python # -*- coding: utf-8 -*- ############## IMPORTS ################## from __future__ import print_function from os import path from sys import argv, exit from colorama import init as initColorama from colorama import Fore, Style from struct import pack from binascii import unhexlify as unHex #########...
LLOW + '\'' + fileName + '\'') raise IOError # It doesn't raise an exception # Read in the source code from the file with open(fileName, 'r') as sourceFile: sourceCode = sourceFile.readlines() # Strip the newlines sourceCode = map(lambda sc: sc.strip(), sou...
for (i, scLine) in enumerate(sourceCode): scLine = scLine.lower() # Turn it to lower case for easier lookup # Check for ORG if scLine.split(' ')[0] == "org": programCounter = int(scLine.split(' ')[1].zfill(4)) print("O...
twisted/twistedchecker
twistedchecker/test/test_docstring.py
Python
mit
678
0.001475
from twisted.trial import unittest from twistedchecker.checkers.docstring import DocstringChecker class DocstringTe
stC
ase(unittest.TestCase): """ Test for twistedchecker.checkers.docstring """ def test_getLineIndent(self): """ Test of twistedchecker.checkers.docstring._getLineIndent. """ checker = DocstringChecker() indentNoSpace = checker._getLineIndent("foo") indentTwo...
wahur666/kodok
python/bead5/mian.py
Python
gpl-3.0
1,500
0.002667
import os.path for root, dirs, files in os.walk(os.path.dirname(os.path.realpath(__file__))): for file in files : if file.endswith('.prog') : os.chdir(root) f1 = open(file, 'r') output = file.split(".") f2 = open(output[0]+'.py', 'w') indent = 0 ...
ag in tags: a = tag.replace("{", ":\n") a = a.replace("CIKLUS", "for") a = a.replace("ELAGAZAS", "if") if "\n" in a: t = a.split("\n") for t1 in t: for i in range(...
1 if "}" in t1: indent -= t1.count("}") t1 = t1.replace("}" ,"") f2.write(t1 + '\n') else: for i in range(indent): a = pad + a ...
ofavre/cellulart
matrixwidget.py
Python
bsd-3-clause
13,392
0.006347
# -*- coding: utf-8 -*- # License: See LICENSE file. import random import math try: import png except ImportError: png = False import pygtk pygtk.require('2.0') import gtk import gtk.gtkgl import gtk.gtkgl.apputils from OpenGL.GL import * from OpenGL.GLU import * import openglutils class MatrixWidget(gtk.D...
"""Configures the view origin, size and viewport. To be called inside gl_begin() and gl_end().""" # Get the widget's size width, height = self.allocation.width, self.allocation.height # Tell OpenGL to draw onto the same size glViewport(0, 0, width, height) # Set th...
.offset[1]+width/float(self.__pointsize), self.offset[0]+0.0, self.offset[0]+height/float(self.__pointsize), -1.0, 1.0) # Reset any 3D transform glMatrixMode(GL_MODELVIEW) glLoadIdentity() def __on_expose_event(self, widget, event, for_export=False): gldrawable = self.get_gl_drawabl...
indexofire/django-cms-content
cms_content_patch/forms.py
Python
bsd-3-clause
604
0.006623
# -*- coding: utf-8 -*- from django import forms from cms_content.settings import EDITOR from cms_content.models import CMSArticle from cms_content import widgets WIDGET = getattr(widgets, EDITOR) class CMSArticleAdminForm(forms.ModelForm): content = forms.CharField(widget=WIDGET) class Meta: m...
clas
s CMSArticleFrontendForm(forms.ModelForm): error_css_class = 'error' required_css_class = 'required' content = forms.CharField(widget=WIDGET) class Meta: model = CMSArticle fields = ('title', 'slug', 'content', 'category',)
benjamincongdon/adept
editMapTestScene.py
Python
mit
5,875
0.00783
import os import os.path import sys import pygame from buffalo import utils from buffalo.scene import Scene from buffalo.label import Label from buffalo.button import Button from buffalo.input import Input from buffalo.tray import Tray from camera import Camera from mapManager import MapManager from pluginManager im...
e) self.tool_tray.labels.add( Label( (int(self.tool_tray.width / 2), 120), "________________", color=(255,255,255,255), x_centered=True, font="default18", ) ) self.tool_tray.labels.add(
Label( (int(self.tool_tray.width / 2), 150), "Area of Effect", color=(255,255,255,255), x_centered=True, font="default18", ) ) def set_effect_state_to_draw(): ToolManager.set_effect_state(Tool...
OCA/partner-contact
partner_industry_secondary/tests/test_res_partner_industry.py
Python
agpl-3.0
1,860
0
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2016 Tecnativa S.L. - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import UserError, ValidationError from odoo.tests import common class T...
ner.industry"] cls.industry_main = cls.industry_model.create({"name": "Test"}) cls.industry_child = cls.industry_model.create( {"name": "Test child", "parent_id": cls.industry_main.id} )
def test_check_industries(self): with self.assertRaises(ValidationError): self.env["res.partner"].create( { "name": "Test", "industry_id": self.industry_main.id, "secondary_industry_ids": [(4, self.industry_main.id)], ...
sesuncedu/bitcurator
python/bc_gen_feature_rep_xls.py
Python
gpl-3.0
1,974
0.015198
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def bc_generate_feature_x...
ow in data: # Skip the lines with known text lines to be eliminated if (re.match("Total features",str(row))): conti
nue filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or feature may be missing. if len(row) > 3: filename = row[3] else: filename = "U...
nicococo/tilitools
tilitools/utils_data.py
Python
mit
5,881
0.009522
import numpy as np import cvxopt as co def load_mnist_dataset(): import torchvision.datasets as datasets mnist_train = datasets.MNIST(root='../data/mnist', train=True, download=True, transform=None) mnist_test = datasets.MNIST(root='../data/mnist', train=False, download=True, transform=None) test_labe...
_len-lens)-3 > min_block_len: break block_len = min( [block_len, block_len - (block_start+block_len-lens)-3] ) lbls[block_start:block_start+block_len-1] = 1 marker = 1 for d in range(dims): seqs[d,block_start:block_start+block_len-1] = np.random.randn(1,block...
qs = co.matrix(0.0, (1, lens)) lbls = co.matrix(0, (1, lens)) marker = 0 # generate first state sequence, gaussian noise 0=mean, 1=variance seqs = np.zeros((1, lens)) lbls = np.zeros((1, lens)) bak = seqs.copy() prob = np.random.uniform() if prob < anom_prob: # add second stat...
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/335_TheSongOfTheHunter/__init__.py
Python
gpl-3.0
28,333
0.032895
import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest from com.l2scoria.gameserver.network.serverpackets import CreatureSay from com.l2scoria.util.random import Rnd qn = "3...
719],30], [[3720],20], [[3721],20], [[3722,3723,3724,3725,3726],1] ] #Droplist Format- npcId : [itemRequired,itemGive,itemToGiveAmount,itemAmount,chance] Tor_requests_1 = {
20578 : [3727,3769,'1',40,80], #Leto Lizardman Archer 20579 : [3727,3769,'1',40,83], #Leto Lizardman Soldier 20586 : [3728,3770,'1',50,89], #Timak Orc Warrior 20588 : [3728,3770,'1',50,100], #Timak Orc Overlord 20565 : [3729,3771,'1',50,100], #Enchanted Stone Golem 20556 : [3730,3772,'1',30,50],...
legionus/billing
tests/test_wapi_metrics.py
Python
gpl-3.0
2,622
0.031274
import uuid from unithelper import DBTestCase from unithelper import mocker from unithelper import requestor from unithelper import hashable_dict from bc import database from bc import metrics from bc_wapi import wapi_metrics class Test(DBTestCase): def test_metric_get(self): """Check getting metric with metri...
FORMULA_SPEED, 'aggregate': 0L, } with database.DBConnect() as db: db.insert('metrics', data) self.ass
ertEquals(wapi_metrics.metricGet({'id': data['id']}), requestor({'metric': data}, 'ok')) self.assertEquals(wapi_metrics.metricGet({'id':''}), requestor({'message': 'Metric not found' }, 'error')) with mocker([('bc.metrics.get', mocker.exception), ('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]): ...
sparkslabs/kamaelia_
Sketches/JL/IRC/plainPython/client.py
Python
apache-2.0
2,730
0.007692
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License,...
enses/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 und...
: send = 'PRIVMSG %s :%s\r\n' % (chan, words) sock.send(send) def run(self): global done while not done: msg = raw_input('IRC > ') if msg == 'QUIT': sock.send('QUIT') done = True self.say(channel, msg) ...
ytsapras/robonet_site
events/management/commands/fetch_obs_for_field.py
Python
gpl-2.0
879
0.009101
# -*- coding: utf-8 -*- """ Created on Mon Apr 24 10:55:03 2017 @author: rstreet """ from django.core.managemen
t.base import BaseComman
d from django.contrib.auth.models import User from events.models import Field, ObsRequest from sys import exit from scripts import query_db class Command(BaseCommand): help = '' def add_arguments(self, parser): parser.add_argument('field', nargs='+', type=str) def _fetch_obs_for_field...
julien-girard/openstick
openstick/openstick.py
Python
gpl-3.0
8,148
0.001473
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Julien Girard # # Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3 ; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://http://www.gnu.org/licenses/gpl-3.0.htm...
socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: # Test if port is open s.bind(("", p)) is_open = p except socket.error as e: # If
port is use, we try with next port if e.errno == 98: is_open = is_open_port(p + 1) else: print(e) except OverflowError as e: # If port is overflow, we get a random open port is_open = get_open_port() return is_open def get_fw...
pmghalvorsen/gramps_branch
gramps/gen/datehandler/_datestrings.py
Python
gpl-2.0
14,146
0.012588
# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2013 Vassilii Khachaturov # # 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 ...
me inflections - short month form||Jan"), _("localized lexeme inflections - short month form||Feb"), _("localized lexeme inflections - short
month form||Mar"), _("localized lexeme inflections - short month form||Apr"), _("localized lexeme inflections - short month form||May"), _("localized lexeme inflections - short month form||Jun"), _("localized lexeme inflections - short month form||Jul"), ...
stvstnfrd/edx-platform
lms/lib/courseware_search/test/test_lms_result_processor.py
Python
agpl-3.0
3,315
0.001207
""" Tests for the lms_result_processor """ import six import pytest from lms.djangoapps.courseware.tests.factories import UserFactory from lms.lib.courseware_search.lms_result_processor import LmsSearchResultProcessor from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tes...
obal_staff = UserFactory(is_staff=True) self.course = CourseFactory.create( org='Elasticsearch', course='ES101', run='test_run', display_name='El
asticsearch test course', ) self.section = ItemFactory.create( parent=self.course, category='chapter', display_name='Test Section', ) self.subsection = ItemFactory.create( parent=self.section, category='sequential', ...