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
jazzabeanie/python_koans
python2/koans/about_true_and_false.py
Python
mit
1,579
0.0057
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutTrueAndFalse(Koan): def truth_value(self, condition): if condition: return 'true stuff' else: return 'false stuff' def test_true_is_treated_as_true(self): self.assertEqual('true...
s_false(self): self.assertEqual('false stuff', self.truth_value(False
)) def test_none_is_treated_as_false(self): self.assertEqual('false stuff', self.truth_value(None)) def test_zero_is_treated_as_false(self): self.assertEqual('false stuff', self.truth_value(0)) def test_empty_collections_are_treated_as_false(self): self.assertEqual('false stuff', ...
coolbombom/CouchPotatoServer
couchpotato/core/downloaders/utorrent/__init__.py
Python
gpl-3.0
1,744
0.002867
from .main import uTorrent def start(): return uTorrent() config = [{ 'name': 'utorrent', 'groups': [ { 'tab': 'downloaders', 'list': 'download_providers', 'name': 'utorrent', 'label': 'uTorrent', 'description': 'Use <a href="http://www.u...
g>localhost:8000</strong>', }, { 'name': 'username', }, { 'name': 'password', 'type': 'password', }, { 'name': 'label', 'des...
'default': False, 'description': 'Add the torrent paused.', }, { 'name': 'manual', 'default': 0, 'type': 'bool', 'advanced': True, 'description': 'Dis...
GunoH/intellij-community
python/testData/editing/noBackslashOnEnterInMappingPattern.after.py
Python
apache-2.0
63
0.095238
ma
tch x: case {'foo': 1, <caret>
'bar': 2} pass
laysakura/relshell
setup.py
Python
apache-2.0
1,163
0.035254
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name = 'relshell', description = '''A framework to manage shell commands\' inputs/outputs as relational data.''', long_description = open('README.rst').read(), url = 'https://github.com/lays...
'nose-parameterized', ], packages = [ 'relshell', 'relshell.test', ], scripts = [ ], classifiers = ''' Pro
gramming Language :: Python Development Status :: 4 - Beta License :: OSI Approved :: Apache Software License Programming Language :: Python :: 2.6 Programming Language :: Python :: 2.7 Programming Language :: Python :: Implementation :: PyPy Operating System :: POSIX :: Linux '''.strip().splitlines() )
hahaps/openstack-project-generator
template/<project_name>/openstack/common/config/generator.py
Python
apache-2.0
10,546
0.000284
# Copyright 2012 SINA Corporation # Copyright 2014 Cisco Systems, 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/licens...
'DEFAULT', []) opt_list.append((ext.name, opts
)) for pkg_name in pkg_names: mods = mods_by_pkg.get(pkg_name) mods.sort() for mod_str in mods: if mod_str.endswith('.__init__'): mod_str = mod_str[:mod_str.rfind(".")] mod_obj = _import_module(mod_str) if not mod_obj: rai...
stan-dev/math
lib/boost_1.75.0/libs/metaparse/tools/benchmark/generate.py
Python
bsd-3-clause
8,790
0
#!/usr/bin/python """Utility to generate files to benchmark""" # Copyright Abel Sinkovics (abel@sinkovics.hu) 2016. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import argparse import os import stri...
omment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), int(match.group(3)) ) def property(self, name): """Parses and returns a property""...
urn self._get_line(in_comment(name + ':[ \t]*(.*)')) def modes(self): """Returns the list of generation modes""" return [Mode(s.strip()) for s in self.property('modes').split(',')] def _match(self, regex): """Find the first line matching regex and return the match object""" cre...
Aravinthu/odoo
addons/stock_picking_batch/wizard/stock_immediate_transfer.py
Python
agpl-3.0
1,110
0.005405
from odoo import models, fields, api class StockImmediateTransfer(models.TransientModel): _inherit = 'stock.immediate.trans
fer' _description = 'Immediate Transfer' pick_to_backorder_ids = fields.Many2many('stock.picking', help='Picking to backorder') @api.multi def process(self): backorder_wizard_dict = super(StockImmediateTransfer, self).process() # If the immediate transfer wizard process all our picking...
eded we want to add the backorder already passed to the wizard. if backorder_wizard_dict is not None: backorder_wizard = self.env['stock.backorder.confirmation'].browse(backorder_wizard_dict.get('res_id', False)) backorder_wizard.write({'pick_ids': [(4, p.id) for p in self.pick_to_backor...
gdetor/SI-RF-Structure
Statistics/weights-evo.py
Python
gpl-3.0
4,698
0
# Copyright (c) 2014, Georgios Is. Detorakis (gdetor@gmail.com) and # Nicolas P. Rougier (nicolas.rougier@inria.fr) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redis...
absolute deviation. **Parameters** x : double Data array """ return 1.4826 * np.median(np.abs(x - np.median(x))) if __name__ == '__main__': base = '/Users/gdetorak/Desktop/DNF-SOM/REF/' m, n, q = 1024, 16, 256 if 0: epochs = 35000 mean, std, median, m...
mean.append(np.mean(np.mean(W, axis=1))) std.append(np.std(np.std(W, axis=1))) median.append(np.median(np.median(W, axis=1))) mmad.append(np.apply_along_axis(mad, 0, np.apply_along_axis(mad, 1, W)))...
dpwrussell/openmicroscopy
components/tools/OmeroPy/test/integration/clitest/test_chown.py
Python
gpl-2.0
26,460
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 University of Dundee & Open Microscopy Environment. # 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;...
def testFilesetPartialFailing(self): images = self.import_mif(2) # 2 images sharing a fileset # Create user and try to transfer only one image to the user client, user = self.new_client_and_user(group=self.group) self.args += ['%s' % user.id.val] self.args += ['Image:%s' %...
es[0].id.val] self.cli.invoke(self.args, strict=True) # Check the images have not been transferred for i in images: obj = self.query.get('Image', i.id.val, all_grps) assert obj.id.val == i.id.val assert obj.details.owner.id.val == self.user.id.val def te...
nel215/catprep
tests/blender_test.py
Python
apache-2.0
1,379
0
# coding:utf-8 import catprep import pandas as pd import numpy as np def gen_data(dim, n, label): res = [] for i in range(n): x = np.random.randint(4, size=dim) y = np.sum(x) % 2 row = list(map(lambda x: chr(65+x), x)) if label: row = row + [y] res.append(ro...
aFrame(gen_data(dim, 100, label=True), colu
mns=columns) blender = catprep.Blender() blender.fit(df, columns=x_columns, target='y') blended_df = blender.blend(df, columns=x_columns, target='y') assert blender.best_score < 1e-9 assert blender.best_param == {'n_estimators': 10, 'max_depth': 8} assert blender.best_reg is not None def test_...
deisi/SFG2D
sfg2d/widgets.py
Python
mit
66,147
0.000242
import os from glob import glob from collections import Counter import numpy as np from json import dump, load from traitlets import TraitError import matplotlib.pyplot as plt import matplotlib.ticker as mtick import matplotlib.gridspec as gridspec from traitlets import validate from ipywidgets import IntRangeSlider ...
# Internal objects # Figure to draw on self._fig = fig # Central wavelength of the camera # Size of the figure self._figsize = figsize # List of widget
s that update the figure self._figure_widgets = [] # Buffer to save autoscale values with. self._autoscale_buffer = [None, None] self._autoscale_buffer_2 = [None, None] # Buffer to save x_rois upon switching data. self._rois_x_pixel_buffer = [slice(None, None)] # ...
etcher3rd/EKPI
main.py
Python
unlicense
552
0.005435
# coding=utf-8 __aut
hor__ = 'etcher3rd' __version__ = "alpha31" __guid__ = '5b6dab14-577b-48b8-955a-80c0112a2aee' import sys import ctypes from os im
port _exit if __name__ == "__main__": if hasattr(sys, 'frozen'): sys.stdout = open("stdout.log", "w") sys.stderr = open("stderr.log", "w") # noinspection PyBroadException try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(__guid__) except: ...
jaeilepp/mne-python
mne/tests/test_fixes.py
Python
bsd-3-clause
1,340
0.000746
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD import numpy as np from numpy.testing import assert_allclose from scipy.signal import filtfilt from scipy.spe...
ol) assert_allclose(sph, sph
_scipy, atol=1e-7) run_tests_if_main()
rusenask/stubo-app
stubo/model/__init__.py
Python
gpl-3.0
155
0.025806
""" stub
o.model ~~~~~~~~~~~
The Model? :copyright: (c) 2015 by OpenCredo. :license: GPLv3, see LICENSE for more details. """
domitry/draw
setup.py
Python
mit
601
0
try: from setuptools import setup except ImportError: from distutils.core import setup kw = { 'name': 'draw', 'version': '0.0.1', 'description': 'A drawing tool for IPython', 'long_description': "", 'author': 'Naoki Nishida', 'author_email': 'domitry@gmail.com', 'license': 'MIT Lice...
se', 'url': 'https://github.com/domitry/draw', 'keywords': 'data visualization', 'classifiers': ( 'License :: OSI Approved :: MIT License' ), 'packages': ['draw'], 'install_requires': ( 'ipython' ),
'zip_safe': True, } setup(**kw)
marcrasi/webset
statistics/heat_map/process.py
Python
gpl-2.0
778
0.028278
#Our statistic is a 21-element array. Each element is the number of times #the player has picked up a card from the corresponding position on the #table. import common_lib def process_game(game): statistic_map = {} sg = common_lib.SetGame(game) for action in sg.actionList: if(action.action_type == 'pi...
action.player][idx] +=
1 return statistic_map def aggregate_statistics(stats): agg = [0] * 21 for j in range(0,len(stats)): for i in range(0,len(agg)): agg[i] += stats[j][i] return agg def table_name(): return 'HeatMapStat'
r0x0r/pywebview
webview/util.py
Python
bsd-3-clause
7,443
0.003225
# -*- coding: utf-8 -*- """ (C)
2014-2019 Roman Sirokov and contributors Licensed under BSD license http://github.com/r0x0r/pywebview/ """ import inspect import json import logging import os import re import sys import traceback from platform import architecture from threading import Thread from uuid import uuid4 import we
bview from .js import api, npo, dom, event, drag _token = uuid4().hex default_html = """ <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0"> </head> <body></body> </html> """ logger = l...
dracos/QGIS
tests/src/python/qgis_local_server.py
Python
gpl-2.0
29,318
0.000171
# -*- coding: utf-8 -*- """Convenience interface to a locally spawned QGIS Server, e.g. for unit tests .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (a...
if self._statuscmd: try: subprocess.check_call(self._statuscmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) running = True except subprocess.CalledProcessError: running...
set_startcmd(self, cmd): self._startcmd = cmd def set_stopcmd(self, cmd): self._stopcmd = cmd def set_restartcmd(self, cmd): self._restartcmd = cmd def set_statuscmd(self, cmd): self._statuscmd = cmd def process(self): return self._process def pid(self): ...
antonnik/code-classifier
naive_bayes/resources/python/test_pymongo.py
Python
apache-2.0
1,040
0.002885
# Copyright 2009-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
der the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test the pymongo module itself.""" import unittest import os import sys sys.path[0:0]...
t_alias(self): # Testing that pymongo module imports mongo_client.MongoClient c = pymongo.MongoClient(host, port) self.assertEqual(c.host, host) self.assertEqual(c.port, port) if __name__ == "__main__": unittest.main()
MatthewWilkes/reportlab
demos/odyssey/odyssey.py
Python
bsd-3-clause
4,323
0.009715
#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details __version__='
'' $Id$ ''' ___doc__='' #odyssey.py # #Demo/benchmark of PDFgen rendering Homer's Odyssey. #results on my humble P266 with 64MB: # Without page compression: # 239 pages in 3.76 seconds = 77 pages per second # With textOut rather than textLine, i.e. computing width # of every word as we would for wrapping: # 239 pag...
per second from reportlab.pdfgen import canvas import time, os, sys #find out what platform we are on and whether accelerator is #present, in order to print this as part of benchmark info. try: import _rl_accel ACCEL = 1 except ImportError: ACCEL = 0 from reportlab.lib.units import inch, cm from repo...
bdh1011/wau
venv/lib/python2.7/site-packages/notebook/services/kernelspecs/handlers.py
Python
mit
2,798
0.002502
"""Tornado handlers for kernel specifications. Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-25%3A-Registry-of-installed-kernels#rest-api """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import glob import json import os pjoin = os.p...
'kernel.css']: if os.path.exists(pjoin(resource_dir, resource)): resources[resource] = url_path_join(
handler.base_url, 'kernelspecs', name, resource ) for logo_file in glob.glob(pjoin(resource_dir, 'logo-*')): fname = os.path.basename(logo_file) no_ext, _ = os.path.splitext(fname) resources[no_ext] = url_path_join( ...
pauloschilling/sentry
src/sentry/interfaces/exception.py
Python
bsd-3-clause
11,130
0.00027
""" sentry.interfaces.exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Exception',) from django.conf import settings from sentry.interfaces.base impor...
the exception itself. .. note:: This interface can be passed as the 'exception' key in addition to the full interface path. """ score = 2000 @classmethod def to_python(cls, data): if 'values' not in data: data = {'values': [data]} assert data['values'] ...
], } if data.get('exc_omitted'): assert len(data['exc_omitted']) == 2 kwargs['exc_omitted'] = data['exc_omitted'] else: kwargs['exc_omitted'] = None return cls(**kwargs) def to_json(self): return { 'values': [v.t...
henriquemiranda/yambopy
yambopy/__init__.py
Python
bsd-3-clause
2,164
0.004159
# Copyright (C) 2015 Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # # """ Create, read and write yambo input files Read, modify and write yambo databases Analyse results from yambo calculations Modules: io - YamboIn: read, write and manipulate yambo input files ...
mport * #yambo databases from yambopy.dbs.savedb import * from yambopy.dbs.dipolesdb impor
t * from yambopy.dbs.qpdb import * from yambopy.dbs.em1sdb import * from yambopy.dbs.greendb import * from yambopy.dbs.latticedb import * from yambopy.dbs.electronsdb import * from yambopy.dbs.rtdb import * from yambopy.dbs.excitondb import * from yambopy.dbs.wfdb import * from yambopy.dbs.elphondb import * #input/out...
eldho5505/OOP
dice.py
Python
gpl-2.0
689
0.002903
from random import randint import time # rolls n dice, reports results def roll(n): tally = [0, 0, 0, 0, 0, 0] for i in range(n): r = randint(0, 5) tally[r] += 1 return tally def main(): n = 0 while n <= 0: n = int(input("How many dice would you like to
roll? ")) if n <= 0: print("") print("Please enter a positive number!") start = time.clock() result = roll(n) print("") for i in range(6): print("You rolled a", i + 1, "", result[i], "times (", '%.2f' % (100 * result[i] / n), "%)") pr
int("") stop = time.clock() print("Time taken:", stop - start, "seconds") main()
flavour/ifrc_qa
languages/vi.py
Python
mit
374,132
0.019023
# -*- coding: utf-8 -*- { '# selected': '# được lựa chọn', "'Cancel' will indicate an asset log entry did not occur": "'Hủy' sẽ chỉ dẫn một lệnh nhập không thực hiện được", "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a...
guyện viên hoạt động tích cực là những ng
ười tham gia trung bình từ 8 tiếng hoặc hơn vào các hoạt động của chương trình hay tập huấn một tháng trong năm trước.', "Acronym of the organization's name, eg. IFRC.": 'Từ viết tắt của tên tổ chức, vd IFRC.', "Add Person's Details": 'Thêm thông tin cá nhân', "Address of an image to use for this La...
sivaramakrishnansr/ryu
ryu/cmd/of_config_cli.py
Python
apache-2.0
15,609
0.001409
#!/usr/bin/env python # # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp> # # 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...
et_port_config <peer> <target> <port> <key> <value> eg. set_port_config sw1 running LogicalSwitch7-Port2 admin-state down eg. set_port_config sw1 running LogicalSwitch7-Port2 no-forward false """ def f(p, args): try: target, port, key, value = args ...
# get switch id o = p.get() capable_switch_id = o.id try: capable_switch = ofc.OFCapableSwitchType( id=capable_switch_id, resources=ofc.OFCapableSwitchResourcesType( port=[ ...
philanthropy-u/edx-platform
lms/djangoapps/courseware/tests/factories.py
Python
agpl-3.0
5,195
0.001155
# Factories are self documenting # pylint: disable=missing-docstring import json from functools import partial import factory from django.test.c
lient import RequestFa
ctory from factory.django import DjangoModelFactory from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import CourseLocator from courseware.models import ( StudentModule, XModuleStudentInfoField, XModuleStudentPrefsField, XModuleUserStateSummaryField ) from student.roles import ( ...
ctut-jim/ctut-gitgud
py3-sockets/send.py
Python
gpl-2.0
173
0.00578
# file send.py import socket server = socket.socket()
serverAddr = ("127.0.0.1", 1025, ) server.bind(serverAddr)
server.listen(0) foo = server.accept() print(foo)
sirNoolas/PA-Save-editor
gui.py
Python
mit
19,373
0.003975
from shutil import copy from tkinter import * from tkinter import filedialog from tkinter import ttk from .GetStaticData import * from .SetStaticData import * # The following handles everything to do with the gui. (main) # variables starting with var are default values; when the user changes the value of a ui elemen...
file to write to\n This function retrieves predetermined data from a given file, and then asigns the values to the global ui-vars""" misconduct, gangs, decay, visibility, failure_conditions, events = get
_general_settings(file_path) var_misconduct.set(misconduct) var_gangs.set(gangs) var_decay.set(decay) var_visibility.set(visibility) var_failure_conditions.set(failure_conditions) var_events.set(events) balance, bank_loan, credit_rating, ownership, unlimited_funds = get_finance_settings(fil...
junqueira/balance
manage.py
Python
mit
1,570
0.003185
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) # if os.path.exists('.env'): # print('Importing environment from .env...') # for...
or 'default') # manager = Manager(app) # @manager.command # def test(): # from subprocess import call # call(['nosetests', '-v', # '--with-coverage', '--cover-package=app', '--cover-branches', # '--cover-erase'
, '--cover-html', '--cover-html-dir=cover']) # #python3 manage.py adduser --admin lcjneto@gmail.com luiz # @manager.command # def adduser(email, username, admin=False): # """Register a new user.""" # from getpass import getpass # password = getpass() # password2 = getpass(prompt='Confirm: ') # if ...
locked/4stability
servo_manual.py
Python
bsd-3-clause
1,011
0.011869
#!/usr/bin/python import os import sys import time import termios import fcntl from Adafruit_PWM_Servo_Driver import PWM # Terminal init stuff found on stackoverflow (SlashV) fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECH...
c = sys.stdin.read(1) except IOError: c = '' if c == "-": pos -= 10 elif c == "+": pos += 10 sys.stdout.write("\r%d" % pos) sys.stdout.flush() pwm.setPWM(0, 0, pos) #time.sleep(.1) except: pass finally: # Reset terminal termios.tcsetattr(fd, termios.TCSAFLUSH, oldte...
oldflags)
openlabs/trytond-carrier-zone
carrier.py
Python
bsd-3-clause
4,654
0
# -*- coding: utf-8 -*- """ :co
pyright: (c) 2014 by Openlabs Technologies & Consulting (P) Limited :license: BSD, see LICENSE for more details. """ from trytond.model import ModelSQL, ModelView
, fields from trytond.pool import PoolMeta, Pool from trytond.pyson import Eval, Bool from trytond.transaction import Transaction __all__ = ['Carrier', 'CarrierZonePriceList'] __metaclass__ = PoolMeta class Carrier: __name__ = 'carrier' zone_currency = fields.Many2One( 'currency.currency', 'Currency...
mdevaev/emonoda
emonoda/plugins/trackers/kinozal_tv.py
Python
gpl-3.0
4,716
0.002395
""" Emonoda -- A set of tools to organize and manage your torrents Copyright (C) 2015 Devaev Maxim <mdevaev@gmail.com> 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 vers...
.tv/" _SITE_FINGERPRINT_TEXT = "<title>Торрент трекер Кинозал.ТВ</title>" _COMMENT_REGEXP = re.compile(r"http://kinozal\.tv/details\.php\?id=(?P<torrent_id>\d+)") _TIMEZONE_URL = "http://kinozal.tv/my.php" _TIMEZONE_REGEXP = re.compile(r"<option value=\"(?P<delta>-?\d{1,3})\" selected") _TIMEZONE_...
torrent_id}" _DOWNLOAD_PAYLOAD = b"" _STAT_URL = "http://kinozal.tv/details.php?id={torrent_id}" _STAT_OK_REGEXP = re.compile(r"<img src=\"/pic/dwn_torrent\.gif\"") _STAT_SEEDERS_REGEXP = re.compile(r"href=\"#\">Раздают<span class=\"floatright\">(?P<seeders>\d+)</span>") _STAT_LEECHERS_REGEXP = re....
babykick/gain
example/sciencenet_spider.py
Python
gpl-3.0
521
0.019194
from gain import Css, Item, Parser, Spider cla
ss Post(Item): title = Css('.ph') async def save(self): print(self.title) class MySpider(Spider): start_url = 'http://blog.sciencenet.cn/home.php?mod=space&uid=40109&do=blog&view=me&from=space' concurrency = 1 headers = {'User-Agent': 'Google Spider'} parsers = [Parser('http://blog.sc...
der.run()
andir/ganeti
test/py/ganeti.storage.bdev_unittest.py
Python
bsd-2-clause
27,296
0.005202
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2010, 2012, 2013, 2016 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above co...
testutils.ReadTestData("bdev-rbd/plain_output_old_empty.txt") self.plain_output_new_ok = \ testutils.ReadTestData("bdev-rbd/plain_output_new_ok.txt") self.plain_output_new_no_matches = \ testutils.ReadTestData("bdev-rbd/plain_output_new_no_matches.txt") self.plain_output_new_extra_matches ...
ReadTestData("bdev-rbd/plain_output_new_extra_matches.txt") # This file is completely empty, and as such it's not shipped. self.plain_output_new_empty = "" self.json_output_ok = testutils.ReadTestData("bdev-rbd/json_output_ok.txt") self.json_output_no_matches = \ testutils.ReadTestData("bdev-rbd/j...
iulian787/spack
var/spack/repos/builtin/packages/perl-error/package.py
Python
lgpl-2.1
800
0.00375
# Copyright
2013-2020 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 PerlError(PerlPackage): """The Error package provides two interfaces. Firstly Error provides a pr...
se class for errors/exceptions that can either be thrown, for subsequent catch, or can simply be recorded.""" homepage = "https://metacpan.org/pod/Error" url = "https://cpan.metacpan.org/authors/id/S/SH/SHLOMIF/Error-0.17028.tar.gz" version('0.17028', sha256='3ad85c5e58b31c8903006298424a51bba...
kiancheong/CaveJohnson
test.py
Python
mit
126
0.015873
import cavejohnson cavejohnson.set_github_status("drewcrawford/DCAKit", "a5840df1d9cf2f1176c63e8
1009361d7850a3dd9", "pending
")
mjvakili/supermean
code/dumbass.py
Python
mit
220
0.05
import numpy as np def f(x): return ((x-5.)**2.).sum(axis=1) x = np.
arange(10) def ngrad(x,h): return (f(x[:,None]+h)-f(
x[:,None]-h))/(2.*h) def agrad(x): return 2.*(x-5.) print ngrad(x,1e-6), agrad(x)
UCSD-ANF/pyzfsautosnap
zfs/zfsbackup.py
Python
bsd-2-clause
2,986
0.005358
#!/usr/bin/env python """Backup ZFS filesystems to a remote host""" import logging import sys from optparse import OptionParser from zfs import * from zfs.backup import MbufferedSSHBackup class App(object): """The ZFS backup application Usage: myapp = App(options) app.run() """ def ...
, e.g. 'hourly' or 'daily' * targethost - hostname of remote system * targetuser - username on remote system with privileges to run ZFS commands * targetdataset - the base dataset on the remote system under which all backups will be stored. Usually this is a d...
can be passed directly to the app. """ self.options=options if options.verbose: level=logging.DEBUG else: level=logging.INFO logging.basicConfig(level=level) def run(self): """Run this application Returns: a result code suitable for...
ksmit799/Toontown-Source
toontown/toon/DistributedNPCTailorAI.py
Python
mit
8,113
0.004437
from otp.ai.AIBaseGlobal import * from pandac.PandaModules import * from DistributedNPCToonBaseAI import * import ToonDNA from direct.task.Task import Task from toontown.ai import DatabaseObject from toontown.estate import ClosetGlobals class DistributedNPCTailorAI(DistributedNPCToonBaseAI): freeClothes = simbase....
self.sendUpdate('setMovie', [NPCToons.PURCHASE_MOVIE_TIMEOUT, self.npcId, self.busy, ClockDelta.globalC
lockDelta.getRealNetworkTime()]) self.sendClearMovie(None) return Task.done def sendClearMovie(self, task): self.ignore(self.air.getAvatarExitEvent(self.busy)) self.customerDNA = None self.customerId = None self.busy = 0 self.timedOut = 0 self.sendUpd...
petewarden/tensorflow
tensorflow/python/keras/layers/__init__.py
Python
apache-2.0
13,826
0.004267
# 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...
mport GaussianNoise from tensorflow.python.keras.layers.noise import GaussianDropout # Normalization layers. from tensorflow.python.keras.layers.normalization import LayerNormaliz
ation from tensorflow.python.keras.layers.normalization_v2 import SyncBatchNormalization if tf2.enabled(): from tensorflow.python.keras.layers.normalization_v2 import BatchNo
joeyjy/ayi-django
ms/booking/admin.py
Python
mit
2,741
0.007297
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from booking.models import * class UserInline(admin.TabularInline): model = User class BookingAdmin(admin.ModelAdmin): list_display = ('booker', 'book_type', 'status', ...
iption = 'Area' get_area.admin_order_field = 'booker__my_profile__get_area_display()' get_bldg.short_description = 'Building #' get_bldg.admin_order_field = 'b
ooker__my_profile__get_bldg_display()' get_apt.short_description = 'Apartment #' get_apt.admin_order_field = 'booker__my_profile__get_apt_display()' admin.site.register(Booking, BookingAdmin) #for cls in [Booking, BookingAdmin]: # admin.site.register(cls)
nicolas471/Lecole
main/migrations/0001_initial.py
Python
gpl-3.0
2,971
0.00202
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] opera
tions = [ migrations.CreateModel( name='Artista', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=100, null=True)), ('descripcion', models.Te...
grations.CreateModel( name='Evento', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=50, null=True)), ('hs_inicio', models.TimeField()), ...
bostrick/totav.stripe
totav/stripe/domain.py
Python
gpl-2.0
9,924
0.003325
from datetime import datetime from Acquisition import aq_inner #from zope.component import getMultiAdapter #from Products.CMFCore.utils import getToolByName from plone import api from five import grok from plone.directives import dexterity, form from plone.dexterity.content import Container from plone.supermodel ...
not b: cust = self.api_base.Customer.create( card=token, email=email, metadata={'username': username, }, plan=p
lan, ) custobj = createContentInContainer( self.context, "totav.stripe.customer", id=cust.id, title=username, stripe_id=cust.id, exclude_from_nav=True, checkConstraints=False, ...
Uran198/med
config/wsgi.py
Python
bsd-3-clause
1,624
0
""" WSGI config for med_project project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATIO...
MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. a
pplication = get_wsgi_application() # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.org/ application = DjangoWhiteNoise(application) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
youtube/cobalt
third_party/blink/Tools/Scripts/webkitpy/thirdparty/coverage/results.py
Python
bsd-3-clause
8,758
0.001256
"""Results of coverage measurement.""" import os from coverage.backward import set, sorted # pylint: disable=W0622 from coverage.misc import format_lines, join_regex, NoSource from coverage.parser import CodeParser class Analysis(object): """The results of analyzing a code unit.""" def __init__(s...
executed = self.coverage.data.executed_lines(self.filename) exec1 = self.parser.first_lines(executed) self.missing = sorted(set(self.statements) - set(exec1)) if self.cove
rage.data.has_arcs(): self.no_branch = self.parser.lines_matching( join_regex(self.coverage.config.partial_list), join_regex(self.coverage.config.partial_always_list) ) n_branches = self.total_branches() mba = self.missing_branch_arcs()...
googleapis/python-aiplatform
google/cloud/aiplatform_v1/services/metadata_service/async_client.py
Python
apache-2.0
145,760
0.001173
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
permissions a
nd # limitations under the License. # from collections import OrderedDict import functools import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_co...
webitup/python3-wforms
tests/translations.py
Python
bsd-3-clause
1,370
0.00292
from unittest import TestCase from wtforms import Form, TextField from wtforms import validators as v from wtforms.validators import u class Lower_Translator(object): """A fak
e translator that just converts everything to lowercase.""" def gettext(self, s): return s.lower() def ngettext(self, singular, plural, n): if n == 1: return singular.lower() else: return plural.lower() class MyFormBase(Form): def
_get_translations(self): return Lower_Translator() class DummyTranslationsTest(TestCase): class F(Form): a = TextField(validators=[v.Length(max=5)]) def setUp(self): self.a = self.F().a def test_gettext(self): x = u("foo") self.assert_(self.a.gettext(x) is x) ...
nasa/CrisisMappingToolkit
cmt/modis/simple_modis_algorithms.py
Python
apache-2.0
6,672
0.009742
# ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache #...
nflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflo...
) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' re...
liuxuyang/tools
kpiTest/data/mode_tag.py
Python
apache-2.0
3,667
0
CAMERA_MODE_PHOTO2 = 100 CAMERA_MODE_PHOTO = 0 CAMERA_MODE_FACE_BEAUTY = 1 CAMERA_MODE_PANORAMA = 2 CAMERA_MODE_SELF_WIDEVIEW = 3 CAMERA_MODE_SCENE_FRAME = 4 CAMERA_MODE_GESTURE_SHOT = 5 CAMERA_MODE_LIVE_PHOTO = 6 CAMERA_MODE_VIDEO = 7 CAMERA_MODE_PROFESSIONAL = 8 CAMERA_MODE_NIGHTSHOT = 9 CAMERA_MODE_PIP = 10 CAMERA_M...
CAMERA_MODE_SUPERPIXEL: VALUE_CAPTURE_MODE_SUPERPIXEL, CAMERA_MODE_CLEARSIGHT: VALUE_CAPTURE_MODE_CLEARSIGHT, CAMERA_MODE_VIDEOBEAUTY: VALUE_CAPTURE_
MODE_VEDOBEAUTY, CAMERA_MODE_VIDEOTIMELAPSE: VALUE_CAPTURE_MODE_VEDOTIMELAPSE, CAMERA_MODE_MONOCHROME: VALUE_CAPTURE_MODE_MONOCHROME, CAMERA_MODE_PORTRAIT: VALUE_CAPTURE_MODE_PORTRAIT }.get(mode) action = "android.myos.action.%s" ACTION_NOMARL_CAMERA = "NOMARLCAMERA" # normal ACTION_NS_C...
gbin/err
errbot/core_plugins/chatRoom.py
Python
gpl-3.0
8,056
0.000745
import logging from errbot import BotPlugin, botcmd, SeparatorArgParser, ShlexArgParser from errbot.backends.base import RoomNotJoinedError log = logging.getLogger(__name__) class ChatRoom(BotPlugin): connected = False def callback_connect(self): self.log.info('Connecting bot chatrooms') i...
.info('Joining room %s with username %s.', room, username) self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password) def deactivate(
self): self.connected = False super().deactivate() @botcmd(split_args_with=SeparatorArgParser()) def room_create(self, message, args): """ Create a chatroom. Usage: !room create <room> Examples (XMPP): !room create example-room@chat.server.tld ...
scs/uclinux
user/python/python-2.4.4/Lib/distutils/command/sdist.py
Python
gpl-2.0
17,746
0.001803
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" import sys, os, string from types import * from glob import glob from distutils.core import Command from distutils import dir_util, de...
getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats=[] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() pretty_printer = FancyGetopt(formats) pretty_printe...
"create a source distribution (tarball, zip file, etc.)" user_options = [ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), ('use-defaults', None, "include the default fil...
anaruse/chainer
examples/imagenet/resnet50.py
Python
mit
3,641
0
# Original author: yasunorikudo # (https://github.com/yasunorikudo/chainer-ResNet) import chainer import chainer.functions as F from chainer import initializers import chainer.links as L class BottleNeckA(chainer.Chain): def __init__(self, in_size, ch, out_size, stride=2, groups=1): super(BottleNeckA, s...
super(ResNet50, self).__init__() with self.init_scope(): self.conv1 = L.Convolution2D( 3, 64, 7, 2, 3, initialW=initializers.HeNormal()) self.bn1 = L.BatchNormalization(64) self.res2 = Block(3, 64, 64, 256, 1) self.res3 = Block(4, 256, 128, 512) ...
.Linear(2048, 1000) def __call__(self, x, t): h = self.bn1(self.conv1(x)) h = F.max_pooling_2d(F.relu(h), 3, stride=2) h = self.res2(h) h = self.res3(h) h = self.res4(h) h = self.res5(h) h = F.average_pooling_2d(h, 7, stride=1) h = self.fc(h) ...
UpSea/thirdParty
pyqtgraph-0.9.10/examples/CustomGraphItem.py
Python
mit
3,694
0.020845
# -*- coding: utf-8 -*- """ Simple example of subclassing GraphItem. """ import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) w...
self.textItems = [] for t in text: item = pg.TextItem(t) self.textItems.append(item
) item.setParentItem(self) def updateGraph(self): pg.GraphItem.setData(self, **self.data) for i,item in enumerate(self.textItems): item.setPos(*self.data['pos'][i]) def mouseDragEvent(self, ev): if ev.button() != QtCore.Qt.LeftButton: ...
blueyed/pip
pip/commands/search.py
Python
mit
4,909
0
import sys import textwrap from pip.basecommand import Command, SUCCESS from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from pip.exceptions import CommandError from pip.status_codes import NO_MATCHES_FOUND from pip._vendo
r import pkg_resources from distutils.version import StrictVersion, LooseVersion class SearchCommand(Command): """Sea
rch for PyPI packages whose name or summary contains <query>.""" name = 'search' usage = """ %prog [options] <query>""" summary = 'Search PyPI for packages.' def __init__(self, *args, **kw): super(SearchCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '--...
norn/bustime
bustime/update_lib.py
Python
mit
13,164
0.001709
# -*- coding: utf-8 -*- from bustime.models import * from django.core.cache import cache import logging import zmq from bustime.detector import * def analyze_events(city, events, debug=False): # import yappi; yappi.start() context = zmq.Context() sock = context.socket(zmq.PUB) sock.connect(ZSUB) R...
uniqueid, if e.x: lava['x'], lava['y'] = e.x, e.y lava['bn'] = e.busstop_nearest.busstop.name if e.x_prev: lava['px'], lava['py'] = e.x_prev, e.y_prev if e.sleeping:
lava['sleep'] = 1 if not e.zombie: bdata_mode0[e.bus_id]['l'].append(lava) # для мультипасса if not bdata_mode1.get(e.busstop_nearest.busstop_id): bdata_mode1[e.busstop_nearest.busstop_id] = [] mode1bus = [e.bus_i...
JaDogg/__py_playground
reference/sketchbook/boole/validity.py
Python
mit
2,586
0.013148
""" Propositional validity checker. Crunched down from boole.py. Suggested by reading http://www.ps.uni-sb.de/~duchier/python/validity.py and https://gist.github.com/2789099 """ def is_valid(expr): return not satisfy(expr, 0) def satisfy(expr, goal): return expr(goal, {None:None}, lambda env: env) def Constant(v...
ical pen-and-paper version of that search, but with more cases to consider (which I unify by reducing the connectives to Choice). The usual tableau method over AND, OR, etc. has an advantage: you get a choice of which subexpression to expand next, which can make for smaller search trees if you're smart. (This correspo...
dvantageous expansion into if-then-else expressions, as in validity_smallerfirst.py, only that's more static.) """
Comunitea/CMNT_00098_2017_JIM_addons
product_custom/__manifest__.py
Python
agpl-3.0
738
0
# -*- coding: utf-8 -*- # Copyright 2017 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Product customizations', 'version': '10.0.1.0.0', 'depends': [ 'product_tags', 'jim_stock' ], 'author': "Comunit...
cense': "AGPL-3", 'summary': '''Several customizations on product models''', 'website': 'http://www.comunitea.com',
'data': ["views/product_tags_view.xml", "views/product_web_report.xml", "views/product_category.xml", "views/account_invoice_report_view.xml", "views/product_view.xml"], 'installable': True, 'auto_install': False, }
CenterForOpenScience/SHARE
share/transformers/com_biomedcentral.py
Python
apache-2.0
1,752
0
from share.transform.chain import * # noqa class AgentIdentifier(Parser): uri = IRI(ctx) class WorkIdentifier(Parser): uri = IRI(ctx) class Tag(Parser): name = ctx class ThroughTags(Parser): tag = Delegate(Tag, ctx) class Person(Parser): given_name = ParseName(ctx.creator).first famil...
class Organization(Parser): name = ct
x.publisher identifiers = Map(Delegate(AgentIdentifier), ctx.issn) class Publisher(Parser): agent = Delegate(Organization, ctx) class Extra: publication_name = ctx.publicationName class Article(Parser): title = ctx.title description = ctx.abstract rights = ctx.copyright date_pub...
DarioGT/OMS-PluginXML
org.modelsphere.sms/lib/jython-2.2.1/Tools/jythonc/main.py
Python
gpl-3.0
8,961
0.003013
# Copyright (c) Corporation for National Research Initiatives """Usage: jythonc [options] [module]* where options include: --ignore-warning -i silence the jythonc deprecation warning --package package -p package put all compiled code into the named Java package --jar jarfile ...
ass:', classname sys.exit(1) filename = m.file if mainclass is None: mainclass = classname if opts.package is not None: mainclass = opts.package+'.'+mainclass comp.compilefile(filename, classname) comp.dump(opts.workdir) ...
def copyclass(jc, fromdir, todir): import jar from java.io import FileInputStream, FileOutputStream name = apply(os.path.join, jc.split('.'))+'.class' fromname = os.path.join(fromdir, name) toname = os.path.join(todir, name) tohead = os.path.split(toname)[0] if not os.path.e...
bussiere/pypyjs
website/demo/home/rfk/repos/pypy/lib-python/2.7/pprint.py
Python
mit
11,932
0.001341
# Author: Fred L. Drake, Jr. # fdrake@acm.org # # This is a simple little module I wrote to make life easier. I didn't # see anything quite like it in the library, though I may have overlooked # something. I wrote this when I was trying to read some heavily nested # tuples with fairly non-desc...
el = indent self._width = width if stream is not None: self._stream = stream else: self._stream = _sys.stdout def pprint(self, object): self._format(object, self._stream, 0, 0, {}, 0) self._stream.write("\n") def pformat(self, object):
sio = _StringIO() self._format(object, sio, 0, 0, {}, 0) return sio.getvalue() def isrecursive(self, object): return self.format(object, {}, 0, 0)[2] def isreadable(self, object): s, readable, recursive = self.format(object, {}, 0, 0) return readable and not rec...
FrancescoCeruti/linux-show-player
lisp/layouts/cue_menu_registry.py
Python
gpl-3.0
1,849
0
# -*- coding: utf-8 -*- # # This file is part of Linux Show Player # # Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com> # # Linux Show Player 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 ...
ance(item, (QAction, QMenu)): raise TypeError('items must be QAction(s) or QMenu(s), not {
0}' .format(item.__class__.__name__)) if not issubclass(ref_class, Cue): raise TypeError('ref_class must be Cue or a subclass, not {0}' .format(ref_class.__name__)) return super().add_item(item, ref_class) def add_separator(self, ...
SeiryuZ/magnet
magnet/settings.py
Python
mit
4,246
0.001178
""" Django settings for magnet project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os ...
odel AUTH_USER_MODEL = 'users.User' # Static files
(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'magnet', 'static'), os.path.join(BASE_DIR, 'node_modules'), # packages installed by yarn ] # Auth with mob...
j-n-f/silly-beatport-scraper
example_scraper.py
Python
unlicense
2,771
0.004331
# Note: you must have `flac` and `metaflac` available in your path from silly_beatport_scraper import * import os import subprocess import urllib all_files = os.listdir(".") all_files = [f_name for f_name in all_files if "wav" in f_name] my_scraper = SillyBeatportScraper() print("{} file(s) to scrape".format(len(al...
ar'])] tags += ['"Track={}"'.format(meta['track_number'])] tags += ['"Genre={}"'.format(meta['genre'])] tags += ['"Comment={}"'.format("Catalog #{}".format(meta['album_info']['catalogue-number']))] tags = ["--set-tag={}".format(tag) for tag in tags] ta
gs = ['--remove-all-tags'] + tags tags += ['--import-picture-from={}'.format(f.replace('wav', 'jpg'))] args = 'metaflac ' + " ".join(tags) + " " + f.replace('wav', 'flac') #print(args) subprocess.Popen(args, shell=True).wait() print("")
katiecheng/Bombolone
env/lib/python2.7/site-packages/requests/_oauth.py
Python
bsd-3-clause
698
0.005731
# -*- coding: utf-8 -*- """ requests._oauth ~~~~~~~~~~~~~~~ This module comtains the path hack neccesary for oauthlib to be vendored into requests while allowing upstream cha
nges. """ import os import sys try: from oauthlib.oauth1 import rfc5849 from oauthlib.common import extract_params from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER) except ImportError: path = os.path.abspath('/'.join(__file__.split('/')[:-1]+['packages'])) sy...
ath) from oauthlib.oauth1 import rfc5849 from oauthlib.common import extract_params from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
coala/coala
tests/core/CoreTest.py
Python
agpl-3.0
35,897
0.000111
from concurrent.futures import ThreadPoolExecutor import logging import sys import unittest import unittest.mock from coalib.settings.Section import Section from coalib.core.Bear import Bear from coalib.core.Core import initialize_dependencies, run from coala_utils.decorators import generate_eq from tests.core.CoreT...
None`` if not found in ``iterable``. """ try: return next(obj for obj in iterable if isinstance(obj, typ)) except StopIteration: return None clas
s InitializeDependenciesTest(unittest.TestCase): def setUp(self): self.section1 = Section('test-section1') self.section2 = Section('test-section2') self.filedict1 = {'f1': []} self.filedict2 = {'f2': []} def test_multi_dependencies(self): # General test which makes use ...
vnpy/vnpy
vnpy/trader/ui/widget.py
Python
mit
40,127
0.000127
""" Basic widgets for UI. """ import csv import platform from enum import Enum from typing import Any, Dict from copy import copy from tzlocal import get_localzone import importlib_metadata from .qt import QtCore, QtGui, QtWidgets from ..constant import Direction, Exchange, Offset, OrderType from ..engine import Mai...
.connect(self.resize_columns) self.menu.addAction(resize_action)
save_action = QtWidgets.QAction("保存数据", self) save_action.triggered.connect(self.save_csv) self.menu.addAction(save_action) def register_event(self) -> None: """ Register event handler into event engine. """ if self.event_type: self.signal.conne...
arantebillywilson/python-snippets
py2/tkinter/hello.py
Python
mit
465
0.004301
#!/usr/bin/env python # -*- coding: utf-8 -*- # hello.py # A Hello World program using Tkinter package. # # Author: Billy Wilson Arante # Created: 2016/10/29 EDT # # Attribution: http://effbot.org/tkinterbook/tkinter-hello-tkint
er.htm from Tkinter import * def main(): """Main""" root = Tk() label = Label(root, text="Hello, world!") label.pack
() root.mainloop() if __name__ == "__main__": # Executes only if run as script main()
jenfly/atmos-tools
atmos/data.py
Python
mit
62,848
0.00148
""" Utility functions for atmospheric data wrangling / preparation. - ndarrays - netCDF files - Lat-lon geophysical data - Pressure level data and topography """ from __future__ import division import numpy as np import pandas as pd import collections import scipy.interpolate as interp from mpl_toolkits import basema...
ray.DataArray """ # Maximum number of dimensions handled by this code nmax = 5 ndim = data.ndim if ndim > 5: raise ValueEr
ror('Input data has too many dimensions. Max 5-D.') if isinstance(data, xray.DataArray): name, attrs, coords, dimnames = xr.meta(data) vals = data.values.copy() else: vals = data # Roll axis to end vals = np.rollaxis(vals, axis, ndim) # Add singleton dimensions for looping...
mdesco/dipy
dipy/reconst/tests/test_peakdf.py
Python
bsd-3-clause
2,414
0.000414
import numpy as np import numpy.testing as npt from dipy.reconst.peaks import default_sphere, peaks_from_model def test_PeaksAndMetricsDirectionGetter(): class SillyModel(object): def fit(self, data, mask=None): return SillyFit(self) class SillyFit(object): def __init__(self, m...
ow Hemispheres project # all their vertices into the z >= 0 half of the sphere. peaks.ang_thr = 90. state, nd = get_direction(peaks, point, up) npt.assert_equal
(state, 0) expected_dir = peaks.peak_dirs[i, j, k, 0] npt.assert_array_almost_equal(nd, expected_dir) state, nd = get_direction(peaks, point, down) npt.assert_array_almost_equal(nd, -expected_dir) # Check that we can get directions at non-...
nachandr/cfme_tests
cfme/tests/automate/test_domain_priority.py
Python
gpl-2.0
9,718
0.002161
"""This module contains tests that check priority of domains.""" import fauxfactory import pytest from cfme import test_requirements from cfme.automate.explorer.domain import DomainCollection from cfme.automate.simulation import simulate from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.u...
rmat(original_method_write_data)) return method @pytest.fixture(scope="function"
) def original_instance(request, original_method, original_class): instance = original_class.instances.create( name=fauxfactory.gen_alphanumeric(), fields={ "meth5": { "value": original_method.name } }, ) return instance @pytest.mark.meta(blo...
alexander-bzikadze/graph_diff
graph_diff/unordered_ant_algorithm/pheromon_table.py
Python
apache-2.0
1,107
0.000903
from graph_diff.unordered_ant_algorithm import parameters class PheromonTable: """Lazy pheromon table for the ant algorithm""" P = parameters.P def __init__(self): self.table = {} self.last_update = {} self.current_iteration = 0 # O(1) def get_element(self, u, u1, v, v1)...
, v1] *= (1 - PheromonTable.P) ** (self.current_iteration - self.last_update[u, u1, v, v1]) self.table[u, u1, v, v1] += value self.last_update[u, u1, v, v1] =
self.current_iteration # O(1) def next_iteration(self): self.current_iteration += 1
sean797/Flexget
flexget/plugins/metainfo/rottentomatoes_lookup.py
Python
mit
4,533
0.002206
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import logging from flexget import plugin from flexget.event import event from flexget.utils.log import log_once try: from flexge...
Example:: rottentomatoes_lookup: yes """ field_map = { 'rt_name': 'title', 'rt_id': 'id', 'rt_year': 'year', 'rt_genres': lambda movie: [genre.name for genre in movie.genres]
, 'rt_mpaa_rating': 'mpaa_rating', 'rt_runtime': 'runtime', 'rt_critics_consensus': 'critics_consensus', 'rt_releases': lambda movie: dict((release.name, release.date) for release in movie.release_dates), 'rt_critics_rating': 'critics_rat...
google-research/google-research
aqt/jax/wmt_mlperf/hparams_configs/leaderboard/full_model_bfloat16.py
Python
apache-2.0
1,016
0.002953
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
S" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Full-sized unquantized model. A 'full size' means * 6 layers in the encoder and decoder * 1024 emd_dim * 16 heads * 1024 qkv_di...
nfig.get_config(n_layers=6, quant_target=quant_target) config.metadata.hyper_str = 'full_bfloat16' return config
kervinck/gigatron-rom
Contrib/pkupper/BabelFish/tinyfont.py
Python
bsd-2-clause
4,452
0.002471
#----------------------------------------------------------------------- # # tinyfont.py -- a very small font # #----------------------------------------------------------------------- # # Description: # # The tiny font is an 3x5 pixel monospaced font where each character # is placed in a box of 4x6...
@.@..@................@'\ '......@......@.@..@@..@...@.......@...@...@..@@@.....@@@......@.'\ '.............@@@.@@..@...@.@......@...@..@.@..@...@..........@..'\ '......@......@.@..@....@..@@.......@.@...........@........@.....'\ '................................................................'\ '....
'.@.@.@@....@...@.@.@.@...@.....@.@.@.@.@..@...@...@..@@@..@....@'\ '.@.@..@...@..@@..@@@.@@..@@@..@..@@@.@@@.........@.........@..@.'\ '.@.@..@..@.....@...@...@.@.@.@...@.@...@..@...@...@..@@@..@.....'\ '.@@..@@@.@@@.@@....@.@@..@@@.@...@@@.@@......@.....@.....@....@.'\ '.................................
townbull/mtaaas-openstack
mtaaas/openstack/common/excutils.py
Python
apache-2.0
1,791
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation. # Copyright 2012, Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http:/...
can happen when eventlet switches greenthreads or when running an exception handler, code raises and catches an exception. In both cases the exception conte
xt will be cleared. To work around this, we save the exception state, run handler code, and then re-raise the original exception. If another exception occurs, the saved exception is logged and the new exception is re-raised. """ type_, value, tb = sys.exc_info() try: yield except Ex...
apache/incubator-allura
ForgeUserStats/forgeuserstats/tests/test_model.py
Python
apache-2.0
22,990
0.00013
# 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 (t...
lmtickets = self.user.stats.getLastMonthTickets() lmcommits = self.user.stats.getLastMonthCommits() assert self.user.stats.getLastMonthLogins() == 0 assert lmartifacts['c
reated'] == 0 assert lmartifacts['modified'] == 0 assert lmtickets['assigned'] == 0 assert lmtickets['solved'] == 0 assert lmtickets['revoked'] == 0 assert lmtickets['averagesolvingtime'] is None assert lmcommits['number'] == 0 assert lmcommits['lines'] == 0 ...
jcchoiling/learningPython
aws/sqs/use_queue.py
Python
gpl-3.0
349
0.002865
#!/usr/
bin/env python # -*- coding: utf-8 -*- # Author: Janice Cheng import boto3 # Get the service resource sqs = boto3.resource('sqs') # Get the queue. This returns an SQS.Queue instance queue = sqs.get_queue_by_name(QueueName='test') # You can now access identifiers and a
ttributes print(queue.url) print(queue.attributes.get('DelaySeconds'))
shaharzeira/video_file_directory_to_mp3_python_linux
saveToMp3.py
Python
apache-2.0
919
0.006529
#!/usr/bin/python ''' Copyright (C) 2014 by Shahar Zeira (shahar.zeira@gmail.com) 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...
**************" print getFull(mp4) print getFullFr
omMp4(mp4)
jcoady9/beets
test/test_dbcore.py
Python
mit
20,402
0.000049
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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 t...
test_store_and_retrieve_flexattr(self): model = TestModel1() model.add(self.db) model.foo = 'bar' model.store() other_model = self.db._get(TestModel1, model
.id) self.assertEqual(other_model.foo, 'bar') def test_delete_flexattr(self): model = TestModel1() model['foo'] = 'bar' self.assertTrue('foo' in model) del model['foo'] self.assertFalse('foo' in model) def test_delete_flexattr_via_dot(self): model = Test...
osborne6/luminotes
view/Json.py
Python
gpl-3.0
946
0.048626
import warnings warnings.filterwarnings( "ignore", message = "The sre module is deprecated, please import re." ) from simplejson import JSONEncoder from datetime import datetime, date class Json( JSONEncoder ): def __init__( self, *args, **kwargs ): JSONEncoder.__init__( self ) if args and kwargs: ra...
args or kwargs, not both." ) self.__args = args self.__kwargs = kwargs def __str__( self ): if self.__args: if len( self.__args ) == 1: return self.encode( self.__args[ 0 ] ) return self.encode( self.__args ) return self.encode( self.__kwargs ) def default( self, obj ): ...
ow how to encode. """ if isinstance( obj, datetime ) or isinstance( obj, date ): return unicode( obj ) if hasattr( obj, "to_dict" ): return obj.to_dict() raise TypeError
zenweasel/travelsite
travelsite/contrib/sites/migrations/0002_set_site_domain_and_name.py
Python
bsd-3-clause
953
0
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, d...
"name": "travelsite" } ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "na...
carlosadean/evgnet
src/evgnet/evgnet/settings.py
Python
apache-2.0
3,436
0.001746
""" Django settings for evgnet project. Generated by 'django-admin startproject' using Django 1.11.4. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os ...
IRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messag...
], }, }, ] WSGI_APPLICATION = 'evgnet.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'evgnet.sqlite3'), } } # Password val...
carolFrohlich/nipype
nipype/interfaces/afni/tests/test_auto_MaskTool.py
Python
bsd-3-clause
1,581
0.024668
# AUTO-GENERATED by tools/checkspecs.py - DO NOT ED
IT from ....testing import assert_equal from ..utils import MaskTool def test_MaskTool_inputs(): input_map = dict(args=dict(argstr='%s', ), count=dict(argstr='-count', position=2, ),
datum=dict(argstr='-datum %s', ), dilate_inputs=dict(argstr='-dilate_inputs %s', ), dilate_results=dict(argstr='-dilate_results %s', ), environ=dict(nohash=True, usedefault=True, ), fill_dirs=dict(argstr='-fill_dirs %s', requires=[u'fill_holes'], ), fill_holes=dict(args...
t3dev/odoo
addons/website_membership/__manifest__.py
Python
gpl-3.0
711
0.001406
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Online Members Directory', 'category': 'Website', 'summary': 'Publish your members directory', 'version': '1.0', 'description': """ Publish your members/association directory publicly. ...
partner', 'website_google_map', 'association', 'website_sale'], 'data': [ 'data/members
hip_data.xml', 'views/website_membership_templates.xml', 'security/ir.model.access.csv', 'security/website_membership.xml', ], 'demo': ['data/membership_demo.xml'], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
mjiang-27/django_learn
model_advanced/model_advanced/wsgi.py
Python
gpl-3.0
406
0
"
"" WSGI config for model_advanced 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/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application o
s.environ.setdefault("DJANGO_SETTINGS_MODULE", "model_advanced.settings") application = get_wsgi_application()
hroncok/freeipa
ipaserver/install/ipa_otptoken_import.py
Python
gpl-3.0
19,592
0.002654
# Authors: Nathaniel McCallum <npmccallum@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # 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, eith...
tionMethod/xenc11:PBKDF2-params") if params is None: raise ValueError("XML file is missing PBKDF2 parameters!") self.salt = fetch(params, "./xenc11:Salt/xenc11:Specified/text()", base64.b64decode) self.iter = fetch(params, "./xenc11:Iteration
Count/text()", int) self.klen = fetch(params, "./xenc11:KeyLength/text()", int) self.hmod = fetch(params, "./xenc11:PRF/@Algorithm", convertHMACType, hashlib.sha1) if self.salt is None: raise ValueError("XML file is missing PBKDF2 salt!") if self.iter is None: r...
deuxpi/pytrainer
pytrainer/main.py
Python
gpl-2.0
21,967
0.012246
# -*- coding: iso-8859-1 -*- #Copyright (C) Fiz Vazquez vud1@sindominio.net # Modified by dgranda #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 opt...
= self.plugins.loadPlugin(plugin) self.windowmain.addImportPlugin(txtbutton) else: logging.debug('From version 1.10 on fi
le import plugins are managed via File -> Import. Not displaying plugin ' + plugin_name) logging.debug('<<') def loadExtensions(self): logging.debug('>>') activeextensions = self.extension.getActiveExtensions() if (len(activeextensions)<1): logging.info("No active exten...
dstcontrols/osisoftpy
src/osisoftpy/factory.py
Python
apache-2.0
1,646
0.00486
# -*- coding: utf-8 -*- # Copyright 2017 DST Controls # # Licensed under the Apache Li
cen
se, 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 distribut...
yuewko/neutron
neutron/tests/unit/tests/test_base.py
Python
apache-2.0
1,600
0
# Copyright 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
s) # this message should be generated when SystemExit is raised by a test self.assertIn('A SystemEx
it was raised during the test.', str(exc)) def test_system_exit(self): # this should generate a failure that mentions SystemExit was used sys.exit(1)
bmcfee/crema
setup.py
Python
bsd-2-clause
1,596
0
from setuptools import setup, find_packages imp
ort imp version = imp.load_source('crema.version', 'crema/version.py') setup( name='crema', version=version.version, desc
ription="Convolutional-recurrent estimators for music analysis", author='Brian McFee', url='http://github.com/bmcfee/crema', download_url='http://github.com/bmcfee/crema/releases', packages=find_packages(), package_data={'': ['models/*/*.pkl', 'models/*/*.h5', ...
xiangke/pycopia
experimental/pycopia/GUI/canvas.py
Python
lgpl-2.1
1,013
0.00691
#!/usr/bin/python2.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # # $Id$ # # Copyright (C) 199
9-2006 Keith Dart <keith@kdart.com> # # This library 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 2.1 of the License, or (at your option) any later version. # # This ...
NESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. from gtk import * from gnome.ui import * win = GtkWindow() win.connect('destroy', mainquit) win.set_title('Canvas test') canvas = GnomeCanvas() canvas.set_size(300, 300) win.add(canvas) canvas.show() canvas.root().add('...
nwjs/chromium.src
net/data/verify_certificate_chain_unittest/target-has-512bit-rsa-key/generate-chains.py
Python
bsd-3-clause
820
0.00122
#!/usr/bin/env python # Copyright (c) 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Valid certificate chain where the target certifi
cate contains a public key with a 512-bit modulus (weak).""" import sys sys.path += ['../..'] import gencerts # Self-signed root certificate. root = gencerts.create_self_signed_root_certificate('Root') # Intermediate intermediate = gencerts.create_intermediate_certificate('Intermediate', root) # Target certificate...
.name))) chain = [target, intermediate, root] gencerts.write_chain(__doc__, chain, 'chain.pem')
vgrem/Office365-REST-Python-Client
office365/onenote/entity_base_model.py
Python
mit
139
0
fr
om office365.entity import Entity class OnenoteEntityBaseModel(Entity): """This is the base type for OneN
ote entities.""" pass
DanielHopper/botty-bot-bot-bot
src/plugins/wiki.py
Python
mit
2,233
0.007613
#!/usr/bin/env python3 """ Wikipedia lookup plugin for Botty. Example invocations: #general | Me: what is fire #general | Botty: wikipedia says, "Fire is the rapid oxidation of a material in the exothermic
chemical process of combustion, releasing heat, light, and various reaction products. Slower oxidative processes like rusting or digestion are not included by this definition." #general | Me: what's
bismuth? #general | Botty: wikipedia says, "Bismuth is a chemical element with symbol Bi and atomic number 83. Bismuth, a pentavalent post-transition metal, chemically resembles arsenic and antimony. Elemental bismuth may occur naturally, although its sulfide and oxide form important commercial ores." #gene...
google-research/language
language/xsp/data_preprocessing/convert_to_tfrecords.py
Python
apache-2.0
17,885
0.00643
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
' SEP_TOK = '[SEP]' TAB_TOK = '[TAB]' UNK_TOK = '[UNK]' GENERATE_TYPE = 1 COPY_TYPE = 2 COL_TYPE_TO_TOK = { 'text': '[STR_COL]', 'number': '[NUM_COL]', 'others': '[OTH_C
OL]', 'time': '[TIME_COL]', 'boolean': '[BOOL_COL]', } class InputToken( collections.namedtuple('InputToken', [ 'wordpiece', 'index', 'copy_mask', 'segment_id', 'indicates_foreign_key', 'aligned' ])): pass class OutputAction( collections.namedtuple('OutputAction', ['wordpiece',...
tessonec/PySPG
spg/runner/__init__.py
Python
gpl-3.0
49
0
#
from exchange import * from t
hreaded import *
netscaler/neutron
neutron/tests/unit/services/vpn/service_drivers/test_ipsec.py
Python
apache-2.0
3,062
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013, Nachi Ueno, NTT I3, 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...
# 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
er the License. import mock from neutron import context from neutron.openstack.common import uuidutils from neutron.services.vpn.service_drivers import ipsec as ipsec_driver from neutron.tests import base _uuid = uuidutils.generate_uuid FAKE_VPN_CONNECTION = { 'vpnservice_id': _uuid() } FAKE_VPN_SERVICE = { ...
grnet/synnefo
snf-cyclades-app/synnefo/logic/management/commands/flavor-access-add.py
Python
gpl-3.0
1,983
0
# Copyright (C) 2010-2017 GRNET S.A. # # 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 is distributed i...
SynnefoCommand from synnefo.db import transaction class Command(SynnefoCommand): can_import_settings = True help = 'Create a new flavor access.' option_list = SynnefoCommand.option_list + ( make_option('--project', dest='project'), make_option('--flavor', dest='flavor'), ) @trans...
nts") project = options['project'] flavor_id = options['flavor'] if not (project and flavor_id): raise CommandError("Project and Flavor must be supplied") flavor = common.get_resource("flavor", flavor_id, for_update=True) flavor_access, created = FlavorAccess.obje...
szeged/csibe
bin/csibe/__init__.py
Python
bsd-3-clause
25
0.04
from l
ogge
r import logger