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
giantas/elibrary
repo/urls.py
Python
mit
535
0.018692
from django.conf.urls import url from . import views app_name = 'repo' urlpatterns =
[ url(r'^$', views.home, name='home'), url(r'^home/$', views.hom
e, name='home'), url(r'^library/$', views.library, name='library'), url(r'^login/$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^results/?P<form>[A-Za-z]+/$', views.results, name='results'), url(r'^(?P<sn>[-\/\d\w]{5,100})/borrow/$', views.borrow, name='borrow'), #url(...
kylon/pacman-fakeroot
test/pacman/tests/upgrade042.py
Python
gpl-2.0
725
0.002759
self.description = "Backup file relocation" lp1 = pmpkg("bash") lp1.files = ["etc/profile*"] lp1.backup = ["etc/profile"] self.addpkg2db("local", lp1) p1 = pmpkg("bash", "1.0-2") self.addpkg(p1) lp2 = pmpkg("filesystem") self.addpkg2db("local", lp2) p2 = pmpkg("filesystem", "1.0-2") p2.files = ["etc/profile**"] p2....
me() for p in (p1, p2)]) self.filesystem = ["etc/profile"] self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSION=bash|1.0-2") self.addrule("PKG_VERSION=filesystem|1.0-2") self.addrule("!FILE_PACSAVE=etc/profile") self.a
ddrule("FILE_PACNEW=etc/profile") self.addrule("FILE_EXIST=etc/profile")
ingadhoc/account-payment
account_payment_group/hooks.py
Python
agpl-3.0
1,366
0.000732
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import api, SUPERUSER_ID _logger = logging.getLogger(__name__) def post_init_hook(cr, registry): """ Create a payment group for every existint payment """ env = api.Environment(cr, SUPERUSER_ID, {}) # payments...
tate = payment.state in ['sent', 'reconciled'] and 'posted' or payment.state _state = _state if _state != 'cancelled' else 'cancel' env['account.payment.group'].create({ 'company_id': payment.company_id.id, 'partner_type': payment.partner_type, 'partner_id': payment.p...
, 'state': _state, })
showell/zulip
analytics/lib/counts.py
Python
apache-2.0
29,578
0.003719
import logging import time from collections import OrderedDict, defaultdict from datetime import datetime, timedelta from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union from django.conf import settings from django.db import connection from django.db.models import F from psycopg2.sql import SQL, C...
ency == CountStat.DAY: time_increment = timedelta(days=1) else: raise AssertionError(f"Unknown frequency: {stat.frequency}") verify_UTC(fill_to_time) if floor_to_hour(fill_to_time) != fill_to_time: raise ValueError(f"fill_to_time must be on an hour boundary: {fill_to_time}") fi...
if fill_state is None: currently_filled = installation_epoch() fill_state = FillState.objects.create(property=stat.property, end_time=currently_filled, state=FillState.DONE) logger.info("INITIALIZED %...
petterip/exam-archive
test/rest_api_test_course.py
Python
mit
16,344
0.006975
''' Testing class for database API's course related functions. Authors: Ari Kairala, Petteri Ponsimaa Originally adopted from Ivan's exercise 1 test class. ''' import unittest, hashlib import re, base64, copy, json, server from database_api_test_common import BaseTestCase, db from flask import json, jsonify...
{"name": "teacherId", "value": 2}] } } course_resource_url = '/exam_archive/api/archives/1/courses/1/' course_re
source_not_allowed_url = '/exam_archive/api/archives/2/courses/1/' courselist_resource_url = '/exam_archive/api/archives/1/courses/' # Set a ready header for authorized admin user header_auth = {'Authorization': 'Basic ' + base64.b64encode(super_user + ":" + super_pw)} # Define a lis...
hazelnusse/sympy-old
bin/sympy_time.py
Python
bsd-3-clause
1,207
0.023198
import time seen = set() import_order = [] elapsed_times = {} level = 0 parent = None children = {} def new_import(name, globals={}, locals={}, fromlist=[]): global level, parent if name in seen: return old_import(name, globals, locals, fromlist) seen.add(name) import_order.append((name, ...
ent t2 = time.time() elapsed_times[name] = t2-t1 return module old_import = __builtins__.__import__ __builtins__.__import__ = new_import from sympy import * parents = {} is_parent = {} for name, level, parent in import_order: parents[name] = parent is_parent[parent] = True print "== Tree =...
rint "\n" print "== Slowest (including children) ==" slowest = sorted((t, name) for (name, t) in elapsed_times.items())[-50:] for elapsed_time, name in slowest[::-1]: print "%.3f %s (%s)" % (elapsed_time, name, parents[name])
wileeam/airflow
airflow/operators/dummy_operator.py
Python
apache-2.0
1,203
0
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the
# "License"); you may not 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, WITHOU...
ither express or implied. See the License for the # specific language governing permissions and limitations # under the License. from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DummyOperator(BaseOperator): """ Operator that does literally nothing. It can be ...
nachoplus/cronoStamper
zmqClient.py
Python
gpl-2.0
568
0.021127
#!/usr/bin/python ''' Example of zmq client. Can be used to record test data on remote PC Nacho Mas January-2017 ''' import sys import zmq import time import json from
config import * # Socket to talk to server context = zmq.Context() socket = context.socket(zmq.SUB) #socket.setsockopt(zmq.CONFLATE, 1) socket.connect ("tcp
://cronostamper:%s" % zmqShutterPort) topicfilter = ShutterFlange socket.setsockopt(zmq.SUBSCRIBE, topicfilter) # Process while True: topic, msg = demogrify(socket.recv()) print "%f" % msg['unixUTC'] #time.sleep(5)
psf/black
src/black_primer/lib.py
Python
mit
13,941
0.001507
import asyncio import errno import json import logging import os import stat import sys from functools import partial from pathlib import Path from platform import system from shutil import rmtree, which from subprocess import CalledProcessError from sys import version_info from tempfile import TemporaryDirectory from ...
din_test else repo_path try: LOG.debug(f"Running black for {project_name}: {' '.join(cmd)}") _stdout, _stderr = await _gen_check_output( cmd, cwd=cwd_path, env=env, stdin=stdin, timeout=timeout ) except asyncio.TimeoutError: results.stats["...
except CalledProcessError as cpe: # TODO: Tune for smarter for higher signal # If any other return value than 1 we raise - can disable project in config if cpe.returncode == 1: if not project_config["expect_formatting_changes"]: results.stats["f...
cg31/tensorflow
tensorflow/contrib/distributions/python/ops/operator_test_util.py
Python
apache-2.0
6,295
0.008896
# 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 applica...
k, 5))) self._compare_results( expected=tf.matrix_solve(mat, x).eval(), actual=operator.sqrt_solve(operator.sqrt_solve(x))) def testAddToTensor(self): with self.test_session(): for batch_shape in [(), (2, 3,)]: for k in [1, 4]: operator, mat = self._...
l(), actual=operator.add_to_tensor(tensor))
ismailsunni/f3-factor-finder
core/tweet_model.py
Python
gpl-2.0
4,719
0.042594
#!/F3/core/tweet_model.py # A class for representating a tweet. # Author : Ismail Sunni/@ismailsunni # Created : 2012-03-30 from db_control import db_conn from datetime import datetime, timedelta import preprocess as pp class tweet_model: '''A class for representating a tweet.''' def __init__(self, id...
[1] sentiment = row[3] negation = row[4] tweets.append(tweet_model(id, time, text, sentiment, negation)) return tweets def get_test_data_by_duration(keyword = "", start_time = None, end_time = None, duration_hour = 1): '''return test data divide byu duration.''' duration_second = duration_hour * ...
ion = timedelta(0, duration_second) cur_time = start_time retval = [] dur_times = [] while (cur_time + delta_duration < end_time): retval.append(get_test_data(keyword, cur_time, cur_time + delta_duration)) dur_times.append(cur_time) cur_time += delta_duration if (cur_time < end_time): dur_t...
sdispater/orator
tests/orm/test_factory.py
Python
mit
4,197
0.000477
# -*- coding: utf-8 -*- from orator.orm import Factory, Model, belongs_to, has_many from orator.connections import SQLiteConnection from orator.connectors import SQLiteConnector from .. import OratorTestCase, mock class FactoryTestCase(OratorTestCase): @classmethod def setUpClass(cls): Model.set_con...
def test_factory_create_with_attributes(self): user = self.factory.create(User, name="foo", email="foo@bar.com") self.assertIsInstance(user, User) self.assertEqual("foo", user.name) self.assertEqual("foo@bar.com", user.email) self.assertIsNotNone(User.where("name", user.name).fi...
e(self.factory.make(Post))) self.assertEqual(3, len(users)) self.assertIsInstance(users[0], User) self.assertEqual(3, User.count()) self.assertEqual(3, Post.count()) def test_factory_call(self): user = self.factory(User).create() self.assertFalse(user.admin) ...
dtroyer/osc-debug
oscdebug/tests/v1/test_auth.py
Python
apache-2.0
1,401
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distrib...
age governing permissions and limitations # under the License. # import mock from oscdebug.tests import base from oscdebug.v1 import auth class TestAuthTypeShow(base.TestCommand): def setUp(self): super(TestAuthTypeShow, self).setUp() # Get the command object to test self.cmd = auth....
('auth_type', 'password'), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) # DisplayCommandBase.take_action() returns two tuples columns, data = self.cmd.take_action(parsed_args) collist = ('name', 'options') self.assertEqual(collist, columns) ...
alephobjects/Cura2
cura/Scene/GCodeListDecorator.py
Python
lgpl-3.0
316
0
from UM.Scene.SceneNodeDecorat
or import SceneNodeDecorator class GCodeListDecorator(SceneNodeDecorator): def __init__(self): super().__init__() self._gcode_list = [] def getGCodeList(self): return self._gcode_list def setGCodeList(self, list): self._g
code_list = list
alvarouc/ica
ica/__init__.py
Python
gpl-3.0
49
0.020408
from .ica imp
ort * #from .ica_gpu i
mport ica_gpu
electrolinux/weblate
weblate/accounts/tests.py
Python
gpl-3.0
26,044
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
_mailbox() response = self.client.get(url, follow=True) self.assertRedirects( response, '{0}#auth'.format(reverse('profile')) ) # Check database models user = User.objects.get(username='username')
self.assertEqual( VerifiedEmail.objects.filter(social__user=user).count(), 2 ) self.assertTrue( VerifiedEmail.objects.filter( social__user=user, email='second@example.net' ).exists() ) class NoCookieRegistrationTest(RegistrationTest):...
dnjohnstone/hyperspy
hyperspy/tests/component/test_components.py
Python
gpl-3.0
20,259
0.000346
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
ed"), TRUE_FALSE_2_TUPLE) def test_estimate_parameters(self, only_current, binned): self.m.signal.metadata.Signal.binned = binned s = self.m.as_signal(parallel=False) assert s.metadata.Signal.binned == binned g = hs.model.components1D.PowerLaw()
g.estimate_parameters(s, None, None, only_current=only_current) A_value = 1008.4913 if binned else 1006.4378 r_value = 4.001768 if binned else 4.001752 assert_allclose(g.A.value, A_value) assert_allclose(g.r.value, r_value) if only_current: A_value, r_value =...
thegodone/pyms
Experiment/Class.py
Python
gpl-2.0
3,288
0.012165
""" Models a GC-MS experiment represented by a list of signal peaks """ ############################################################################# # # # PyMS software for processing of metabolomic mass-spectrometry
data # # Copyright (C) 2005-2012 Vladimir Likic # # # # This program is free software; you can redistribute
it and/or modify # # it under the terms of the GNU General Public License version 2 as # # published by the Free Software Foundation. # # # # This program is distributed in the hope that it will be ...
kevinharvey/django-tourney
tourney/players/apps.py
Python
gpl-3.0
89
0
from django.app
s import AppConfig class PlayersConfig(AppConfig): name = 'players'
adamjmcgrath/fridayfilmclub
src/tests/test_model_league.py
Python
mpl-2.0
1,925
0.002597
#!/usr/bin/python # # Copyright Friday Film Club. All Rights Reserved. """League unit tests.""" __author__ = 'adamjmcgrath@gmail.com (Adam McGrath)' import unittest import base import helpers import models class LeagueTestCase(base.TestCase): def testPostPutHook(self): league_owner = helpers.user() le...
e = models.League(name='Foo', owner=league_owner.put(), users=[league_member_1.put(), league_member_2.put()]) league_key = lea
gue.put() self.assertListEqual(league_owner.leagues, [league_key]) self.assertListEqual(league_member_1.leagues, [league_key]) self.assertListEqual(league_member_2.leagues, [league_key]) league.users = [league_member_2.key] league.put() self.assertListEqual(league_member_1.leagues, []) self...
codeofdusk/ProjectMagenta
src/accessible_output2/__init__.py
Python
gpl-2.0
885
0.027119
import ctypes import os import types from platform_utils import paths def load_library(libname): if paths.is_frozen(): libfile = os.path.join(paths.embedded_data_path(), '
accessible_output2', 'lib', libname) else: libfile = os.path.join(paths.module_path(), 'lib',
libname) return ctypes.windll[libfile] def get_output_classes(): import outputs module_type = types.ModuleType classes = [m.output_class for m in outputs.__dict__.itervalues() if type(m) == module_type and hasattr(m, 'output_class')] return sorted(classes, key=lambda c: c.priority) def find_datafiles(): import...
dchud/sentinel
canary/study.py
Python
mit
63,030
0.009107
# $Id$ import copy import logging import time import traceback import types from quixote import form2 from quixote.html import htmltext import canary.context from canary.gazeteer import Feature from canary.qx_defs import MyForm from canary.utils import DTable, render_capitalized import dtuple class ExposureRoute ...
self.uid = self.get_new_uid(context) else: # Assume all calls to save() are a
fter all routes have been removed # already by "DELETE FROM exposure_routes" in methodology.save() try: cursor.execute(""" INSERT INTO exposure_routes (uid, study_id, methodology_id, route) VALUES (%...
jbarmash/rhaptos2.user
rhaptos2/user/cnxbase.py
Python
agpl-3.0
1,673
0.003586
#!/usr/bin/env python #! -*- coding: utf-8 -*- ### # Copyright (c) Rice University 2012-13 # This software is subject to # the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. ### """ THis exists solely to provide less typing for a "leaf node" in a simple real...
tr def safe_type_out(self, col): """return the value of a coulmn field safely as something that json can use This is essentially a JSONEncoder sublclass inside this object. """ if isinstance(type(col.type), sqlalchemy.types.DateTime): outstr = getattr(self...
return outstr
bashu/django-facebox
example/urls.py
Python
bsd-3-clause
266
0.003759
from django.conf.urls import url from django.views.gener
ic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='homepage.html')), url(r'^remote.html$', TemplateView.as_view(template_name='remote.html'), name="
remote.html"), ]
nanditav/15712-TensorFlow
tensorflow/contrib/metrics/python/ops/metric_ops_test.py
Python
apache-2.0
163,728
0.009143
# 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 applica...
__ import division from __future__ import print_function im
port math import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from tensorflow.contrib.metrics.python.ops import metric_ops NAN = float('nan') metrics = tf.contrib.metrics def _enqueue_vector(sess, queue, values, shape=None): if not shape: shape = (1, l...
tvtsoft/odoo8
addons/crm/models/crm_activity.py
Python
agpl-3.0
2,406
0.001663
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp import api, fields, models class CrmActivity(models.Model): ''
' CrmActivity is a model introduced in Odoo v9 that models activi
ties performed in CRM, like phonecalls, sending emails, making demonstrations, ... Users are able to configure their custom activities. Each activity has up to three next activities. This allows to model light custom workflows. This way sales manager can configure their crm workflow that saleperson...
waile23/todo
utils/xwjemail.py
Python
mit
2,175
0.063391
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng ''' import smtplib from email.mime.text import MIMEText import urllib import web class XWJemail: ''' classdocs ''' def __init__(self, params): ''' Constructor ''' pa
ss @staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s" %(web.ctx.sitehost,urllib.urlencode({'email':user.u_email,"v":hash})) mail_body = """ <html> <head></head> <body> <h4>%s,你好</h4> 您刚才在 liulin.info 申请了找回密码。<br> 请点击下面的链接来重置密码:<br> <a href="%s">%s</a><br> 如果无法点击上面的链接,您可以复制该地址,并粘帖在浏览器的地址
栏中访问。<br> </body> </html> """ % (web.utf8(user.u_name),link,link) #mail_body = web.utf8(mail_body) if isinstance(mail_body,unicode): mail_body = str(mail_body) mail_from = "liulin.info<wukong10086@163.com>" mail_to = user.u_email mail_subject = 'liulin.info重置密码邮件' msg = MIMEText(mail_body,'html',...
schimar/hts_tools
vcf2nex012.py
Python
gpl-2.0
1,837
0.004355
#!/usr/bin/python # This script reads through a enotype likelihood file and the respective mean genotype likelihood file. It writes a nexus file for all individuals and the given genotypesi, with '0' for ref homozygote, '1' for heterozygote, and '2' for alt homozygote. # Usage: ~/vcf2nex012.py pubRetStriUG_unlnkd.gl ...
fold:bp (which is not in the same order as the vcf file, resulting from vcf2gl.py) with open(argv[1], 'rb') as gl_file: scafPos_gl = list() for line in gl_file: if line.split(' ')[0] == '65': continue elif line.split(' ')[0] == 'CR1043': ind_id = line.split(' ')
ind_id[len(ind_id)-1] = ind_id[len(ind_id)-1].split('\n')[0] else: scafPos_gl.append(line.split(' ')[0]) # read the file with mean genotypes with open(argv[2], 'rb') as mean_gt_file: ind_dict = dict() for line in mean_gt_file: gt_line = line.split(' ') for i, i...
hainm/pythran
pythran/optimizations/list_comp_to_map.py
Python
bsd-3-clause
2,611
0
""" ListCompToMap transforms list comprehension into intrinsics. """ from pythran.analyses import OptimizableComprehension from pythran.passmanager import Transformation from pythran.transformations import NormalizeTuples import ast class ListCompToMap(Transformat
ion): ''' Transforms list comprehension into intrinsics. >>> import ast >>> from pythran import passmanager, backend >>> node = ast.parse("[x*x for x
in range(10)]") >>> pm = passmanager.PassManager("test") >>> _, node = pm.apply(ListCompToMap, node) >>> print pm.dump(backend.Python, node) __builtin__.map((lambda x: (x * x)), range(10)) ''' def __init__(self): Transformation.__init__(self, NormalizeTuples, ...
dpimenov/tvdb_api
tests/gprof2dot.py
Python
unlicense
53,218
0.004209
#!/usr/bin/env python # # Copyright 2008 Jose Fonseca # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
= self class Profile(Object): """The whole profile.""" def __init__(self): Object.__init__(self) self.functions = {} self.cycles = [] de
f add_function(self, function): if function.id in self.functions: sys.stderr.write('warning: overwriting function %s (id %s)\n' % (function.name, str(function.id))) self.functions[function.id] = function def add_cycle(self, cycle): self.cycles.append(cycle) def validate(sel...
QTB-HHU/ModelHeatShock
HSM_ODEsSystem10or9eqs.py
Python
gpl-3.0
5,759
0.009029
from HSM_Reactions import * ########## RIGHT MEMBERS OF ODEs, rewritten with only 10 equations to isolate those that are independent ############## def f10eqs(t, y, ksetDict, TparamSet, REACparamSet, DirectControlnuPp, IC_PplusPp, IC_SplusSs): #P = y[0] Ph = y[0] #S = y[2] Ss = y[1] F = y[2] ...
, n2, P0const), # Ss nuF(I, Fs, kF0) + piF(RF, kFpi0) + nuFGp(FG, kFGp) - nuFG(G, F, kFG) - nuFp(F,
Ss, kFp0) - etaF(F, ketaF), # F - nuF(I, Fs, kF0) + nuFp(F, Ss, kFp0) + nuFsGp(FsG, kFsGp) - nuFsG(G, Fs, kFsG), # Fs #nuFsGp(FsG, kFsGp) + nuFGp(FG, kFGp) - nuFG(G, F, kFG) - nuFsG(G, Fs, kFsG), # G nuFsG(G, Fs, kFsG) + nuFs(FG, kFs) - nuFsp(FsG, I, kFsp) - nuFsGp(FsG, kFsGp), # FsG ...
LingyuGitHub/codingofly
python/threading/mthreading.py
Python
gpl-3.0
699
0.013413
#!/usr/bin/env python3 ######################################################################### # File Na
me: mthreading.py # Author: ly # Created Time: Wed 05 Jul 2017 08:46:57 PM CST # Description: #################
######################################################## # -*- coding: utf-8 -*- import time import threading def play(name,count): for i in range(1,count): print('%s %d in %d' %(name, i, count)) time.sleep(1) return if __name__=='__main__': t1=threading.Thread(target=play, args=('t1',10...
pymedusa/SickRage
medusa/tv/base.py
Python
gpl-3.0
2,303
0.001303
# coding=utf-8 """TV base class.""" from __future__ import unicode_literals import threading from builtins import object from medusa.indexers.config import INDEXER_TVDBV2 class Identifier(object): """Base identifier class.""" def __bool__(self): """Magic method.""" raise NotImplementedError...
"""Initialize class. :param indexer: :type indexer: int :param indexerid: :type indexerid: int :param ignored_properties: :type ignored_properties: set(str) """ self.__dirty = True self.__ignored_properties = ignored_properties | {'lock'} ...
t(indexer) self.indexerid = int(indexerid) self.lock = threading.Lock() @property def series_id(self): """To make a clear distinction between an indexer and the id for the series. You can now also use series_id.""" return self.indexerid def __setattr__(self, key, value): ...
OSSOS/MOP
src/ossos/core/ossos/match.py
Python
gpl-3.0
13,649
0.005495
from astropy.io import ascii from astropy.table import MaskedColumn, Table, Column import logging import math import numpy import os from .downloads.cutouts.downloader import ImageDownloader from . import util from .downloads.cutouts.source import SourceCutout from astropy.time import Time from .astrom import Observati...
((observations[observation]['x'], # observations[observation]['y']), hdulist_index) observations[observation]['mags'] = daophot.phot(source._hdu_on_disk(hdulist_index), observations[observation]['x'], ...
observations[observation]['y'], aperture=source.apcor.aperture, sky=source.apcor.sky, swidth=source.apcor.swidth, ...
sdlBasic/sdlbrt
win32/mingw/opt/lib/python2.7/idlelib/EditorWindow.py
Python
lgpl-2.1
66,626
0.001816
import sys import os import platform import re import imp from Tkinter import * import tkSimpleDialog import tkMessageBox import webbrowser from idlelib.MultiCall import MultiCallCreator from idlelib import idlever from idlelib import WindowList from idlelib import SearchDialog from idlelib import GrepDialog from idle...
idlelib.IOBinding import IOBinding, filesystemencoding, encoding from idlelib import Bindings from Tkinter import Toplevel from idlelib.MultiStatusBar import MultiStatusBar help_url = None def __i
nit__(self, flist=None, filename=None, key=None, root=None): if EditorWindow.help_url is None: dochome = os.path.join(sys.prefix, 'Doc', 'index.html') if sys.platform.count('linux'): # look for html docs in a couple of standard places pyver = 'python-docs...
dhylands/python_lcd
lcd/esp8266_i2c_lcd_test.py
Python
mit
1,476
0.002033
"""Implements a HD44780 character LCD connected via PCF8574 on I2C. This was tested with: https://www.wemos.cc/product/d1-mini.html"""
from time import sleep_ms, ticks_ms from machine import I2C, Pin from esp8266_i2c_lcd import I2cLcd # The PCF8574 has a jumper selectable address: 0x20 - 0x27 DEFAULT_I2C_ADDR = 0x27 def test_main(): """Test function for verifying basic functionality.""" print("Running test_main") i2c = I2C(scl=Pin(5), ...
4), freq=100000) lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16) lcd.putstr("It Works!\nSecond Line") sleep_ms(3000) lcd.clear() count = 0 while True: lcd.move_to(0, 0) lcd.putstr("%7d" % (ticks_ms() // 1000)) sleep_ms(1000) count += 1 if count % 10 == 3: ...
mikkqu/rc-chrysalis
scapp/moment.py
Python
bsd-2-clause
500
0.006
from jinja2 import Markup class momentjs(object): def __init__(self, timestamp): self.timestamp = timestamp def render(self, format): return Markup("<script>\ndocument.write(moment(\"%s\").%s);\n</script>" % (self.timestamp.strftime("%Y-%m-%dT%H:%M:%S
Z"), format)) def format(self, fmt): return s
elf.render("format(\"%s\")" % fmt) def calendar(self): return self.render("calendar()") def fromNow(self): return self.render("fromNow()")
dc3-plaso/plaso
tests/parsers/test_lib.py
Python
apache-2.0
8,486
0.004949
# -*- coding: utf-8 -*- """Parser related functions and classes for testing.""" import heapq from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import resolver as path_spec_resolver from plaso.containers import sessions from plaso.engine imp...
list[EventObject]: sorted events. """ events_heap = _EventsHeap() events_heap.PushEvents(events) return list(events_heap.PopEvents()) def _GetShortMessage(self, message_string): """Shortens a message string to a maximum of 80 character width. Args: me
ssage_string (str): message string. Returns: str: short message string, if it is longer than 80 characters it will be shortened to it's first 77 characters followed by a "...". """ if len(message_string) > 80: return u'{0:s}...'.format(message_string[0:77]) return message_string...
biomodels/MODEL1201230000
setup.py
Python
cc0-1.0
377
0.005305
from setuptools import setup, find_packages setup(name='MODEL1201230000',
version=20140916, description='MODEL1201230000 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1201230000', maintainer='Stanley Gu', main
tainer_url='stanleygu@gmail.com', packages=find_packages(), package_data={'': ['*.xml', 'README.md']}, )
wakatime/wakatime
wakatime/packages/py27/pygments/lexers/ncl.py
Python
bsd-3-clause
63,986
0.004095
# -*- coding: utf-8 -*- """ pygments.lexers.ncl ~~~~~~~~~~~~~~~~~~~ Lexers for NCAR Command Language. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, include, words from pygments.token...
', 'echo_off', 'echo_on', 'eof2data', 'eof_varimax', 'eofcor', '
eofcor_pcmsg', 'eofcor_ts', 'eofcov', 'eofcov_pcmsg', 'eofcov_ts', 'eofunc', 'eofunc_ts', 'eofunc_varimax', 'equiv_sample_size', 'erf', 'erfc', 'esacr', 'esacv', 'esccr', 'esccv', 'escorc', 'escorc_n', 'escovc', 'exit', 'exp', 'exp_tapersh', 'exp_tapersh_wgts', ...
AustereCuriosity/astropy
astropy/tests/helper.py
Python
bsd-3-clause
18,299
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides the tools used to internally run the astropy test suite from the installed astropy. It makes use of the `pytest` testing framework. """ from __future__ import (absolute_import, division, print_function, uni...
temporary # directory, so we replace all the paths with the true source # path. Note that this will not work properly for packages that still # rely on 2to3. try: # Coverage 4.0: _harvest_data has been renamed to get_data, the # lines dict is private cov.get_data() except At...
lines.keys()): new_path = os.path.relpath( os.path.realpath(key), os.path.realpath(testing_path)) new_path = os.path.abspath( os.path.join(rootdir, new_path)) lines[new_path] = lines.pop(key) color_print('Saving coverage data in .coverage...', 'green') ...
Stackato-Apps/py3kwsgitest
tables.py
Python
mit
647
0.006182
import sqlalchemy metadata = sqlalchemy.MetaData() log_table = sqlalchemy.Table('log', metadata, sqlalchemy.Column('id', sqlalchemy.Inte
ger, primary_key=True), sqlalchemy.Column('filename', sqlalchemy.Unicode), sqlalchemy.Column('digest', sqlalchemy.Unicode), sqlalchemy.Column('comment', sqlalchemy.Unicode), sqlalchemy.Column('user_agent'...
chemy.Unicode), sqlalchemy.Column('traceback', sqlalchemy.Unicode)) def init(engine): metadata.create_all(bind=engine)
pashinin-com/pashinin.com
src/core/migrations/0002_auto_20161030_1553.py
Python
gpl-3.0
478
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-30 12:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migra
tion): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='user', name='added', ), migrations.RemoveField(
model_name='user', name='changed', ), ]
Yarrick13/hwasp
tests/wasp1/AllAnswerSets/edbidb_3.test.py
Python
apache-2.0
199
0.005025
input = """ g(1). g(2). g(3). f(a,b). f(A,B):- g(A), g(B). f(a,a). """ output
= """ {f(
1,1), f(1,2), f(1,3), f(2,1), f(2,2), f(2,3), f(3,1), f(3,2), f(3,3), f(a,a), f(a,b), g(1), g(2), g(3)} """
kcompher/velox-modelserver
bin/cluster/fabfile.py
Python
apache-2.0
27
0
from velox_deploy
im
port *
Azulinho/ansible
lib/ansible/plugins/lookup/redis.py
Python
gpl-3.0
3,113
0.002891
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # (c) 2017 Ansible Project # 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 DOCUMENTATION = """ lookup: redis author: - Jan-P...
): if not HAVE_REDIS: raise AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed") # get options self.set_options(direct=kwargs) # setup connection host
= self.get_option('host') port = self.get_option('port') socket = self.get_option('socket') if socket is None: conn = redis.Redis(host=host, port=port) else: conn = redis.Redis(unix_socket_path=socket) ret = [] for term in terms: try: ...
tschmorleiz/amcat
amcat/scripts/article_upload/controller.py
Python
agpl-3.0
3,148
0.0054
from __future__ import absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content...
r.project) try: articles, errors = Article.create_articles(self.articles, scraper.articleset) self.saved_article_ids = {getattr(a, "duplicate_of", a.id) for a in self.articles} for e in errors: self.errors.append(ScrapeError(None,None,e)) except Excep...
: self.errors.append(ScrapeError(None,None,e)) log.exception("scraper._get_units failed") return self.saved_article_ids def _set_default(obj, attr, val): try: if getattr(obj, attr, None) is not None: return except Project.DoesNotExist: pass # django throws DNE o...
dfunckt/django
tests/urlpatterns_reverse/tests.py
Python
bsd-3-clause
50,749
0.003074
# -*- coding: utf-8 -*- """ Unit tests for reverse URL lookups. """ from __future__ import unicode_literals import sys import threading import unittest from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.conf.urls import include, url from django.contrib.auth.models import...
'/included/12/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(),
{'arg2': '37'} ), # Unnamed views should have None as the url_name. Regression data for #21157. ( '/unnamed/normal/42/37/', None, '', '', 'urlpatterns_reverse.views.empty_view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} ), ( '/unnamed/view_class/42/37/...
ftomassetti/worldengine
worldengine/views/WatermapView.py
Python
mit
880
0
from worldengine.simulations.basic import * import random from worldengine.views.basic import color_prop from PyQt4 import QtGui class WatermapView(object): def is_applicable(self, world): return world.has_watermap() def draw(self, world, canvas): width = world.width height = world.h...
for x in range(0, width): if world.is_ocean((x, y)): r = g = 0 b = 255 else: w = world.watermap['data'][y][x]
if w > th: r = g = 0 b = 255 else: r = g = b = 0 col = QtGui.QColor(r, g, b) canvas.setPixel(x, y, col.rgb())
NuGrid/NuGridPy
nugridpy/version.py
Python
bsd-3-clause
54
0
"""NuGridPy package ve
rsion""" __
version__ = '0.7.6'
pegler/django-thumbs
setup.py
Python
bsd-2-clause
691
0.004342
#!/usr/bin/env python # -*- encoding: utf-8 -*- # -*- mode: python -*- # vi: set ft=python : import os from setuptools
import setup, find_packages README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README') DESCRIPTION = 'Easy image thumbnails in Django.' if os.path.exists(README_PATH): LONG_DESCRIPTION = open(README_PATH).read() else: LONG_DESCRIPTION = DESCRIPTION setup( name='django-thumbs', ve
rsion='1.0.4', install_requires=['django'], description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Matt Pegler', author_email='matt@pegler.co', url='https://github.com/pegler/django-thumbs/', packages=['thumbs'], )
sublee/lets
lets/transparentlet.py
Python
bsd-3-clause
600
0
# -*- coding: utf-8 -*- """ lets.transparentlet ~~~~~~~~~~~~~~~~~~~ Deprecated. gevent-1.1 keeps a traceback exactly. If you want to just prevent to print an exception by the hub, use :mod:`lets.quietlet` inste
ad. :copyright: (c) 2013-2018 by Heungsub Lee :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from gevent.pool import Group as TransparentGroup from lets.quietlet import quiet as no_error_handling from lets.quietlet import Quietlet as Transparentlet __all__
= ['Transparentlet', 'TransparentGroup', 'no_error_handling']
facetothefate/contrail-controller
src/opserver/partition_handler.py
Python
apache-2.0
23,447
0.00917
#!/usr/bin/python from gevent import monkey monkey.patch_all() import logging import gevent from gevent.coros import BoundedSemaphore from kafka import KafkaClient, KeyedProducer, SimpleConsumer, common from uveserver import UVEServer import os import json import copy import traceback import uuid import struct import ...
aceback.format_exc())) lredis = None if pb is not None:
pb.close() pb = None gevent.sleep(2) return None class UveStreamer(gevent.Greenlet): def __init__(self, logger, q, rfile, agp_cb, partitions, rpass): gevent.Greenlet.__init__(self) self._logger = logger self._q = q self._r...
Phyks/Flatisfy
modules/seloger/pages.py
Python
mit
9,785
0.002146
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of a woob module. # # This woob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, o...
self.agency_doc = el['agency'] self.el = el['advert'] obj_id = Dict('id') def obj_house_type(self): naturebien = Dict('propertyNatureId')(self) try: return
next(k for k, v in RET.items() if v == naturebien) except StopIteration: return NotLoaded def obj_type(self): idType = Dict('idTransactionType')(self) try: type = next(k for k, v in TYPES.items() if v == idType) if type == POS...
droidzone/Supernova-Kernel
tools/tools/perf/scripts/python/check-perf-trace.py
Python
gpl-2.0
2,501
0.02479
# perf trace event handlers, generated by perf trace -g python # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Ba...
ame, common_cpu, common_secs, common_nsecs, co
mmon_pid, common_comm) print_uncommon(context) print "vec=%s\n" % \ (symbol_str("irq__softirq_entry", "vec", vec)), def kmem__kmalloc(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, call_site, ptr, bytes_req, bytes_alloc, gfp_flags): print_header(event_na...
richo/flysight-manager
flysight_manager/config.py
Python
mit
6,142
0.002279
# flake8: noqa import sys import toml import log from .uploader import DropboxUploader from .file_manager import DirectoryPoller, VolumePoller SECT = 'flysight-manager' class ConfigError(Exception): pass class FlysightConfig(object): pass class DropboxConfig(object): pass class VimeoConfig(object...
_addr = get("from") _cfg.to_addr = get("to") _cfg.subject = get("subj
ect") return _cfg def load_pushover_opts(self, cfg): get = lambda x: cfg["pushover"][x] _cfg = PushoverConfig() _cfg.token = get("token") _cfg.user = get("user") return _cfg def load_youtube_opts(self, cfg): get = lambda x: cfg["youtube"][x] _cfg...
OpenNingia/l5r-character-manager-3
l5r/dialogs/newrankdlg.py
Python
gpl-3.0
3,473
0.001152
# -*- coding: utf-8 -*- # Copyright (C) 2014-2022 Daniele Simonetti # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # ...
f not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from PyQt5 import QtCore, QtGui, QtWidgets import l5r.widgets as widgets import l5r.api as api import l5r.api.character.rankadv class NextRankDlg(QtWidgets.QDialog): def __init__(self, pc, parent=None): super(...
gs(QtCore.Qt.Tool) self.setWindowTitle(self.tr("L5R: CM - Advance Rank")) def build_ui(self): vbox = QtWidgets.QVBoxLayout(self) vbox.addWidget(QtWidgets.QLabel(self.tr("""\ You can now advance your Rank, what would you want to do? """))) self.bt_...
ricardogsilva/django-mapserver
djangomapserver/migrations/0001_initial.py
Python
bsd-2-clause
8,539
0.00445
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='ClassObj', fields=[ ('id', models.AutoField(ver...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='LayerObj', fields=[ ...
, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255)), ('layer_type', models.SmallIntegerField(choices=[(3, b'raster'), (2, b'vector polygon'), (1, b'vector line'), (0, b'vector point')])), ('projection', models.CharField(default=b'init=epsg:...
antoinecarme/pyaf
tests/artificial/transf_None/trend_MovingAverage/cycle_30/ar_12/test_artificial_32_None_MovingAverage_30_12_20.py
Python
bsd-3-clause
264
0.087121
import pyaf.Bench.TS_datasets as tsds import tests.artificial.p
rocess_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 30, transform = "None", sigma = 0.0, exog_count = 2
0, ar_order = 12);
dshlai/oyprojectmanager
oyProjectManager/db/__init__.py
Python
bsd-2-clause
5,475
0.009315
# -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Erkan Ozgur Yilmaz # # This module is part of oyProjectManager and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause """ Database Module =============== This is where all the magic happens. .. versionadded:: 0.2.0 SQLite3 Datab...
maker(bind=engine) # create and save session object to session session = Session() query = session.query # initialize the db __init_db__() # TODO: create a test to check if the returned session is session return session def __init_db__(): """initializes the just setup
database It adds: - Users - VersionTypes to the database. """ logger.debug("db is newly created, initializing the db") global query global session # get the users from the config from oyProjectManager import conf # ------------------...
ezequielpereira/Time-Line
libs64/wx/lib/agw/cubecolourdialog.py
Python
gpl-3.0
139,714
0.003285
# --------------------------------------------------------------------------- # # CUBECOLOURDIALOG Widget wxPython IMPLEMENTATION # # Python Code By: # # Andrea Gavana, @ 16 Aug 2007 # Latest Revision: 14 Apr 2010, 12.00 GMT # # # TODO List # # 1. Find A Way To Reduce Flickering On The 2 ColourPanels; # # 2. See Why wx...
Mailing List!!! # # # End Of Comments # --------------------------------------------------------------------------- # """ CubeColourDialog is an alternative implementation of `wx.ColourDialog
`. Description =========== The CubeColourDialog is an alternative implementation of `wx.ColourDialog`, and it offers different functionalities with respect to the default wxPython one. It can be used as a replacement of `wx.ColourDialog` with exactly the same syntax and methods. Some features: - RGB components may...
Buggaboo/gimp-plugin-export-layers
export_layers/pygimplib/pgitemdata.py
Python
gpl-3.0
14,487
0.015669
#------------------------------------------------------------------------------- # # This file is part of pygimplib. # # Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com> # # pygimplib is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
=================== pdb = gimp.pdb #=============================================================================== class ItemData(object): """ This class is an interface to store all items (and item groups) of a certain type (e.g. layers, channels or paths) of a GIMP image in an ordered dictionary, allo...
to access the items via their names and get various custom attributes derived from the existing item attributes. Use one of the subclasses for items of a certain type: * `LayerData` for layers, * `ChannelData` for channels, * `PathData` for paths (vectors). For custom item attribute...
dnlcrl/PyFunt
pyfunt/spatial_up_sampling_nearest.py
Python
mit
2,179
0.001377
#!/usr/bin/env python # coding: utf-8 from module import Module import numpy as np try: from im2col_cyt import im2col_cython, col2im_cython except ImportError: print('Installation broken, please reinstall PyFunt') from numpy.lib.stride_tricks import as_strided def tile_array(a, b1, b2): r, c = a.shape ...
de x_reshaped = x.transpose(2, 3, 0, 1).flatten() out_cols = np.zeros(out_size) out_cols[:, np.arange(out_cols.shape[1])] = x_reshaped out = col2im_cython(out_cols, N * C, 1, H, W, pool_height, pool_width, padding=0, stride=stride) out
= out.reshape(out_size) return self.grad_input return self.output def update_grad_input(self, x, grad_output, scale=1): N, C, H, W = grad_output.shape pool_height = pool_width = self.scale_factor stride = self.scale_factor out_height = (H - pool_height) / stride ...
darren-wang/op
oslo_policy/_parser.py
Python
apache-2.0
8,552
0
# -*- coding: utf-8 -*- # # 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...
# Reduce the token stream results = meth(*self.values[-len(reduction):]) # Update the tokens and values self.tokens[-len(reduction):] = [r[0] for r in results]
self.values[-len(reduction):] = [r[1] for r in results] # Check for any more reductions return self.reduce() def shift(self, tok, value): """Adds one more token to the state. Calls :meth:`reduce`. """ self.tokens.append(tok) ...
gahlberg/pynet_class_work
class2/ex2a_telnet.py
Python
apache-2.0
1,588
0.003149
#!/usr/bin/env python import telnetlib import time import socket import sys import getpass TELNET_PORT = 23 TELNET_TIMEOUT = 6 def send_command(remote_conn, cmd): ''' Initiate the Telnet Session ''' cmd = cmd.rstrip() remote_conn.write(cmd + '\n') time.sleep(1) return remote_conn.read_ver...
sys.exit("Connection timed-out") def main(): ''' Connect to pynet-rtr1, login, and issue 'show ip int brief' ''' ip_addr = raw_input("IP address: ") ip_addr = ip_addr.strip() username = 'pyclass' password = getpass.getpass() remote_conn = telnet_connect(ip_addr) output = lo...
.read_very_eager() no_more(remote_conn) output = send_command(remote_conn, 'show ip int brief') print "\n\n" print output print "\n\n" remote_conn.close() if __name__ == "__main__": main()
csdevsc/colcat_crowdsourcing_application
manage/views.py
Python
mit
7,968
0.005522
from django.shortcuts import render, render_to_response from django.shortcuts import redirect from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.conf import settings from manage.forms import * from manage.models import * from...
response = HttpResponse(content_type='text/csv') response['Content-Disposition'
] = 'attachment; filename="batch.csv"' writer = csv.writer(response) headers = ['task_language_id', 'task_type_id', 'task_img_id'] writer.writerow(headers) for tid in task_choices: task = Task.objects.get(task_id=tid) task_info = [task.lan...
smjhnits/Praktikum_TU_D_16-17
Fortgeschrittenenpraktikum/Protokolle/V27_Zeeman-Effekt/Python/blau_s.py
Python
mit
2,866
0.010479
import numpy as np from scipy.stats import sem import scipy.constants as const from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) import matplo
tlib.pyplot as plt from scipy.optimize import curve_fit from PIL import Image import scipy.misc from pint import UnitRegistry u = UnitRegistry() Q_ = u.Quantity ## Wellenlängen in nm lambda_b = Q_(480.0, 'nanometer') n_b = 1.4635 h = Q_(const.h, 'joule * second') e_0 = Q_(const.e, 'coulomb') mu_bohr = Q_(const.physi...
hr magneton'][0], 'joule/tesla') c = Q_(const.c, 'meter / second') d = Q_(4, 'millimeter') dispsgebiet_b = lambda_b**2 / (2 * d) * np.sqrt(1 / (n_b**2 - 1)) ## Hysterese, B in mT def poly(x, a, b, c, d): return a * x**3 + b * x**2 + c * x + d B_auf = np.array([4, 87, 112,174, 230, 290, 352, 419, 476, 540, 60...
peterdemin/mutant
src/mutant_django_json/__init__.py
Python
isc
341
0
fro
m mutant_django.generator import DjangoBase def register(app): app.extend_generator('django', django_json_field) def django_json_field(gen): gen.field_generators['JSON'] = JSONField class JSONField(DjangoBase): DJANGO_FIELD = 'JSONField' def render_imports(self): return ['from jsonfield i...
tecnovert/particl-core
test/functional/wallet_descriptor.py
Python
mit
10,725
0.00317
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test descriptor wallet function.""" from test_framework.blocktools import COINBASE_MATURITY from test_...
gacy1") else: self.log.warning("Skipping BDB test") # Make a descriptor wallet self.log.info("Making a descriptor wallet") self.nodes[0].createwa
llet(wallet_name="desc1", descriptors=True) # A descriptor wallet should have 100 addresses * 4 types = 400 keys self.log.info("Checking wallet info") wallet_info = self.nodes[0].getwalletinfo() assert_equal(wallet_info['format'], 'sqlite') assert_equal(wallet_info['keypoolsize'...
Cynary/distro6.01
arch/6.01Soft/lib601-F13-4/soar/worlds/oneDdiff.py
Python
mit
148
0.027027
dimensions(8
,2) wall((0, 2), (8, 2)) wall((1, 1.5),(1.5, 1.5)) wall((2, 1.6),(2.8, 1.6)) wall((3.1, 1.4),(3.5, 1.4)) initialRobotLoc(1
.0, 1.0)
tridvaodin/Assignments-Valya-Maskaliova
LPTHW/projects/gothonweb/bin/app.py
Python
gpl-2.0
488
0.020492
import web urls = ( '/hello','Index' ) app = web.ap
plication(urls,globals()) render = web.template.render('/usr/local/LPTH
W/ex51/gothonweb/templates/',base="layout") class Index(object): def GET(self): return render.hello_form() def POST(self): form = web.input(name="Nobody",greet="Hello") greeting = "%s,%s" % (form.greet,form.name) return render.index(greeting = greeting) if __name__ == '...
quimaguirre/diana
scripts/old_scripts/run_experiment_cluster.py
Python
mit
5,102
0.010584
import os, sys, re import ConfigParser import optparse import shutil import subprocess import difflib import collections #import numpy as np # Alberto Meseguer file; 18/11/2016 # Modified by Quim Aguirre; 13/03/2017 # This file is the master coordinator of the DI
ANA project. It i
s used to run multiple DIANA commands in parallel in the cluster #-------------# # Functions # #-------------# #-------------# # Options # #-------------# def parse_options(): ''' This function parses the command line arguments and returns an optparse object. ''' parser = optparse.OptionParser...
novalabs/core-tools
novalabs/core/CoreWorkspace.py
Python
gpl-3.0
16,247
0.000923
# COPYRIGHT (c) 2016-2018 Nova Labs SRL # # All rights reserved. All use of this software and documentation is # subject to the License Agreement located in the file LICENSE. from .Core import * from .ModuleTarget import * from .ParametersTarget import * from abc import abstractmethod class CoreWorkspaceBase: de...
urces = None self.generated = None self.build = None @abstractmethod def getCorePackage(self, name): pass @abstractmethod
def getCoreModule(self, name): pass @abstractmethod def getCoreConfiguration(self, package, name): pass @abstractmethod def getCoreMessage(self, package, name): pass @abstractmethod def getRoot(self, cwd=None): pass @abstractmethod def isValid(self)...
rancherio/python-agent
cattle/plugins/docker/compute.py
Python
apache-2.0
33,197
0.00009
import logging import socket import re from os import path, remove, makedirs, rename, environ from . import docker_client, pull_image from . import DockerConfig from . import DockerPool from cattle import Config from cattle.compute import BaseComputeDriver from cattle.agent.handler import KindBasedMixin from cattle.ty...
tus only wait to distinguish created from stopped if c['Status'] != '' and c['Status'] != 'Created': nonrunning_containers[c['Id']] = c running_containers = {} for c in client.containers(all=False): running_containers[c['Id']] = c del nonrunning_conta...
if image in self.system_images: return self.system_images[image] except (TypeError, KeyError): pass try: return container['Labels']['io.rancher.container.system'] except (TypeError, KeyError): pass def _get_uuid(self, container): ...
jdddog/einstein_robot
einstein_driver/src/einstein_controller.py
Python
bsd-3-clause
1,255
0.004781
#!/usr/bin/env python __author__ = 'Jamie Diprose' import rospy from sensor_msgs.msg import JointState from ros_pololu_servo.msg import servo_pololu import math class EinsteinController(): def __init__(self): rospy.init_node('einstein_controller') rospy.Subscriber("joint_angles", JointState, self...
es, queue_size=10) self.pololu_pub = rospy.Publisher("cmd_pololu", servo_pololu) self.joint_ids = {'neck_yaw': 23,
'neck_roll': 2, 'neck_pitch': 3} def handle_joint_angles(self, msg): rospy.logdebug("Received a joint angle target") for i, joint_name in enumerate(msg.name): servo_msg = servo_pololu() servo_msg.id = self.joint_ids[joint_name] servo_msg.angle = msg.position[i] ...
KraftSoft/together
location/migrations/0001_initial.py
Python
bsd-3-clause
767
0.002608
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-19 21:08 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ]
operations = [ migrations.CreateModel( name='Subway', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('coordinates', django.contrib.gis.db.models.fields.PointField(null=True,
srid=4326)), ('name', models.CharField(max_length=64)), ], options={ 'abstract': False, }, ), ]
mlecours/fake-switches
fake_switches/netconf/netconf_protocol.py
Python
apache-2.0
4,337
0.003689
# Copyright 2015 Internap. # # 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, so...
if response.require_disconnect: self.logger.info("Disconnecting") self.transport.loseConnection() def say(self, etree_root): self.logger.info("Saying : %s" % repr(etree.tostring(etree_
root))) self.transport.write(etree.tostring(etree_root, pretty_print=True) + "]]>]]>\n") def error_to_response(error): error_specs = { "error-message": error.message } if error.type: error_specs["error-type"] = error.type if error.tag: error_specs["error-tag"] = error.tag if error...
klis87/django-cloudinary-storage
tests/settings.py
Python
mit
2,246
0.000445
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] SECRET_KEY = 'my-key' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'tests', 'cloudinary_storage', # 'django.contrib.admin', 'django.contrib.auth', 'django.con...
_STORAGE = { 'CLOUD_NAME': os.getenv('CLOUDINARY_CLOUD_NAME', 'my-cloud-name'), 'API_KEY': os.getenv('CLOUDINARY_API_KEY', 'my-api-key'), 'API_SECRET': os.getenv('CLOUDINARY_API_SECRET', 'my-api-secret') } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'conso...
ging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, }
TGITS/programming-workouts
exercism/python/isbn-verifier/isbn_verifier_test.py
Python
mit
1,989
0
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase): def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(i...
ut_contain
s_a_valid_isbn(self): self.assertIs(is_valid("98245726788"), False) if __name__ == "__main__": unittest.main()
ingenioustechie/zamboni
mkt/account/tests/test_serializers.py
Python
bsd-3-clause
3,416
0
from datetime import datetime import mock from nose.tools im
port eq_ import mkt import mkt.site.tests from mkt.account.serializers import (AccountSerializer, AccountInfoSerializer, TOSSerializer) from mkt.users.models import UserProfile class TestAccountSerializer(mkt.site.tests.TestCase): def setUp(self): self.account = UserP...
name_returns_name(self): with mock.patch.object(UserProfile, 'name', 'Account name'): eq_(self.serializer().data['display_name'], 'Account name') def test_recommendations(self): # Test default. eq_(self.serializer().data['enable_recommendations'], True) self.account.enab...
gantzgraf/vape
vase/family_filter.py
Python
gpl-3.0
69,896
0.000229
from .sample_filter import SampleFilter, GtFilter from .sv_gt_filter import SvGtFilter import logging from collections import OrderedDict, defaultdict class FamilyFilter(object): ''' Determine whether variants/alleles fit given inheritance patterns for families. ''' def __init__(self, pe...
= list(x for x in self.unaffected if x in self.
vcf.header.samples) self.vcf_samples = self.vcf_affected + self.vcf_unaffected self.inheritance_patterns = defaultdict(list) if infer_inheritance: self._infer_inheritance() if force_inheritance: if force_inheritance not in ('dominant', 'recessive'): ...
huangshiyu13/RPNplus
train.py
Python
mit
12,215
0.00393
import inspect import os import time import sys import numpy as np import tensorflow as tf import shutil import data_engine VGG_MEAN = [103.939, 116.779, 123.68] image_height = 720 image_width = 960 feature_height = int(np.ceil(image_height / 16.)) feature_width = int(np.ceil(image_width / 16.)) class RPN: def...
'pool4') # Conv layer 5 self.conv5_1, conv5_1_wd = self.conv_layer(self.pool4, 'conv5_1') self.conv5_2, conv5_2_wd = self.conv_layer(self.conv5_1, 'conv5_2') self.conv5_3, conv5_3_wd = self.conv_layer(self.conv5_2, 'conv5_3') self.weight_dacay += conv5_1_wd + conv5_2_wd + conv5_...
self.gamma3 = tf.Variable(np.sqrt(2), dtype=tf.float32, name='gamma3') self.gamma4 = tf.Variable(1.0, dtype=tf.float32, name='gamma4') # Pooling to the same size self.pool3_p = tf.nn.max_pool(self.pool3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', ...
Cadasta/django-skivvy
setup.py
Python
agpl-3.0
3,207
0
import sys impor
t os import re import shutil from setuptools import setup name = 'django-skivvy' package = 'skivvy' description = ('Write faster integration tests for Django views – with less ' 'code.') url = 'https://github.com/oliverroick/django-skivvy' author = 'Oliver Roick' author_email = 'oliver.roick@gmail.com' ...
n(readme_file, 'r') as f: long_description = f.readline().strip() def get_version(package): """ Return package version as listed in `__version__` in `init.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() return re.search("^__version__ = ['\"]([^'\"]+)['\"]", ...
sidartaoliveira/ansible
lib/ansible/modules/system/parted.py
Python
gpl-3.0
22,160
0.000632
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Fabrizio Colonna <colofabrix@tin.it> # # 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 ...
artitions: description: List of device partitions. type: list sample: > { "disk": { "dev": "/dev/sdb", "logical_block": 512, "model": "VMware Virtual disk", "physical_block": 512, "size": 5.0, "table": "msdos", "unit": "...
fstype": "", "name": "", "num": 1, "size": 1.0 }, { "begin": 1.0, "end": 5.0, "flags": [], "fstype": "", "name": "", "num": 2, "size": 4.0 }] } ''' EXAMPLES = """ # Create a new primary partition -...
olavurmortensen/gensim
gensim/similarities/index.py
Python
lgpl-2.1
3,188
0.002509
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
ctor_size) def build_from_doc2vec(self): """Build an Annoy index using document vectors from a Doc2Vec model""" docvecs = self.model.docvecs doc
vecs.init_sims() labels = [docvecs.index_to_doctag(i) for i in range(0, docvecs.count)] return self._build_from_model(docvecs.doctag_syn0norm, labels, self.model.vector_size) def _build_from_model(self, vectors, labels, num_features): index = AnnoyIndex(num_features) for vector_num...
Zulfikarlatief/tealinux-software-center
src/updatePage.py
Python
gpl-3.0
6,849
0.007446
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # 2012 Reza Faiz A # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # Reza Faiz A <ylpmiskrad@gmail.com> # Remixed : Reza Faiz A <ylpmi...
self.updateView.selectAllPkg, self.updateView.unselectAllPkg, self.updateView.getSelectList, upgradeSelectedPkgsCallback, showIgnorePageCallback) # Connect components.
self.box.pack_start(self.topbar.eventbox, False, False) self.box.pack_start(self.updateView.scrolledwindow) self.box.show_all() class Topbar(object): '''Top bar.''' def __init__(self, repoCache, selectAllPkgCallback, unselectAllPkgCallback, ...
eukaryote/knowhow
tests/conftest.py
Python
mit
1,892
0
# coding=utf8 from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import division import os from os.path import join import tempfile import shutil from six.moves import configparser import pytest from tests import setenv, test_doc0 f...
conf.write(f) return path @pytest.fixture def tmp_app_index_dir_paths(tmpd): app_dir = join(tmpd, "app") index_dir = join(tmpd, "index") return tmpd, app_dir, index_dir @pytest.fixture def tmp_app_index_dirs(tmp_app_index_dir_paths): tmpd, appd, indexd = tmp_app_index_dir_paths os.mkdir...
return tmpd, appd, indexd @pytest.fixture def index_empty(request, tmp_app_index_dirs): _, app_dir, index_dir = tmp_app_index_dirs orig_home = os.environ.get("KNOWHOW_HOME") orig_data = os.environ.get("KNOWHOW_DATA") def restore(): setenv("KNOWHOW_HOME", orig_home) setenv("KNOWH...
eryxlee/scrapy
sexy/sexy/items.py
Python
gpl-2.0
358
0.002793
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topi
cs/items.html import scrapy class SexyItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() d
irname = scrapy.Field() file_urls = scrapy.Field() files = scrapy.Field()
certik/sympy-oldcore
sympy/printing/printer.py
Python
bsd-3-clause
847
0
class Printer(object): """ """ def __init__(self):
self._depth = -1 self._str = str self.e
mptyPrinter = str def doprint(self, expr): """Returns the pretty representation for expr (as a string)""" return self._str(self._print(expr)) def _print(self, expr): self._depth += 1 # See if the class of expr is known, or if one of its super # classes is known, and us...
BirkbeckCTP/janeway
src/repository/migrations/0020_vq_title_abstracts.py
Python
agpl-3.0
693
0.001443
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-11-02 10:04 from __future__ import unicode_literals from django.db import migrations def update_version_queues(apps, schema_editor): VersionQueue = apps.get_model('repository', 'VersionQueue')
for queue in VersionQueue.objects.all(): queue.title = queue.preprint.title queue.abstract = queue.preprint.abstract queue.save() class Migration(migrations.Migration): dependencies = [ ('repository', '0019_auto_20201030_1423'), ] operations = [ migrations.RunP...
reverse_code=migrations.RunPython.noop, ) ]
coreboot/chrome-ec
zephyr/test/ec_app/BUILD.py
Python
bsd-3-clause
195
0
#
Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source
code is governed by a BSD-style license that can be # found in the LICENSE file. register_host_test("ec_app")
zenoss/ZenPacks.community.SquidMon
setup.py
Python
gpl-2.0
2,623
0.012962
################################ # These variables are overwritten by Zenoss when the ZenPack is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = "ZenPacks.community.SquidMon" VERSION = "1.0" AUTHOR = "Josh Baird" LICENSE = "GPLv2" NAMESPACE_PACKAGES = ['ZenPacks', 'ZenPacks.c...
edit page. Whenever the edit page is submitted it will # overwrite the values below (the ones it knows about) with new values. name = NAME, version = VERSION, author = AUTHOR, license = LICENSE, # This is the version spec which indicates what versions of Zenoss # this ZenPack is compat...
is ZenPack has changed. If no ZenPack with the current name is # installed then a zenpack of this name if installed will be upgraded. prevZenPackName = PREV_ZENPACK_NAME, # Indicate to setuptools which namespace packages the zenpack # participates in namespace_packages = NAMESPACE_PACKAGES, ...
bradchristensen/cherrymusic
tinytag/__init__.py
Python
gpl-3.0
194
0.005155
#!/usr/bin/python # -*- coding: utf-8 -*- from .tinytag import TinyTag, StringWalker, ID3, Ogg, Wave, Flac __versi
on__ = '0.9.1' if __name__ == '__main__': print(TinyT
ag.get(sys.argv[1]))
monk-ee/AWSBillingToDynamoDB
tests/__init__.py
Python
gpl-2.0
623
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015
Monk-ee (magic.monkee.magic@gmail.com). # """__init__.py: Init for unit testing this module.""" __author__ = "monkee" __maintainer__ = "monk-ee" __email__ = "magic.monkee.magic@gmail.com" __status__ = "Development
" import unittest from PuppetDBClientTestCaseV2 import PuppetDBClientTestCaseV2 from PuppetDBClientTestCaseV3 import PuppetDBClientTestCaseV3 def all_tests(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(PuppetDBClientTestCaseV2)) suite.addTest(unittest.makeSuite(PuppetDBClientTestCaseV...
yannrouillard/weboob
modules/voyagessncf/pages.py
Python
agpl-3.0
4,591
0.003921
# -*- coding: utf-8 -*- # Copyright(C) 2013 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
e): i = -1 i
f last else 0 p = div.cssselect(name)[i] sub = p.find('p') if sub is not None: txt = sub.tail.strip() if txt == '': p.remove(sub) else: return unicode(txt) return unicode(self.parser.tocleanstring(p)) def parse_hou...
altvod/pymander
examples/simple.py
Python
mit
1,893
0.002113
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
LineHandler(LineHandler): def try_execute(self, line): if line.strip() == 'kerrigan': self.context.write('Oh, Sarah...\n') return raise CantParseLine(line) class BerryLineHandler(RegexLineHandler): @bind_command(r'pick a (?P<berry_kind>\w+)') def pick_berry(self, b...
, berry_kind): self.context.write('Made some {0} jam\n'.format(berry_kind)) class GameLineHandler(ArgparseLineHandler): @bind_command('play', [ ['game', {'type': str, 'default': 'nothing'}], ['--well', {'action': 'store_true'}], ]) def play(self, game, well): self.context.w...
chepe4pi/sokoban_api
sokoban/urls.py
Python
gpl-2.0
2,156
0.00603
from django.conf.urls import include, url from django.contrib import admin from rest_framework.routers import DefaultRouter from sk_map.api.map import MapViewSet, WallViewSet, BoxViewSet, PointViewSet, MenViewSet,\ WallListViewSet, BoxListViewSet, PointListViewSet, MenListViewSet, MapListViewSet from sk_auth.api.au...
t': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'} action_no_pk = {'get': 'list', 'post': 'create'} router = DefaultRouter() router.register(r'skins', SkinView) router.register(r'auth/register', RegisterView) urlpatterns = router.urls urlpa
tterns_game = [ url('^game/(?P<map>\d+)/$', GameViewSet.as_view({'get': 'retrieve', 'patch': 'partial_update'})), url('^game/$', GameViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'post': 'create'})), ] urlpatterns_map = { url('^map/(?P<pk>\d+)/$', MapViewSet.as_view(action_with_...
dahaic/outerspace
server/lib/ige/ospace/Rules/__init__.py
Python
gpl-2.0
11,626
0.027697
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space 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 # (...
ratio is dynamic on cost of building. it's full of magic constants # goal is to have 480 CP building to repair in ~2 days (which is twice the legacy repair # ratio), and the most expansive ones (adv. stargate) ~ 6 days. # We are usi
ng log10() as it's quicker than log() _magicBase = 1.0 / (turnsPerDay * 2) _repairMagicBase = math.log10(480 * structDefaultCpCosts) ** 2 * _magicBase repairRatioFunc = lambda x: _repairMagicBase / math.log10(x) ** 2 # building decay ratio bigger or equivalent of 480 CP repair decayRatioFunc = lambda x: min( _magicBase...
Hoohm/pyHomeVM
pyHomeVM/__main__.py
Python
gpl-3.0
5,792
0.000691
"""__Main__.""" import sys import os import logging import argparse import traceback import shelve from datetime import datetime from CONSTANTS import CONSTANTS from settings.settings import load_config, load_core, load_remote, load_email from settings.settings import load_html, load_sms from core import read_structure...
tr(os.getpid()) pidfile = "/tmp/pyHomeVM.pid" config = load_config(args.
config_file_path) # load config file if os.path.isfile(pidfile): logger.info('Program already running') html = load_html(config) email = load_email(config) send_mail_log(CONSTANTS['log_file_path'], email, html) sys.exit() file(pidfile, 'w').write(pid) (ffmpeg, local)...
stormi/tsunami
src/secondaires/navigation/commandes/matelot/recruter.py
Python
bsd-3-clause
5,585
0.00072
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
ge cle = getattr(cible, "cle", None) try: fiche = importeur.navigation.fiches[cle] except KeyError: personnage.envoyer("|err|Vous ne pouvez recruter {}.|ff|",
cible) return try: n_cible = navires[nombre - 1] except IndexError: personnage << "|err|Ce navire n'est pas visible.|ff|" return if cible.etats: personnage.envoyer("{} est occupé.", cibl...