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 |
|---|---|---|---|---|---|---|---|---|
Sw4T/Warband-Development | mb_warband_module_system_1166/Module_system 1.166/module_parties.py | Python | mit | 34,291 | 0.065207 | from compiler import *
####################################################################################################################
# Each party record contains the following fields:
# 1) Party id: used for referencing parties in other files.
| # The prefix p_ is automatically added before e | ach party id.
# 2) Party name.
# 3) Party flags. See header_parties.py for a list of available flags
# 4) Menu. ID of the menu to use when this party is met. The value 0 uses the default party encounter system.
# 5) Party-template. ID of the party template this party belongs to. Use pt.none as the default value.
# ... |
daanwierstra/pybrain | pybrain/rl/environments/cartpole/balancetask.py | Python | bsd-3-clause | 4,061 | 0.008126 | __author__ = 'Thomas Rueckstiess and Tom Schaul'
from pybrain.rl.environments.cartpole.nonmarkovpole import NonMarkovPoleEnvironment
from pybrain.rl.tasks import EpisodicTask
from cartpole import CartPoleEnvironment
from scipy import pi, dot, array
class BalanceTask(EpisodicTask):
""" The task of balancing some ... | f min(angles) < 0.05:
reward = 0
elif max(angles) > 0.7 or abs(s) > 2.4:
reward = -2 * (self.N - self.t)
else:
reward = -1
return reward
class EasyBalanceTask(BalanceTask):
""" th | is task is a bit easier to learn because it gives gradual feedback
about the distance to the centre. """
def getReward(self):
angles = map(abs, self.env.getPoleAngles())
s = abs(self.env.getCartPosition())
reward = 0
if min(angles) < 0.05 and abs(s) < 0.05:
reward... |
kustomzone/augur-core | pyrpctools/__init__.py | Python | gpl-3.0 | 1,125 | 0.008 | import os
import sys
import math
import time
import json
from rpc_client import RPC_Client
ROOT = os.path.dirname(os.path.realpath(sys.argv[0]))
DBPATH = os.path.join(ROOT, 'build.json')
MAXGAS = hex(int(math.pi*1e6))
def get_db():
with open(DBPATH) as dbfile:
return json.load(dbfile)
def save_db(db):
... | ':to,
'from':sender,
'gas':gas,
'data':data,
'value':value})
assert 'error' not in response, json.dumps(response, indent=4, sort_keys=True)
txhash = res... | f receipt['result']:
return receipt
time.sleep(blocktime)
|
philbull/ghost | halomodel.py | Python | mit | 6,878 | 0.00916 | #!/usr/bin/python
"""
Halo mass function and halo bias model.
"""
import numpy as np
import scipy.integrate
import pylab as P
#om = 0.3
#h = 0.7
#gamma = 0.55
class HaloModel(object):
def __init__(self, pkfile, om=0.272, h=0.728, gamma=0.55, ampfac=1.):
"""
Initialise HaloModel class.
... | .pi**2.)
return np.sqrt(sig_r)
def dlogsigM_dlogM(self, M, sig):
"""
Logarithmic derivative o | f sigma(M) with respect to M, i.e.
d log(sigma(M)) / d log(M)
"""
coeffs = np.polyfit(np.log(M), np.log(sig), deg=4)
p = np.poly1d(coeffs)
return p.deriv()(np.log(M))
def bias(self, M, z=0.):
"""
Calculate the halo bias, b(M, z), using Eq. 12 of Sheth & Torme... |
Imperium-Software/resolver | tests/test_factory.py | Python | mit | 511 | 0.009785 | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys. | path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from SATSolver.individual import Factory
class TestFactory(TestCase):
"""
Test class for Factory
| """
def test_create(self):
factory = Factory()
population = factory.create(10,50)
self.assertEqual(50, len(population))
for individual in population:
self.assertEqual(individual.length, 10)
|
uppsaladatavetare/foobar-api | src/wallet/tests/factories.py | Python | mit | 926 | 0 | import uuid
import factory.fuzzy
from .. import models, enums
from moneyed import Money
from utils.factories import FuzzyMoney
class WalletFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Wallet
owner_id = factory.Sequence(lambda n: str(uuid.uuid4()))
balance = Money(0, 'SEK... | = models.WalletTransaction
wallet = factory.SubFactory(WalletFactory)
amount = FuzzyMoney(0, 100000)
class WalletTrxStatusFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Wallet | TransactionStatus
trx = factory.SubFactory(WalletTrxFactory)
status = enums.TrxStatus.FINALIZED
class WalletTrxWithStatusFactory(WalletTrxFactory):
states = factory.RelatedFactory(
WalletTrxStatusFactory,
'trx',
status=enums.TrxStatus.FINALIZED
)
|
xylophonw/cwspy | cwspy/data.py | Python | mit | 1,465 | 0.005461 | from datetime import datetime
from collections import namedtuple
BASE_URL = 'http://conworkshop.com/'
class User(namedtuple('User', 'uid name gender bio country karma')):
@property
def link(self):
'''Return a URL in a string to | the user's profile page on CWS.'''
return ''.join([BASE_URL, 'view_profile.php?m=', self.uid])
@property
def avatar(self):
'''Return a URL in a string to the user's avatar image on CWS.'''
return ''.join([BASE_URL, 'ava/', self.uid, '.png'])
defaultUser = User('', '', 'Other', '', 'Un... | us('', '')
class Language(namedtuple('Language', ['code', 'name', 'native_name', 'ipa',
'lang_type', 'owners', 'overview', 'public',
'status', 'registered', 'word_count', 'karma'])):
@property
def link(self):
'''Return a URL ... |
les69/calvin-base | calvin/runtime/south/plugins/storage/twistedimpl/securedht/dht_server.py | Python | apache-2.0 | 9,399 | 0.002873 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... | ootstrap(bootstrap)
self.port = reactor.listenUDP(port,
self.kserver.protocol,
interface=iface)
return self.port.getHost().host, self.port.getHost().port
def __getattr__(self, name):
if hasattr(self.kserver, n... | return getattr(self.kserver, name)
else:
# Default behaviour
raise AttributeError
def get_port(self):
return self.port
def stop(self):
if self.port:
return self.port.stopListening()
class ThreadWrapper(object):
def __init__(self, obj, ... |
ClaudioNahmad/Servicio-Social | Parametros/CosmoMC/prerrequisitos/plc-2.0/waf_tools/pmclib.py | Python | gpl-3.0 | 653 | 0.047473 | #try to support many flavours of lapack
import autoinstall_lib as atl
from waflib import Logs
import os.path as osp
def options(ctx):
at | l.add_lib_option("pmc",ctx,install=False)
def configure(ctx):
ctx.env.has_pmc = False
#pmc_config_path = ctx.find_program("pmc-config",path_list=[ctx.options.pmc_prefix+"/bin"])[0]
try:
pmc_config_path = ctx.find_program("pmc-config",path_list=[ctx.options.pmc_prefix+"/bin"])
pmcflagline = ctx.cmd_and_... | h",["pmclib","pmctools"],defines=["HAS_PMC"],flagline=pmcflagline)
|
baylee-d/cos.io | common/blocks/collapsebox.py | Python | apache-2.0 | 705 | 0 | from wagtail.wagtailcore.blocks import RichTextBlock, CharBlock, ListBlock, \
StructBlock
class CollapseEntryBlock(Struc | tBlock):
title = CharBlock()
content = RichTextBlock()
class Meta:
form_template = 'common/block_forms/collapse_entry.html'
template = 'common/blocks/collapse_entry.html'
class CollapseBoxListBlock(ListBlock):
def __init__(self, **kwargs):
return super(CollapseBoxListBlock, ... | (), **kwargs)
class CollapseBoxBlock(StructBlock):
title = CharBlock()
list = CollapseBoxListBlock()
class Meta:
template = 'common/blocks/collapse_box_block.html'
icon = 'list-ul'
|
WPMedia/dd-agent | checks.d/jenkins.py | Python | bsd-3-clause | 8,601 | 0.002558 | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from collections import defaultdict
from glob import glob
import os
import time
from xml.etree.ElementTree import ElementTree
# project
from checks import AgentCheck
class Skip(Exception):
"""
R... | mestamp_from_dirname(dir_name)
# This is not the latest build
if timestamp is not None and timestamp <= watermark:
return None
# Read the build.xml metadata file that Jenkins generates
build_metadata = os.path.join(dir_n | ame, 'build.xml')
if not os.access(build_metadata, os.R_OK):
self.log.debug("Can't read build file at %s" % (build_metadata))
raise Exception("Can't access build.xml at %s" % (build_metadata))
else:
tree = ElementTree()
tree.parse(build_metadata)
... |
samuelmaudo/yepes | tests/modelmixins/tests.py | Python | bsd-3-clause | 44,994 | 0.000622 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from decimal import Decimal
from unittest import skipIf
from django import test
from django import VERSION as DJANGO_VERSION
from django.utils import timezone
from django.utils import translation
from yepes.contrib.registry... | ds(max_words=3),
'Django, Definitive, Guide',
)
def test_title_and_excerpt_fields(self):
article = RichArticle.objects.create(
title='The Definitive Guide to Django',
headline='Two Scoops of Django',
name='Two Scoops of Django',
excerpt=(
... | ottest topics in web development.'
' In _The Definitive Guide to Django: Web Development Done'
' Right_, **Adrian Holovaty**, one of Django\'s creators, and'
' Django lead developer **Jacob Kaplan-Moss** show you how'
' they use this framework to create aw... |
omg-insa/server | api/utils.py | Python | bsd-3-clause | 372 | 0.021505 | import re
import string
import random
__author__ = 'schitic'
def tokenGenerator(size=16, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def validateEmail(email):
if len(email) > 3:
if re.ma | tch("^.+\\@(\\[?)[a-zA-Z0-9\\ | -\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email):
return True
return False |
jamielennox/tempest | tempest/auth.py | Python | apache-2.0 | 24,953 | 0.00004 | # Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... | url, headers, body,
auth_data=self.alt_auth_data)
| alt_auth_req = dict(url=alt_url, headers=alt_headers,
body=alt_body)
auth_req[self.alt_part] = alt_auth_req[self.alt_part]
else:
# If alt auth data is None, skip auth in the requested part
auth_req[self.alt_... |
Vagab0nd/SiCKRAGE | lib3/github/Path.py | Python | gpl-3.0 | 3,820 | 0.007068 | # -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2018 Justin Kufro <jkufro@andrew.cmu.edu> #
# Copyright 2018 Ivan Minno <iminno@andrew.cmu.edu> ... | (self):
"""
:type: string
"""
return self._title.value
@property
def count(self):
"""
:type: integer
"""
return self._count.value
@property
def uniques(self):
"""
:type: integer
"""
return self._uniques.val... | .GithubObject.NotSet
self._uniques = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "title" in attributes: # pragma no branch
self._title = s... |
yosshy/osclient2 | osclient2/neutron/v2/lb/vip.py | Python | apache-2.0 | 4,709 | 0 | # Copyright 2014-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
# 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... | roject', 'tenant_id', mapper.Resource('project')),
('port', 'port_id', mapper.Resource('neutron.port')),
('is_enabled', 'admin_state_up', mapper.Noop),
('is_session_persistent', 'session_persistence', mapper.Noop),
('status', 'status', mapper.Noop),
]
class Resource(base.Resource):
"""Resource cla... | LB virtual IPs in Networking V2 API"""
def update(self, name=None, description=None, session_persistence=None,
connection_limit=None, is_enabled=None):
"""
Update a VIP for a LB pool
@keyword name: VIP name (str)
@type name: str
@keyword description: VIP desc... |
markusmichel/Tworpus-Client | session/views.py | Python | apache-2.0 | 9,915 | 0.001614 | import datetime
import time
from django.utils.timezone import utc
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
from django import forms, http
import signal
import shutil
from uuid import uuid4
import ntpath
import json
import glob
import os
from StringIO import StringIO
fr... | _data['message'] = 'Start fetching tweets'
return HttpResponse(json.dumps(response_data), content_type="a | pplication/json")
else:
return http.HttpResponseServerError("Error fetching tweets")
def invokeCorpusCreation(csvFile, folder, session):
"""
fetches tweets by calling fetcher jar
"""
tw_settings = TworpusSettings.objects.first()
listener = TweetIO.TweetProgressEventHandler(session.id)
... |
bhardesty/qpid-dispatch | tests/system_tests_fallback_dest.py | Python | apache-2.0 | 29,872 | 0.003214 | #
# 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... | 'dest.10', True)
tes | t.run()
self.assertEqual(None, test.error)
def test_11_sender_first_primary_edge_edge(self):
test = SenderFirstTest(self.routers[2].addresses[0],
self.routers[4].addresses[0],
'dest.11', False)
test.run()
self.assertEqual... |
SRJ9/django-driver27 | driver27/management/commands/export_seats_for_csv.py | Python | mit | 1,566 | 0.001916 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from driver27.models import Driver, Team, Seat
import sys
if sys.version_info < (3, 0):
try:
import unicodecsv as csv
except ImportError:
import csv
else:
import csv
class Command(BaseCommand):
h... | export_cls = Driver
elif export_attr == 'teams':
fieldnames = ['id', 'name', 'full_name', 'country']
export_cls = Team
else:
fieldnames = ['id', 'driver_id', 'driver__last_name', 'driver__f | irst_name', 'team_id', 'team__name']
export_cls = Seat
objects = list(export_cls.objects.values(*fieldnames))
return {'fieldnames': fieldnames, 'objects': objects}
def add_arguments(self, parser):
parser.add_argument('csv',)
parser.add_argument(
'--export',
... |
ecoal95/angle | src/libANGLE/renderer/d3d/d3d11/gen_dxgi_format_table.py | Python | bsd-3-clause | 3,280 | 0.006402 | #!/usr/bin/python
# Copyright 2016 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_dxgi_format_table.py:
# Code generation for DXGI format map.
from datetime import date
import sys
sys.path.append('../..')
i... | n dxgi_format for ctype in | types.keys()]
count = reduce((lambda a, b: int(a) + int(b)), found)
component_type = 'GL_NONE'
if count == 1:
gltype = next(gltype for ctype, gltype in types.iteritems() if ctype in dxgi_format)
component_cases += format_case(dxgi_format, gltype)
else:
component_cases += undefi... |
pombredanne/https-git.fedorahosted.org-git-kobo | kobo/admin/commands/cmd_start_worker_task.py | Python | lgpl-2.1 | 815 | 0.002454 | # -*- coding: utf-8 -*-
import os
import kobo.cli
import kobo.admin
class Start_Worker_Task(kobo.cli.Command):
"""create a worker task module in the current directory"""
enab | led = True
def options(self):
self.parser.usage = "%%prog %s [options] <task_name>" % self.normalized_name
self.parser.add_option("-d", "--dir", help="target directory")
def run(self, *args, **kwargs):
if len(args) < 1:
self.parser.error("Please specify a name of the task."... | ry = os.getcwd()
try:
kobo.admin.copy_helper(name, directory, "task___project_name__.py.template")
except kobo.admin.TemplateError, ex:
self.parser.error(ex)
|
cpe/VAMDC-VALD | nodes/jpl/node/forms.py | Python | gpl-3.0 | 2,202 | 0.011807 | from node.models import *
from django.forms import ModelForm
from django.forms.formsets import BaseFormSet
from django.forms.models import modelformset_factory
from .cdmsportalfunc import *
from django.core.exceptions import Validatio | nError
from django import forms
class MoleculeForm(ModelForm):
class Meta:
model = Molecules
fields = '__all__'
class SpecieForm(ModelForm):
datearchived = forms.DateField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
dateactivated = forms.DateField(
wi... | ies
fields = '__all__'
class FilterForm(ModelForm):
class Meta:
model = QuantumNumbersFilter
fields = '__all__'
class XsamsConversionForm(forms.Form):
inurl = forms.URLField(label='Input URL',required=False, widget=forms.TextInput(attrs={'size': 50, 'title': 'Paste here a URL that del... |
npo-poms/scripts | python/vpro/check_with_sitemap_vpro.py | Python | gpl-2.0 | 6,894 | 0.004787 | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
import threading
import time
import urllib
from subprocess import Popen, PIPE
sys.path.append("..")
from check_with_sitemap import CheckWithSitemap
DEFAULT_JAVA_PATH = 'java'
class CheckWithSiteMapVpro(CheckWithSitemap):
"""
This specia... | f._find_by_regexp(".*?~(.*?)~.*", url)
def _find_update_uuid(self, url: str) -> list:
return self._find_by_regexp(".*?update~(.*?)~.*", url)
def _find_cinema_film_id(self, url: str) -> list:
return self._f | ind_by_regexp(".*?film~(.*?)~.*", url)
def _find_cinema_person_uid(self, url: str) -> list:
return self._find_by_regexp(".*?persoon~(.*?)~.*", url)
@staticmethod
def _find_by_regexp(regex: str, url: str) -> list:
matcher = re.match(regex, url)
if matcher:
return [matche... |
jawilson/home-assistant | homeassistant/components/zwave/sensor.py | Python | apache-2.0 | 3,679 | 0.000815 | """Support for Z-Wave sensors."""
from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity
from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
... | def native_value(self):
"""Return the state of the sensor."""
if self._units in ("C", "F"):
retu | rn round(self._state, 1)
if isinstance(self._state, float):
return round(self._state, 2)
return self._state
@property
def device_class(self):
"""Return the class of this device."""
if self._units in ["C", "F"]:
return DEVICE_CLASS_TEMPERATURE
ret... |
wathen/PhD | MHD/FEniCS/ShiftCurlCurl/saddle.py | Python | mit | 5,740 | 0.022997 | #!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4p | y import PETSc
Print = PETSc.Sy | s.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
import PETScIO as IO
import MatrixOperations as MO
def StoreMatrix(A,name):
test ="".join([name,".mat"])
... |
jchodera/MSMs | jchodera/src-11401/pyemma/cluster.py | Python | gpl-2.0 | 3,309 | 0.012088 | #!/usr/bin/env python
import pyemma
import numpy as np
import mdtraj
import time
import os
# Source directory
source_directory = '/cbio/jclab/projects/fah/fah-data/munged3/no-solvent/11401' # Src ensembler
################################################################################
# Load reference topology
####... | ########################################
nskip = 40 # number of initial frames to skip
import pyemma.coordinates
from glob import glob
trajectory_filenames = glob(os.path.join(source_directory, 'run*-clone*.h5'))
coordinates_source = pyemma.coordinates.source(trajectory_filenames, features=featu | rizer)
print("There are %d frames total in %d trajectories." % (coordinates_source.n_frames_total(), coordinates_source.number_of_trajectories()))
################################################################################
# Cluster
################################################################################
... |
croepha/django-filer | filer/tests/helpers.py | Python | mit | 1,697 | 0.007661 | #-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
superuser = User.objects.create_superuser('admin',
... | folder.save()
create_folder_structure(depth=d-1, sibling=sibling, parent=folder)
def create_clipboard_item(user, file):
clipbo | ard, was_clipboard_created = Clipboard.objects.get_or_create(user=user)
clipboard_item = ClipboardItem(clipboard=clipboard, file=file)
return clipboard_item
def create_image(mode='RGB', size=(800, 600)):
image = Image.new(mode, size)
draw = ImageDraw.Draw(image)
x_bit, y_bit = size[... |
dipapaspyros/bdo_platform | aggregator/management/commands/compare_mongo_postgres_joins.py | Python | mit | 13,096 | 0.003894 | import json
import random
import time
import traceback
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connection
from aggregator.converters.random_cnv import RandomDataConverter
from aggregator.management.comma... | "$lookup":
{
"from": "<c2>",
"localField": "<v3>",
"foreignField": "<v3>",
"as": "c2"
}
... | "$unwind": "$c2"
}, {
"$project": {
'lat': 1,
'lng': 1,
'time': 1,
'diff': {'$subtract': ["$value", "$c2.value"]},
... |
gumblex/tg-chatdig | vendor/chinesename.py | Python | mit | 6,353 | 0.008223 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import pickle
import random
import bisect
import operator
import functools
import itertools
from math import log
from .common_surnames import d as common_surnames
from .lookuptable import chrevlookup, pinyintrie, surnamerev
for py in tuple(chrevlookup.keys()):... | g1 = operator.itemgetter(1)
phonetic_symbol = {
"ā": "a",
"á": "a",
"ǎ": "a",
"à": "a",
"ē": "e",
"é": "e",
"ě": "e",
"è": "e",
"ō": "o",
"ó": "o",
"ǒ": "o",
"ò": "o",
"ī": "i",
"í": "i",
"ǐ": "i",
"ì": "i",
"ū": "u",
"ú": "u",
"ǔ": "u",
"ù": "u",
"ü": "v",
"ǖ": "v",
"ǘ": "v",
"ǚ": "v",
"ǜ": "v",
"ń": "n",
"ň": "n",
"... | only for entities defined in xml_escape_table
for k, v in phonetic_symbol.items():
text = text.replace(k, v)
return text
class WeightedRandomGenerator(object):
def __init__(self, weights):
self.totals = list(itertools.accumulate(weights))
self.total = self.totals[-1]
def __i... |
yassen-itlabs/py-linux-traffic-control | tests/plugins_tests/test_netsim.py | Python | mit | 2,138 | 0.003742 | import unittest
from pyltc.plugins.simnet import SimNetPlugin
class TestNetSim(unittest.TestCase):
def test_configure_default(self):
netsim = SimNetPlugin()
self.assertEqual([], netsim._ar | gs.upload)
self.assertEqual([], netsim._args.download)
self.assertEqual('lo', netsim._args.interface)
self.assertIsNone(netsim._args.ifbdevice)
self.assertFalse(netsim._args.clear)
self.assertFalse(netsim._args.verbose)
self.asser | tFalse(netsim._args.clearonly_mode)
def test_configure(self):
netsim = SimNetPlugin()
netsim.configure(clear=True, verbose=True, interface='eth0', ifbdevice='ifb0')
self.assertEqual([], netsim._args.upload)
self.assertEqual([], netsim._args.download)
self.assertEqual('eth0',... |
llinmeng/PythonStudy | maiziedu/3-Pycharm-Study/maiziblog2/manage.py | Python | mit | 253 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "maiziblog2.settings")
from django.cor | e.management import execute_from_command_line
execute_from_command_line | (sys.argv)
|
timwu/pypcap | src/setup.py | Python | bsd-3-clause | 673 | 0.026746 | from distutils.core import setup
from distutils.extension import Extension
from distutils import util
from Pyrex.Distutils im | port build_ext
import os.path
# Hack to get around build_ext's inability to handle multiple
# libraries in its --libraries= argument.
libs = []
if util.get_platform() == 'win32':
libs = [ "wpcap", "iphlpapi" ]
else:
libs = [ "pcap" ]
pcap_extension = Extension( name="pcap",
sourc... | yx", "pcap_ex.c"],
libraries=libs
)
setup( name = "pypcap",
version = "1.1",
ext_modules=[pcap_extension],
cmdclass = {'build_ext' : build_ext}
)
|
HEPData/hepdata3 | fixes/missing_record_ids.py | Python | gpl-2.0 | 2,910 | 0.002062 | from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdat... | er the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmissio... | s([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
|
elainenaomi/sciwonc-dataflow-examples | sbbd2016/experiments/4-mongodb-rp-3sh/9_workflow_full_10files_primary_3sh_noannot_with_proj_9s/calculateratio_0/CalculateRatioCpuMemory_0.py | Python | gpl-3.0 | 3,196 | 0.003129 | #!/usr/bin/env python
"""
This activity will calculate the ratio between CPU request and Memory request by (job ID, task index, event type).
These fields are optional and could be null.
"""
# It will connect to DataStoreClient
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_TaskEvent_0
imp... | newline['time'] = doc['time']
newline['ratio cpu memory'] = ratio
if max_cpu and min_cpu:
if cpu == max_cpu:
newline['max cpu | '] = 'true'
else:
newline['max cpu'] = 'false'
if cpu == min_cpu:
newline['min cpu'] = 'true'
else:
newline['min cpu'] = 'false'
if avg_cpu:
if cpu == avg_cpu:
newline['avg cpu'] = 'equal'
... |
nedbat/zellij | zellij/path.py | Python | apache-2.0 | 8,958 | 0.001563 | """A zigzag path, a sequence of points."""
import collections
from .defuzz import Defuzzer
from .euclid import collinear, Point, Line, Segment, Bounds, EmptyBounds
from .postulates import adjacent_pairs, triples
class Path:
def __init__(self, points):
self.points = tuple(points)
def __repr__(self):... | u | sed.add(id(path))
combined.append(path.clean())
return combined
def draw_paths(paths, ctx):
for path in paths:
path.draw(ctx)
def best_join(path, join_point, possibilities):
others = [p for p in possibilities if p != path]
# If there's only one other path, then join to that one.
... |
Boquete/activity-labyrinth | src/BaseThought.py | Python | gpl-2.0 | 13,410 | 0.03997 | # BaseThought.py
# This file is part of Labyrinth
#
# Copyright (C) 2006 - Don Scorgie <DonScorgie@Blueyonder.co.uk>
#
# Labyrinth 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 Licens... | f):
return self.all_okay
def move_content_by (self, x, y):
pass
def move_by (self, x, y):
| pass
def focus_buffer (self, buf):
self.emit ("select_thought", None)
self.emit ("grab_focus", True)
def set_extended_attrs(self, buf, bold, underline, italics, pango_font):
self.emit("update_attrs", bold, underline, italics, pango_font)
def can_be_parent (self):
return True
# This, you may want to ... |
bohlian/frappe | frappe/model/sync.py | Python | mit | 2,605 | 0.0238 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
"""
Sync's doctype and docfields from txt files to database
perms will get synced only if none exist
"""
import frappe
import os
from frappe.modules.import_file ... | for_sync=True)
#print module_name + ' | ' + doctype + ' | ' + name
frappe.db.commit()
# show progress bar
update_progress_bar("Updating DocTypes for {0}".format(app_name), i, l)
print()
def get_doc_files(files, start_path, force=0, sync_everything = False, verbose=False):
"""walk and sync all doctyp... | _theme', 'web_form', 'email_alert', 'print_style',
'data_migration_mapping', 'data_migration_plan']
for doctype in document_types:
doctype_path = os.path.join(start_path, doctype)
if os.path.exists(doctype_path):
for docname in os.listdir(doctype_path):
if os.path.isdir(os.path.join(doctype_path, docnam... |
rajashreer7/autotest-client-tests | linux-tools/perl_WWW_RobotRules/perl_WWW_RobotRules.py | Python | gpl-2.0 | 1,298 | 0.005393 | #!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class perl_WWW_RobotRules(test.test):
"""
Autotest module for testing basic functionality
of perl_WWW_RobotRules
@author Hariharan T.S. <harihare@in.ibm.com> ... | ize(self):
"""
Sets the overall failure counter for the test.
"""
self.nfail = 0
logging.info('\n Test initialize successfully')
def run_once(self, test_path=''):
"""
Trigg | er test run
"""
try:
os.environ["LTPBIN"] = "%s/shared" %(test_path)
ret_val = subprocess.Popen(['./perl-WWW-RobotRules.sh'], cwd="%s/perl_WWW_RobotRules" %(test_path))
ret_val.communicate()
if ret_val.returncode != 0:
self.nfail += 1
... |
chaos-soft/chocola | files/admin.py | Python | mit | 479 | 0 | from django.contrib | import admin
from .models import File, Link
from .forms import FileForm
class FileAdmin(admin.ModelAdmin):
list_display = ('id', 'md5', 'file', 'size')
list_ | per_page = 100
list_display_links = ('md5',)
form = FileForm
class LinkAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'file', 'user')
list_per_page = 100
list_display_links = ('name',)
admin.site.register(File, FileAdmin)
admin.site.register(Link, LinkAdmin)
|
sushengyang/Data-Science-45min-Intros | python-oop/life/__init__.py | Python | unlicense | 57 | 0.035088 | __all__ = [
| "beast"
| , "human"
]
|
hkariti/ansible | lib/ansible/modules/network/vyos/vyos_banner.py | Python | gpl-3.0 | 5,186 | 0.001928 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# 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 Li... | (.*)' % obj['banner'], line, re.M)
output = match
if output:
obj['text'] = output[0].encode().decode('unicode_escape')
obj['state'] = 'present'
return obj
def map_params_to_obj(module):
text = module.params['text']
if text:
text = "%r" % (str(text).strip())
re... | 'banner': module.params['banner'],
'text': text,
'state': module.params['state']
}
def main():
""" main entry point for module execution
"""
argument_spec = dict(
banner=dict(required=True, choices=['pre-login', 'post-login']),
text=dict(),
state=dict(de... |
cjaymes/pyscap | src/scap/model/ocil_2_0/QuestionResultsType.py | Python | gpl-3.0 | 1,472 | 0.003397 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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 Softw | are Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more d... | g with PySCAP. If not, see <http://www.gnu.org/licenses/>.
from scap.Model import Model
import logging
logger = logging.getLogger(__name__)
class QuestionResultsType(Model):
MODEL_MAP = {
'elements': [
# TODO: at least one of *_question_result
{'tag_name': 'boolean_question_result... |
nioo-knaw/hydra | uparse_scripts/die.py | Python | mit | 446 | 0.042601 | import sys
imp | ort traceback
def Die(Msg):
print >> sys.stderr
print >> sys.stderr
traceback.print_stack()
s = ""
for i in range(0 | , len(sys.argv)):
if i > 0:
s += " "
s += sys.argv[i]
print >> sys.stderr, s
print >> sys.stderr, "**ERROR**", Msg
print >> sys.stderr
print >> sys.stderr
sys.exit(1)
print "NOTHERE!!"
def Warning(Msg):
print >> sys.stderr
print >> sys.stderr, sys.argv
print >> sys.stderr, "**WARNING**", Msg
|
datamade/large-lots | lots_admin/migrations/0022_auto_20160927_1051.py | Python | mit | 462 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-27 15:51
from __future__ import unicode_literal | s
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lots_admin', '0021_auto_20160927_0941'),
]
operations = [
migrations.AlterField(
model_name='address',
name='ward',
field=models.CharField(max_length | =10, null=True),
),
]
|
mjs7231/pkmeter | pkm/plugins/network.py | Python | bsd-3-clause | 2,803 | 0.004638 | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES ... | ace):
newio = self._net_io_counters(newio)
newio['iface'] = iface
newio.update(netinfo[netifaces.AF_INET][0])
self._deltas(self.nics.get(iface,{}), newio)
self.nics[iface] = newio
elif iface in self.nics:... | sorted(self.nics.values(), key=lambda n:n['iface'])
self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters())
super(Plugin, self).update()
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
if iface.startswith(i... |
globaltoken/globaltoken | test/functional/test_runner.py | Python | mit | 23,006 | 0.003043 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
f... | 'store_true', help='only print results summary and failure logs')
parser.add_argument('--tmpdirprefix', '-t', default=tempfile.gettempdir(), help="Root directory for datadirs")
args, unknown_args = parser.parse_known_args()
# args to be passed on always start with two dashes; tests are the remaining unknow... | = "--"]
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
# Read config generated by configure.
config = configparser.ConfigParser()
configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini"
config.read_file(open(configfile))
passon_args.append("--configfile=%s" %... |
tchaly-bethmaure/Emotes | script/script_tools/framework_file_generator.py | Python | gpl-2.0 | 1,143 | 0.013123 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# Developped with python 2.7.3
import os
import sys
import tools
import json
print("The frame :")
name = raw_input("-> name of the framework ?")
kmin = float(raw_input("-> Minimum boundary ?"))
kmax = float(raw_input("-> Maximum boundary ?"))
precision = float(raw_input("-> ... | we define min_boundary max_boundar | y precision frequences)\n")
o.write(json.dumps([kmin, kmax, precision, distribution]))
o.close() |
JordiCarreraVentura/spellchecker | lib/CategoryTree.py | Python | gpl-3.0 | 7,145 | 0.004479 | import json
from collections import (
Counter,
defaultdict as deft
)
from copy import deepcopy as cp
# from cPickle import (
# dump as to_pickle,
# load as from_pickle
# )
from StringIO import StringIO
from TfIdfMatrix import TfIdfMatrix
from Tools import from_csv
class CategoryTree:
de... | print s | elf.vector_by_category[_id].most_common(20)
vector = self.vector_by_category[_id]
if not self.observed_category[category]:
return dict([])
parents = self.__get_parents(_id)
if not parents or depth >= self.max_depth:
tree[category] = dict([])
else:
... |
mganeva/mantid | Framework/PythonInterface/test/python/plugins/algorithms/AbinsBasicTest.py | Python | gpl-3.0 | 10,112 | 0.003362 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Labor | atory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, division, print_function)
import unittest
from mantid import log | ger
# noinspection PyUnresolvedReferences
from mantid.simpleapi import mtd, Abins, Scale, CompareWorkspaces, Load, DeleteWorkspace
from AbinsModules import AbinsConstants, AbinsTestHelpers
import numpy as np
class AbinsBasicTest(unittest.TestCase):
_si2 = "Si2-sc_Abins"
_squaricn = "squaricn_sum_Abins"
_... |
westurner/provis | setup.py | Python | bsd-3-clause | 2,041 | 0.00294 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with op... | tests',
tests_require=['pytest', 'pytest-capturelo | g'],
cmdclass = {
'test': PyTestCommand,
},
)
|
lorin/umdinst | test/testrunprogram.py | Python | bsd-3-clause | 1,972 | 0.022312 | import unittest
import sys
import os
sys.path.append('bin')
from umdinst import wrap
class TestRunProgram(unittest.TestCase):
def setUp(self):
self.tempfilename = 'emptyfile' # This is in createfile.sh
self.failIf(os.path.exists(self.tempfilename))
# Find the "touch" program
if os.path.exists('... | us = os.system("gcc -o fail test/testsource/fail.c")
self.failIf(status!=0)
self.failprog = './fail'
# Build a "succeeding" program, that returns zero status
status = os.system("gcc -o success test/testsource/success.c")
self.failIf( | status!=0)
self.successprog = './success'
def tearDown(self):
if os.path.exists(self.tempfilename):
os.unlink(self.tempfilename)
def testRunWithArgs(self):
prog = self.touchprog
# Make sure the file doesn't exist
self.failIf(os.path.exists(self.tempfilename))
# Create a tempora... |
iamthekyt/POS-System | src/controller.py | Python | gpl-3.0 | 5,417 | 0.006464 | # -*- coding: utf-8 -*-
import kivy
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from pos_system import POS, Item
from db import Database
from buttonex import ButtonEx
from ... | po | pup = Popup(
title='No Buy List',
content=Label(text='You need to start a new list!'),
size_hint=(None, None),
size=(400, 100)
)
popup.open()
return
button = Button(text=instance.text, size_hint_y = None, height... |
smarbos/adopteitor-server | adopteitor_core/migrations/0011_auto_20170221_2157.py | Python | mit | 368 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencie | s = [
('adopteitor_cor | e', '0010_ipn'),
]
operations = [
migrations.AlterModelOptions(
name='ipn',
options={'verbose_name_plural': 'IpnS'},
),
]
|
ostree/plaso | plaso/parsers/mcafeeav.py | Python | apache-2.0 | 5,046 | 0.005747 | # -*- coding: utf-8 -*-
"""Parser for McAfee Anti-Virus Logs.
McAfee AV uses 4 logs to track when scans were run, when virus databases were
updated, and when files match the virus database."""
from plaso.events import text_events
from plaso.lib import errors
from plaso.lib import timelib
from plaso.parsers import man... | ate'], row[u'time'], parser_mediator.timezone)
except errors.TimestampError:
return False
if timestamp is None:
return False
# U | se the presence of these strings as a backup or in case of partial file.
if (not u'Access Protection' in row[u'status'] and
not u'Would be blocked' in row[u'status']):
return False
return True
def ParseRow(self, parser_mediator, row_offset, row):
"""Parses a row and extract event objects.
... |
botswana-harvard/bhp065_project | bhp065/apps/hnscc_subject/admin/__init__.py | Python | gpl-2.0 | 263 | 0 | from .main import HnsccVisitAdmin, HnsccOffStudyAdmin
from .enrollment_admin import EnrollmentAdmin
from .contemp | orary_admin import ContemporaryAdmin
# from .historical_admin import HistoricalAdmin
from .hnscc_off_study_mod | el_admin import HnsccOffStudyModelAdmin
|
flagxor/rainbowforth | iconforth/iconforth.py | Python | gpl-3.0 | 17,696 | 0.010793 | import datetime
import os
import pickle
import pngcanvas
import jinja2
import random
import re
import sys
import webapp2
import zlib
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystem... | rce.iteritems():
dfn = ' '.join((str(i) for i in d))
| self.response.out.write('%s %s\n' % (w, dfn))
return
# Display it in a sensible order.
results = []
pending_ids = [lookup_id]
needed_ids = set([lookup_id])
while pending_ids:
# Pick one.
id = pending_ids[0]
pending_ids = pending_ids[1:]
# Grab out its parts.
int... |
TuDatTr/OkBot | main.py | Python | apache-2.0 | 10,102 | 0.001292 | # requires:
# pip install discord.py
# pip install asyncio
# pip install bs4
# pip install imgurpython
# pip install youtube-dl
# pip install chatterbot
# put this (view raw) in the base directory for windows:
# https://github.com/Just-Some-Bots/MusicBot/blob/ea5e0daebd384ec8a14c9a585da399934e2a6252/libopus-0.x64.dll... | wait bot.say(item.gifv)
else:
await bot.say(item.link)
@bot.command()
async def cat():
"""Sends random cat picture from Imgur"""
items = client.gallery_tag("cat", sort='viral', page=0, window='year').items
item = items[random.randint(0, 59)]
whil | e item.is_album:
item = items[random.randint(0, 59)]
if item.type == "image/gif":
await bot.say(item.gifv)
else:
await bot.say(item.link)
@bot.command()
async def dog():
"""Sends random dog picture from Imgur"""
items = client.gallery_tag("dog", sort='viral', page=0, window='ye... |
analysiscenter/dataset | batchflow/models/tf/fcn.py | Python | apache-2.0 | 9,221 | 0.002061 | """
Shelhamer E. et al "`Fully Convolutional Networks for Semantic Segmentation
<https://arxiv.org/abs/1605.06211>`_"
"""
import tensorflow as tf
from . import TFModel, VGG16
from .layers import conv_block
class FCN(TFModel):
""" Base Fully convolutional network (FCN) """
@classmethod
def default_config(... | = super().build_config(names)
config['body/num_classes'] = self.num_classes('targets')
config['head/num_classes'] = self.num_classes('targets')
return config
@classmethod
def initial_block(cls, inputs, base_network, name='initial_block', **kwargs):
""" Base n | etwork
Parameters
----------
inputs : tf.Tensor
input tensor
base_network : class
base network class
name : str
scope name
Returns
-------
tf.Tensor
"""
with tf.variable_scope(name):
x = bas... |
vntarasov/openpilot | opendbc/can/dbc.py | Python | mit | 8,588 | 0.009432 | import re
import os
import struct
import sys
import numbers
from collections import namedtuple, defaultdict
def int_or_float(s):
# return number, trying to maintain int format
if s.isdigit():
return int(s, 10)
else:
return float(s)
DBCSignal = namedtuple(
"DBCSignal", ["name", "start_bit", "size", "i... | None:
print("bad SG {0}".format(l))
sgname = dat.group(1)
start_bit = | int(dat.group(go + 2))
signal_size = int(dat.group(go + 3))
is_little_endian = int(dat.group(go + 4)) == 1
is_signed = dat.group(go + 5) == '-'
factor = int_or_float(dat.group(go + 6))
offset = int_or_float(dat.group(go + 7))
tmin = int_or_float(dat.group(go + 8))
... |
Impactstory/total-impact-core | totalimpact/providers/linkedin.py | Python | mit | 2,365 | 0.017336 | import os, re, requests
from bs4 import BeautifulSoup
from totalimpact.providers import provider
from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderRateLimitError
import logging
logger = logging.getLogger('ti.providers.linkedin')
class Linkedin(Provider):
example_id = ... | return True
return False
def member_items(self,
| linkedin_url,
provider_url_template=None,
cache_enabled=True):
return [("url", linkedin_url)]
@property
def provides_aliases(self):
return True
@property
def provides_biblio(self):
return True
def aliases(self,
aliases,
... |
Ubuntu-Solutions-Engineering/glance-simplestreams-sync-charm | hooks/charmhelpers/contrib/saltstack/__init__.py | Python | agpl-3.0 | 2,778 | 0 | """Charm Helpers saltstack - declare the state of your machines.
This helper enables you to declare your machine state, rather than
program it procedurally (and have to test each change to your procedures).
Your install hook can be as simple as:
{{{
from charmhelpers.contrib.saltstack import (
install_salt_suppor... | salt-minion package is installed from
the saltstack PPA. If from_ppa is False you must ensure
that the salt-minion package is available in the apt cache.
"""
if from_ppa:
su | bprocess.check_call([
'/usr/bin/add-apt-repository',
'--yes',
'ppa:saltstack/salt',
])
subprocess.check_call(['/usr/bin/apt-get', 'update'])
# We install salt-common as salt-minion would run the salt-minion
# daemon.
charmhelpers.fetch.apt_install('salt-co... |
BehavioralInsightsTeam/edx-platform | openedx/features/enterprise_support/tests/test_signals.py | Python | agpl-3.0 | 1,328 | 0.000753 | """Tests of email marketing signal handlers."""
import logging
import ddt
from django.test import TestCase
from mock import patch
from student.tests.factories import UserFactory
from openedx.features.enterprise_support.tests.factories import EnterpriseCustomerFactory, EnterpriseCustomerUserFactory
log = logging.getLo... | f setUp(self):
self.user = UserFactory.create(username='test', email=TEST_EMAIL)
super(EnterpriseS | upportSignals, self).setUp()
@patch('openedx.features.enterprise_support.signals.update_user.delay')
def test_register_user(self, mock_update_user):
"""
make sure marketing enterprise user call invokes update_user
"""
enterprise_customer = EnterpriseCustomerFactory()
Ent... |
mkelcb/knet | knet/com/io/pyplink.py | Python | mit | 18,683 | 0.000054 | """Module that reads binary Plink files."""
# This file is part of pyplink.
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Louis-Philippe Lemieux Perreault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
... |
__all__ = ["PyPlink"]
# The logger
logger = logging.getLogger(__name__)
# The recoding values
_geno_recode = {1: -1, # Unknown genotype
2: 1, # Heterozygous genotype
0: 2, # Homozygous A1
3: 0} # Homozygous A2
_byte_recode = dict(v | alue[::-1] for value in _geno_recode.items())
class PyPlink(object):
"""Reads and store a set of binary Plink files.
Args:
prefix (str): The prefix of the binary Plink files.
mode (str): The open mode for the binary Plink file.
bed_format (str): The type of bed (SNP-major or INDIVIDUA... |
thecardcheat/egauge-api-examples | python/eGauge.py | Python | mit | 5,735 | 0.013426 | # Copyright (c) 2013 eGauge Systems LLC
# 4730 Walnut St, Suite 110
# Boulder, CO 80301
# voice: 720-545-9767
# email: davidm@egauge.net
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | ,
"units" : ["DEG", | "DEGs"],
"scale" : 1,
},
"h": {
"doc" : "Humidity",
"units" : ["%", "%s"],
"scale" : 1e-1,
},
"Qv": {
"doc" : "Volumetric flow-rate",
"units" : ["m^3/s", "m^3"],
"scale" : 1e-9,
},
... |
mupi/tecsaladeaula | core/migrations/0039_auto__add_field_course_riw_style.py | Python | agpl-3.0 | 19,646 | 0.007839 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Course.riw_style'
db.add_column(u'core_course', 'riw_styl... | m['accounts.City']", 'null': 'True', 'blank': 'True'}),
'cpf': ('django.db.models.fields.CharField', [], {'max_length': '14', 'null': 'True', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'd | isciplines': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.Discipline']", 'null': 'True', 'blank': 'True'}),
'education_levels': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['accounts.EducationLevel']", ... |
jskksj/cv2stuff | cv2stuff/tests/test_hypothesis_code.py | Python | isc | 206 | 0 | from hypothesis import given
from hypothesis.s | trategies import text
from cv2stuff.hypothesis_code import encode, decode
@given(text())
def test_decode_inverts_encod | e(s):
assert decode(encode(s)) == s
|
fitnr/addfips | tests/test_cli.py | Python | gpl-3.0 | 3,471 | 0.000576 | # -*- coding: utf-8 -*-
# This file is part of addfips.
# http://github.com/fitnr/addfips
# Licensed under the GPL-v3.0 license:
# http://opensource.org/licenses/GPL-3.0
# Copyright (c) 2016, fitnr <fitnr@fakeisthenewreal>
# pylint: disable=missing-docstring,invalid-name
import csv
import io
import subprocess
import sy... | ):
| sys.argv = self.co_args[:-2] + ['--state-name', 'Alabama']
sys.stdout = io.StringIO()
addfips_cli.main()
sys.stdout.seek(0)
reader = csv.DictReader(sys.stdout)
row = next(reader)
self.assertIn('county', row.keys())
self.assertIn('fips', row.keys())
... |
dhinakg/BitSTAR | api/database/table.py | Python | apache-2.0 | 1,329 | 0.004515 | # Copyright 2017 Starbot Discord Project
#
# Licensed under the Apache License, Version 2.0 (the "License | ");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,... | either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from api.database import DAL
from api.database.db import DB
from api.database.DAL import SQLite
class Table:
name = None
table_type = None
def __init__(self, name_in, t... |
douglasdecouto/py-concord | ConcordAlarm.indigoPlugin/Contents/Server Plugin/concord/__init__.py | Python | bsd-3-clause | 17 | 0 | # con | cord mo | dule
|
samjy/acmeclient | acmeclient/__init__.py | Python | mit | 73 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__VERSI | ON__ = | ""
# EOF
|
nasfarley88/thebslparlour | bslparloursite/tgbot/models.py | Python | cc0-1.0 | 651 | 0.00768 | from django.db import models
from django.utils import timezone
from videolibrary.models import SourceVideo
# Create y | our models here.
# TODO consider whether this is needed anymore
class RequestedSign(models.Model):
short_description = models.CharField(max_length=100)
description = models.TextField()
date_added = models.DateTimeField(default=timezone.now, editable=False)
def __str__(self):
return self.sh... | ls.ForeignKey(SourceVideo)
|
StartupsPoleEmploi/labonneboite | labonneboite/common/load_data.py | Python | agpl-3.0 | 8,478 | 0.003303 | import os
import pickle
import csv
import pandas as pd
import math
from functools import lru_cache, reduce
from collections import defaultdict
USE_ROME_SLICING_DATASET = False # Rome slicing dataset is not ready yet
if USE_ROME_SLICING_DATASET:
OGR_ROME_FILE = "rome_slicing_dataset/ogr_rome_mapping.csv"
ROM... | the office belongs to
'''
#we split on the label which is from type "10-19" OR 10000+
splitted_label = row['label'].split('-')
if len(splitted_label) == 1: #10000+
value = math.inf if which == 'end_effectif' else 10000
else:
if which == 'start_effectif':... | itted_label[1])
return value
df = load_pd_dataframe("helpers/effectif_labels.csv", ',', dtype= |
google-research/scenic | scenic/common_lib/video_utils.py | Python | apache-2.0 | 1,353 | 0.007391 | # Copyright 2022 The Scenic 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 applicable law or agreed to in w... | (temporal_indices).astype(jnp.int32)
temporal_indices = jnp.minimum(temporal_indices, num_frames - 1)
return x[:, temporal_indices] # [n, t_s, | in_h, in_w, c]
|
zr40/scc | lib/hardware.py | Python | mit | 3,587 | 0.02983 | from serial import Serial
class Hardware(object):
def __init__(self, port, debug=False):
self.debug = debug
self.port = Serial(port, timeout=0.01)
self.resetConnection()
def resetConnection(self):
print 'Establishing connection...'
repeatCount = 0
while True:
if repeatCount == 100:
print 'Mo... | inbytes.pop()
return inbytes
def send(self, data):
if self.debug:
print 'OUT: ' + ' '.join('%02X' % byte for byte in data)
print ' ' + repr(''.join(chr(byte) for byte in data))
print
self | .port.write(''.join(chr(byte) for byte in data))
def sendWithChecksum(self, data):
sum = 0
for byte in data:
sum += byte
checksum = (0x100 - sum) % 0x100
self.send(data + [checksum])
def reset(self):
self.setPC(0x0000)
|
ekarlso/partizan | tests/functional/fixtures/database.py | Python | apache-2.0 | 2,371 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Hewlett-Packard Develo | pment Co | mpany, L.P.
#
# 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
# distr... |
thundergolfer/mAIcroft | maicroft/social_info_extraction.py | Python | mit | 15,272 | 0.000262 | import datetime
try:
import urlparse
except (ImportError):
import urllib.parse as urlparse
import calendar
import pytz
import re
from maicroft.util import Util
from maicroft.activity_metrics_proc import process_metrics
from maicroft.activity_metrics_proc import process_submission_metrics
from maicroft.subreddi... | parser.normalize(w, t) for w, t in noun_phrase if t.startswith("N")
])
noun = next(
(w for w, t in noun_phrase if t.startswith("N")), None
)
if noun:
# See if noun is a pet, family member or a relationship partner
pet = parser.pet_animal(noun)
... | member = parser.family_member(noun)
relationship_partner = parser.relationship_partner(noun)
if pet:
user.pets.append((pet, post_permalink))
elif family_member:
user.family_members.append((family_member, post_permalink))
elif relationship_... |
vthorsteinsson/tensor2tensor | tensor2tensor/models/bytenet_test.py | Python | apache-2.0 | 1,719 | 0.004072 | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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 applicable... |
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.models import bytenet
import tensorflow as tf
class ByteNetTest(tf.test.TestCase):
def testByteNet(self):
vocab_size = 9
x = np.random.ran... | p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size)
with self.test_session() as session:
features = {
"inputs": tf.constant(x, dtype=tf.int32),
"targets": tf.constant(y, dtype=tf.int32),
}
model = bytenet.ByteNet(
hparams, tf.estimator.ModeKeys.T... |
cedricpradalier/vrep_ros_ws | src/ar_slam_base/nodes/rover_mapping.py | Python | bsd-3-clause | 6,109 | 0.014241 | #!/usr/bin/env python
import roslib; roslib.load_manifest('ar_slam_base')
import rospy
from std_msgs.msg import Float64,Float32
from sensor_msgs.msg import JointState
from geometry_msgs.msg import PointStamped
import tf
import numpy
import message_filters
from ar_slam_base.mapping_kf import *
from ar_track_alvar_msg... | arget_frame,timestamp)
def compass_cb(self, value):
self.mapper.update_compass(value.data,self.compass_precision)
def ar_cb(self, markers):
for m in markers.markers:
| if m.id > 32:
continue
self.listener.waitForTransform("/%s/ground"%self.name,m.header.frame_id, m.header.stamp, rospy.Duration(1.0))
m_pose = PointStamped()
m_pose.header = m.header
m_pose.point = m.pose.pose.position
m_pose = self.lis... |
SchrodingersGat/kicad-footprint-generator | scripts/Connector/Connector_JST/conn_jst_VH_tht_side-stabilizer.py | Python | gpl-3.0 | 12,829 | 0.027983 | #!/usr/bin/env python3
'''
kicad-footprint-generator 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.
kicad-footprint-generator is distribut... | 0.9
x4 = pitch * (pins - 1) + 0.9
y6 = 13.4
y4 = y6 - 7.7
y1 = y4 - 7.7
y2 = y1 + 2
y3 = y1 + 4.5
y5 = y3 + 9.4
body_edge={'left':x1, 'right':x2, 'top':y4, 'bottom':y5}
#draw shroud outline on F.Fab layer
k | icad_mod.append(RectLine(start=[x3,y3],end=[x4,y5], layer='F.Fab', width=configuration['fab_line_width']))
kicad_mod.append(PolygoneLine(polygone=[{'x':x4-0.2,'y':y3},{'x':x4-0.2,'y':y1},{'x':x2,'y':y1},{'x':x2,'y':y4},{'x':x4,'y':y4}], layer='F.Fab', width=configuration['fab_line_width']))
kicad_mod.append(Pol... |
kdart/pycopia | core/pycopia/OS/Linux/sysctl.py | Python | apache-2.0 | 52 | 0.019231 | """
| Linux kernel system co | ntrol from Python.
"""
|
pypingou/pypass | pypass/pypobj.py | Python | gpl-3.0 | 4,872 | 0.003079 | """ Object module for pypass
This module contains the objects from and to which the json is
generated/read.
"""
#-*- coding: utf-8 -*-
# Copyright (c) 2011 Pierre-Yves Chibon <pingou AT pingoured DOT fr>
# Copyright (c) 2011 Johan Cwiklinski <johan AT x-tnd DOT be>
#
# This file is part of pypass.
#
# pypass is free s... | ount("p4", "mdp4")
folder2.accounts.append(account)
folder1.folders.append(folder2)
return root
def iterate_over_tree(obj, out, ite=0):
""" Iterate over the items in a PypFolder "" | "
out = '%s"%s": { ' % (out, obj.name)
if obj.description is not None and obj.description != "":
out = '%s "description": "%s",' % (out, obj.description)
ite = ite + 1
cnt = 0
out = '%s "accounts": [' % out
for item in obj.accounts:
cnt = cnt + 1
out = '%s { "name": "%s",... |
damianpv/exercise | home/admin.py | Python | gpl-2.0 | 328 | 0.009146 | from django.contrib import admin
from .models import Friend
class FriendAdmin(admin.ModelAdmin):
list_display = ('full_name', 'profile_image')
def profile_image(self, obj):
return '<img src="%s" width="50" heith="50">' | % obj.photo
profile_image.allow_tags = True
admin.site.register(Friend, FriendAdmin) | |
kikusu/chainer | chainer/datasets/sub_dataset.py | Python | mit | 7,241 | 0 | import numpy
import six
from chainer.dataset import dataset_mixin
class SubDataset(dataset_mixin.DatasetMixin):
"""Subset of a base dataset.
SubDataset defines a subset of a given base dataset. The subset is defined
as an interval of indexes, optionally with a given permutation.
If ``order`` is gi... | he other one is a
:math:`k`-fold cross validation, in whi | ch the dataset is divided into
:math:`k` subsets, and :math:`k` different splits are generated using each
of the :math:`k` subsets as a validation set and the rest as a training
set. It can be done by :func:`get_cross_validation_datasets`.
Args:
dataset: Base dataset.
start (int): The f... |
consciousnesss/learn_theano | learn_theano/deeplearning_tutorials/test_0_logistic_regression.py | Python | apache-2.0 | 4,748 | 0.004212 |
import theano
import theano.tensor as T
import numpy as np
from learn_theano.utils.download_all_datasets import get_dataset
import cPickle
import time
def one_zero_loss(prediction_labels, labels):
return T.mean(T.neq(prediction_labels, labels))
def negative_log_likelihood_loss(prediction_probailities, labels):... | h_index in ra | nge(n_train_batches):
train_model(minibatch_index)
iteration = epoch*n_train_batches + minibatch_index
if (iteration + 1) % validation_frequency == 0.:
validation_cost = np.mean([validation_model(i) for i in range(n_validation_batches)])
... |
austinharris/gem5-riscv | src/mem/slicc/symbols/Transition.py | Python | bsd-3-clause | 2,750 | 0.004 | # Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
# Copyright (c) 2009 The Hewlett-Packard Development Company
# 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 co... | BUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WAR | RANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF ... |
KamilWo/bestja | addons/bestja_offers/models/application.py | Python | agpl-3.0 | 8,916 | 0.000786 | # -*- coding: utf-8 -*-
from datetime import date
from urllib import quote_plus
from openerp import models, fields, api, exceptions
class ApplicationRejectedReason(models.Model):
_name = 'offers.application.rejected'
name = fields.Char(required=True)
description = fields.Text(required=True)
class Appl... | project and the organizatio | n
"""
offer = self.offer
offer.project.write({
'members': [(4, self.user.id)]
})
offer.sudo().project.organization.write({
'volunteers': [(4, self.user.id)]
})
# Unpublish if all vacancies filled
if offer.accepted_application_count ... |
felix9064/python | Demo/demo/demo003.py | Python | mit | 721 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
编程练习:使用二分查找算法求一个任意非负数的平方根(近似值即可)
"""
while True:
x = input("请输入一个非负数:")
try:
x = i | nt(x)
if x < 0:
print(x, " | 不是一个非负数")
else:
break
except ValueError:
print(x, " 不符合要求")
epsilon = 0.0001
num_guesses = 0
low = 0.0
high = max(1.0, x)
ans = (high + low) / 2.0
while abs(ans**2 - x) >= epsilon:
num_guesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + ... |
stackforge/tacker | samples/mgmt_driver/kubernetes_mgmt.py | Python | apache-2.0 | 147,274 | 0.000109 | # Copyright (C) 2021 FUJITSU
# 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 a... | '{}.'.format(ssh_command))
retry -= 1
if retry < 0:
LOG.error('It is time out, When execute command: '
'{}.'.format(ssh_command))
raise exceptions.MgmtDriverOtherError(
error_message=... | |
hmdavis/flask-mega-tutorial | app/views.py | Python | bsd-3-clause | 4,940 | 0.018421 | from flask import render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, lm, oid
from forms import LoginForm, EditForm
from models import User, ROLE_USER, ROLE_ADMIN
from datetime import datetime
@lm.user... | er follow him/herself
db.session.add(user.follow(user))
db.session.commit()
remember_me = Fa | lse
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('in... |
ulif/pulp | server/test/unit/server/webservices/test_urls.py | Python | gpl-2.0 | 33,452 | 0.001196 | import unittest
from django.core.urlresolvers import resolve, reverse, NoReverseMatch
from pulp.server.webservices.urls import handler404
def assert_url_match(expected_url, url_name, *args, **kwargs):
"""
Generate a url given args and kwargs and pass it through Django's reverse and
resolve f... | l, url_name, type_id='mock-type')
def test_match_content_unit_resource(self):
"""
Test url matching for content_unit_resource.
"""
url = '/v2/content/units/mock-type/mock-unit/'
url_name = 'content_unit_resource'
assert_url_match(url, url_name, type_id='mock-type', u... | r_metadata_resource(self):
"""
Test url matching for content_unit_user_metadata_resource.
"""
url = '/v2/content/units/mock-type/mock-unit/pulp_user_metadata/'
url_name = 'content_unit_user_metadata_resource'
assert_url_match(url, url_name, type_id='mock-type', unit_id='m... |
mylxiaoyi/mypyqtgraph-qt5 | examples/MultiplePlotAxes.py | Python | mit | 1,925 | 0.016623 | # -*- coding: utf-8 -*-
"""
Demonstrates a way to put multiple axes around a single plot.
(This will eventually become a built-in feature of PlotItem)
"""
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
impo... | tem(p3)
ax3.linkToView(p3)
p3.setXLink(p1)
ax3.setZValue(-10000)
ax3.setLabel('axis 3', color='#ff0000')
## Handle view resizing
def updateViews():
## view has resized; update auxiliary views to match
global p1, p2, p3
p2.setGeometry(p1.vb.sceneBoundingRect())
p3.setGeometry(p1.vb.sceneBo | undingRect())
## need to re-update linked axes since this was called
## incorrectly while views had different shapes.
## (probably this should be handled in ViewBox.resizeEvent)
p2.linkedViewChanged(p1.vb, p2.XAxis)
p3.linkedViewChanged(p1.vb, p3.XAxis)
updateViews()
p1.vb.sigResized.connect(u... |
carvalhomb/tsmells | guess/src/Lib/xml/parsers/xmlproc/namespace.py | Python | gpl-2.0 | 5,187 | 0.022556 | """
A parser filter for namespace support. Placed externally to the parser
for efficiency reasons.
$Id: namespace.py,v 1.1 2005/10/05 20:19:37 eytanadar Exp $
"""
import string
import xmlapp
# --- ParserFilter
class ParserFilter(xmlapp.Application):
"A generic parser filter class."
def __ini... | for prefix in del_ns:
del self.ns_map[prefix]
self.app.handle_end_tag(name)
# --- Internal methods
def __process_name(self,name,default_to=None):
n=string.split(name,":")
if len(n)>2:
se | lf.parser.report_error(1900)
return name
elif len(n)==2:
if n[0]=="xmlns":
return name
try:
return "%s %s" % (self.ns_map[n[0]],n[1])
except KeyError:
self.parser.report_error(1902)
... |
peter-wangxu/python_play | test/mock_test/MockChild.py | Python | apache-2.0 | 160 | 0.00625 | import mock
class MockTest(m | ock.Mock):
def test_fun1(self, p1, p2):
pass
m = MockTest()
m.test_fun1(1, 2)
m.test_fun1.assert_call | ed_with(1, 2) |
mapnik/python-mapnik | test/python_tests/topojson_plugin_test.py | Python | lgpl-2.1 | 3,919 | 0.000511 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import os
from nose.tools import assert_almost_equal, eq_
import mapnik
from .utilities import execution_path, run_all
def setup():
# All of the paths used are relative, if we run the tests
# from another ... | pojson/escaped.topojson')
e = ds.envelope( | )
assert_almost_equal(e.minx, -81.705583, places=7)
assert_almost_equal(e.miny, 41.480573, places=6)
assert_almost_equal(e.maxx, -81.705583, places=5)
assert_almost_equal(e.maxy, 41.480573, places=3)
def test_topojson_properties():
ds = mapnik.Datasource(
type='t... |
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/plugin.video.muchmovies.hd/default.py | Python | gpl-2.0 | 51,620 | 0.010965 | # -*- coding: utf-8 -*-
'''
Much Movies HD XBMC Addon
Copyright (C) 2014 lambda
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
(... | contextMenu().settings_open()
elif action == 'addon_home': contextMenu().addon_home()
elif action == 'view_movies': contextMenu().view('movies')
elif action == 'metadata_movies': contextMenu().metadata('movie', name, url, imdb, '', '')
... | name, url, imdb, '', '')
elif action == 'playcount_movies': contextMenu().playcount('movie', imdb, '', '')
elif action == 'library': contextMenu().library(name, url)
elif action == 'download': contextMenu().download(name, url)
elif action ... |
bigswitch/sample-scripts | bcf/controller_bcf.py | Python | mit | 7,886 | 0.006848 | #
# Simple BCF config script
# No error checking
#
import requests
import json
import sys
requests.packages.urllib3.disable_warnings()
class Controller(object):
"""
controller version 4.x
"""
def __init__(self, controller_ip, access_token):
self.bcf_path = '/api/v1/data/controller/applica... | path = '/info/statistic/interface-counter[switch-dpid="%s"]/interface[name="%s"]' % (switch_dpid, interface)
response = self.make_request('DELETE', path, data='{}').json()
return response
def switch_dpid(self, switch):
""" """
path = '/switch-config[name="%s"]?sel... | f interface(self, switch, interface, action='no-shutdown'):
""" """
if action == 'shutdown':
path = '/switch-config[name="%s"]/interface[name="%s"]' %(switch, interface)
data = '{"shutdown": true}'
return self.make_request('PATCH', path, data=data, core_path=True)
... |
edisonlz/fruit | web_project/base/site-packages/django/contrib/gis/db/backends/postgis/creation.py | Python | apache-2.0 | 4,498 | 0.001779 | from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND... | else:
index_ops = ''
els | e:
index_ops = ' ' + style.SQL_KEYWORD(self.geom_index_ops)
output.append(style.SQL_KEYWORD('CREATE INDEX ') +
style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) +
style.SQL_KEYWORD(' ON ') +
... |
zultron/virt-manager | tests/capabilities.py | Python | gpl-2.0 | 11,259 | 0.002487 | # Copyright (C) 2013 Red Hat, Inc.
#
# 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.
#
# This program is distributed in ... | s) == 2)
self.assertTrue(len(caps.host.topology.cells[0].cpus) == 8)
self.assertTrue(len(caps.host.topology.cells[0].cpus) == 8)
def testCapsCPUFeaturesOldSyntax(self):
filename = "rhel5.4-xen-caps-virt-enabled.xml"
host_feature_list = ["vmx"]
feature_dict = build_host_featu... | = self._buildCaps(filename)
for f in feature_dict.keys():
self.assertEquals(caps.host.features[f], feature_dict[f])
def testCapsCPUFeaturesOldSyntaxSVM(self):
filename = "rhel5.4-xen-caps.xml"
host_feature_list = ["svm"]
feature_dict = build_host_feature_dict(host_featur... |
specify/specify7 | specifyweb/workbench/views.py | Python | gpl-2.0 | 37,610 | 0.002154 | import json
import logging
from typing import List, Optional
from uuid import uuid4
from django import http
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.db.utils import OperationalError
from django.views.decorators.http import requ... | e7bec1acca",
}
}
},
},
"description": "St | atus of the " +
"upload / un-upload / validation process",
}
]
},
"wb_rows": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string",
... |
back-to/streamlink | tests/test_plugins_input.py | Python | bsd-2-clause | 2,652 | 0.001131 | import unittest
import os.path
from contextlib import contextmanager
from streamlink.plugin.plugin import UserInputRequester
from tests.mock import MagicMock, patch
from streamlink import Streamlink, PluginError
from streamlink_cli.console import ConsoleUserInputRequester
import streamlink_cli.console
from tests.plug... | lue=isatty):
mock_console = MagicMock()
mock_console.ask.return_value = "username"
mock_console.askpass.retur | n_value = "password"
yield ConsoleUserInputRequester(mock_console)
def test_user_input_bad_class(self):
p = _TestPlugin("http://example.com/stream")
self.assertRaises(RuntimeError, p.bind, self.session, 'test_plugin', object())
def test_user_input_not_implemented(self):
p =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.