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 |
|---|---|---|---|---|---|---|---|---|
abo-abo/edx-platform | common/lib/xmodule/xmodule/modulestore/tests/test_split_modulestore.py | Python | agpl-3.0 | 55,767 | 0.003389 | '''
Created on Mar 25, 2013
@author: dmitchell
'''
import datetime
import subprocess
import unittest
import uuid
from importlib import import_module
from xblock.fields import Scope
from xmodule.course_module import CourseDescriptor
from xmodule.modulestore.exceptions import InsufficientSpecificationError, ItemNotFoun... | derr = p.communicate()
if p.returncode != 0:
print "Couldn't run mongoimport:"
print stdout
print stderr
raise Exception("DB did not init correctly")
@classmethod
def tearDownClass(cls):
collection_prefix = SplitModuleTest.MODU... | odulestore:
for collection in ('active_versions', 'structures', 'definitions'):
modulestore().db.drop_collection(collection_prefix + collection)
# drop the modulestore to force re init
SplitModuleTest.modulestore = None
def findByIdInResult(self, collection, _id)... |
EduardoMolina/SU2 | meson_scripts/init.py | Python | lgpl-2.1 | 7,414 | 0.020637 | #!/usr/bin/env python3
## \file init.py
# \brief Initializes necessary dependencies for SU2 either using git or it
# fetches zip files.
# \author T. Albring
# \version 7.0.3 "Blackbird"
#
# SU2 Project Website: https://su2code.github.io
#
# The SU2 Project is maintained by the SU2 Foundation
# (http://su2... | ized
status_indicator = status[0][0]
if status_indicator == '+':
# Write a warning that the sha tags do not match
sys.stderr.write('WARNING: the currently checked out submodule commit in '
+ path + ' does not match the SHA-1 found in the index.\n')
sys.stderr.writ... | e --init '+ path + '\' to reset the module if necessary.\n')
elif status_indicator == '-':
# Initialize the submodule if necessary
print('Initialize submodule ' + path + ' using git ... ')
subprocess.run(['git', 'submodule', 'update', '--init', path], check = True, cwd = sys.path[0])
# Check... |
FXIhub/hummingbird | examples/flash/holo-2017/conf_tof.py | Python | bsd-2-clause | 6,533 | 0.013929 | # Import analysis/plotting modules
import analysis.event
import analysis.hitfinding
import analysis.pixel_detector
import analysis.sizing
import plotting.image
import plotting.line
import plotting.correlation
import plotting.histogram
from backend.record import add_record
import numpy as np
import time
import ipc
impor... |
nx=1024
pixel_size=7.5e-05
center_shift=int((gap_top-gap_bottom)/pixel_size)
# Quick config parameters
hitScoreThreshold = 13000
aduThreshold = 200
strong_hit_threshold = 60000
#experiment_fo | lder = "/data/beamline/current"
experiment_folder = "/asap3/flash/gpfs/bl1/2017/data/11001733"
# Specify the facility
state = {}
state['Facility'] = 'FLASH'
# Specify folders with frms6 and darkcal data
state['FLASH/DataGlob'] = os.path.join(experiment_folder, "raw/pnccd/block-02/holography_*_*_*_*.frms6")
state['FLAS... |
zhlinh/leetcode | 0171.Excel Sheet Column Number/test.py | Python | apache-2.0 | 153 | 0 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
from solution import Solution
s = "AA"
# s = 'Z'
sol | = Solution()
res = sol.titleToNumber(s)
print(res)
|
EttusResearch/gnuradio | gnuradio-runtime/examples/mp-sched/synthetic.py | Python | gpl-3.0 | 4,544 | 0.004401 | #!/usr/bin/env python
#
# Copyright 2008,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your optio... | ad, pipeline(options.nstages, ntaps))
def time_it(tb):
start = os.times()
tb.run()
stop = os.times()
delta = map((lambda a, b: a-b), stop, start)
user, sys, childrens_user, childrens_sys, real = delta
total_user = user + childrens_user
total_sys = sys + childrens_sys
if tb.machine_rea... | al, total_user, total_sys, (total_user+total_sys)/real, tb.flop, tb.flop/real)
else:
print "npipes %7d" % (tb.npipes,)
print "nstages %7d" % (tb.nstages,)
print "nsamples %s" % (eng_notation.num_to_str(tb.nsamples),)
print "real %7.3f" % ... |
slipstream/SlipStreamClient | client/src/setup.py | Python | apache-2.0 | 2,355 | 0.000425 | #!/usr/bin/env python
import os
from distutils.core import setup
def _fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
... | cwd = os.getcwd()
if root_dir != '':
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk(basepkg_name):
# Ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
if dirname.startswith('.'):
del dirnames[i]
if '__init__.py... | 'slipstream-client'
VERSION = '1.0-0'
DESCRIPTION = 'SlipStream client'
LONG_DESCRIPTION = 'SlipStream client: API and CLI'
AUTHOR = 'SixSq Sarl, (sixsq.com)'
AUTHOR_EMAIL = 'info@sixsq.com'
LICENSE = 'Apache License, Version 2.0'
PLATFORMS = 'Any'
URL = 'http://sixsq.com'
# Cheese shop (PyPI)
CLASSIFIERS = [
"Dev... |
MERegistro/meregistro | meregistro/apps/registro/forms/DependenciaFuncionalFormFilters.py | Python | bsd-3-clause | 1,595 | 0.004397 | # -*- coding: UTF-8 -*-
from django import forms
from apps.registro.models import DependenciaFuncional, Jurisdiccion, TipoGestion, TipoDependenciaFuncional, TipoEducacion
class DependenciaFuncionalFormFilters(forms.Form):
jurisdiccion = forms.ModelChoiceField(queryset=Jurisdiccion.objects.order_by('nombre'), lab... | False)
nombre = forms.CharField(max_length=50, label='Nombre', required=False)
def buildQuery(self, q=None):
"""
Crea o refina un query de búsqueda.
"""
if q is None:
q = DependenciaFuncional.objects.all()
if self.is_valid():
def filter_by(field):... | if filter_by('nombre'):
q = q.filter(nombre__icontains=self.cleaned_data['nombre'])
if filter_by('jurisdiccion'):
q = q.filter(jurisdiccion=self.cleaned_data['jurisdiccion'])
if filter_by('tipo_gestion'):
q = q.filter(tipo_gestion=self.cleaned_data['tipo_gestion'... |
tensor-tang/Paddle | python/paddle/fluid/contrib/tests/test_distributed_reader.py | Python | apache-2.0 | 1,305 | 0 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Licen | se");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import n... |
zstackio/zstack-woodpecker | zstackwoodpecker/test/test_engine.py | Python | apache-2.0 | 351 | 0.014245 | '''
@author: Frank
'''
import unittest
from zstackwoodpecker.engine import engine
class Test(unittest.TestCase):
def testName(self):
logfd = open('/tmp/log', 'w')
engine.execute_case('test/testcase2.py', logfd)
|
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.te | stName']
unittest.main() |
pydotorg/pypi | tools/email_renamed_users.py | Python | bsd-3-clause | 3,025 | 0.000661 | import smtplib
import pickle
import sys
import os
from email.mime.text import MIMEText
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path = | [root] + sys.path
import config
import store
config = config.Config("config.ini")
store = store.Store(config)
EMAIL_PLURAL = """
Hello there!
PyPI has begun to enforce restrictions on what a valid Python package name
contains.
These rules are:
* Must contain ONLY ASCII letters, digits, underscores, hyphens, and ... | se new names represent what someone using pip or easy_install would already
have had to use in order to install your packages.
I am sorry for any inconvenience this may have caused you.
"""
EMAIL_SINGLE = """
Hello there!
PyPI has begun to enforce restrictions on what a valid Python package name
contains.
These ru... |
doraemonext/wechat-platform | wechat_platform/system/setting/models.py | Python | bsd-2-clause | 2,006 | 0.00168 | # -*- coding: utf-8 -*-
import logging
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
logger_setting = logging.getLogger(__name__)
class SettingManager(models.Manager):
def add(self, name, value, force=False):
"""
添加一条新的设置项
:param name: 名称
:pa... | me=name)
except ObjectDoesNotExist:
setting = super(SettingManager, self).create(name=name, value=value)
logger_setting.info('Settings created [Detail] %s' % setting.__dict__)
return setting
if force:
setting.value = value
setting.s | ave()
logger_setting.info('Settings saved [Detail] %s' % setting.__dict__)
return setting
def get(self, name):
"""
根据name获取对应的选项内容
:param name: 选项名称
:return: 选项内容
"""
return super(SettingManager, self).get_queryset().get(name=name).value
def ... |
bitmovin/bitmovin-python | bitmovin/resources/models/encodings/start/scheduling.py | Python | unlicense | 1,314 | 0.002283 | from bitmovin.errors import InvalidTypeError
from bitmovin.utils import Serializable
class Scheduling(Serializable):
def __init__(self, priority=None, prewarmed_instance_pool_ids=None):
super().__init__()
self._prewarmed_instance_pool_ids = None
self.priority = priority
self.prewa... | _ids):
if new_prewarmed_instance_pool_ids is None:
self._prewarmed_ | instance_pool_ids = None
return
if not isinstance(new_prewarmed_instance_pool_ids, list):
raise InvalidTypeError('prewarmedInstancePoolIds has to be a list of strings')
if all(isinstance(pool_id, str) for pool_id in new_prewarmed_instance_pool_ids):
self._prewarmed_... |
zhangtianyi1234/django-haystack | haystack/backends/elasticsearch_backend.py | Python | bsd-3-clause | 37,888 | 0.002006 | from __future__ import unicode_literals
import datetime
import re
import warnings
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models.loading import get_model
from django.utils import six
import haystack
from haystack.backends import BaseEngine, BaseSearchBacke... | ,
"max_gram": 15,
"side": "front"
}
},
"filter": {
"haystack_ngram": {
"type": "nGram",
"min_gram": 3,
"max_gram": 15
... | "haystack_edgengram": {
"type": "edgeNGram",
"min_gram": 2,
"max_gram": 15
}
}
}
}
}
def __init__(self, connection_alias, **connection_options):
super(Elastic... |
jsternberg/ansible-modules-core | cloud/amazon/ec2_group.py | Python | gpl-3.0 | 17,973 | 0.002392 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
... | me=group_name, id=group_id)
groups[group_id] = group_instance
groups[group_name] = group_instance
elif 'group_id' in rule:
group_id = rule['group_id']
elif 'group_name' in rule:
group_name = rule['group_name']
if group_name == name:
group_id = group.id
... | name].id
else:
if not rule.get('group_desc', '').strip():
module.fail_json(msg="group %s will be automatically created by rule %s and no description was provided" % (group_name, rule))
if not module.check_mode:
auto_group = ec2.create_security_group(group_... |
opencast/pyCA | tests/test_capture.py | Python | lgpl-3.0 | 3,301 | 0 | # -*- coding: utf-8 -*-
'''
Tests for basic capturing
'''
import os
import os.path
import shutil
import tempfile
import unittest
from pyca import capture, config, db, utils
from tests.tools import should_fail, terminate_fn, reload
class TestPycaCapture(unittest.TestCase):
def setUp(self):
utils.http_r... | .end = self.event.start
self.event.status = db.Status.UPCOMING
data = [{'data': u'äüÄÜß',
'fmttype': 'application/xml',
'x-apple-filename': 'episode.xml'},
{'data': u'äüÄÜß',
'fmttype': 'application/xml',
'x-a | pple-filename': 'series.xml'},
{'data': u'event.title=äüÄÜß\n' +
u'org.opencastproject.workflow.config.x=123\n' +
u'org.opencastproject.workflow.definition=fast',
'fmttype': 'application/text',
'x-apple-filename': 'org.o... |
txm/potato | urls.py | Python | bsd-3-clause | 156 | 0.00641 | from | django.conf.urls.defaults import *
handler500 = 'djangotoolbox.errorviews.server_error'
urlpatterns = patterns('',
(r'', i | nclude('txm.urls')),
)
|
aholmback/fuse | fuse/__about__.py | Python | mit | 489 | 0 | from __future__ import absolute_import, di | vision, print_function
__all__ = [
'__title__', '__summary__', '__uri__', '__version__', '__author__',
'__email__', '__license__', '__copyright__',
]
__title__ = 'fuse'
__summary__ = ("Composes boilerplates")
__uri__ = 'https://github.com/aholmback/fuse'
__version__ = '0.0.2.alpha.18'
__author__ = "... | una Developers"
__email__ = 'people@creuna.se'
__license__ = 'MIT'
__copyright__ = "Copyright 2017 {0}".format(__author__)
|
adrn/gala | gala/potential/scf/tests/test_class.py | Python | mit | 3,357 | 0.000298 | # coding: utf-8
# Third-party
import astropy.units as u
from astropy.constants import G as _G
import numpy as np
import pytest
# Project
from gala._cconfig import GSL_ENABLED
from gala.units import galactic
import gala.potential as gp
from gala.potential.potential.tests.helpers import PotentialTestBase
from gala.pote... | cos_coeff[0, 0, 0] = 1.
scf_potential = _bfe_class.SCFPotential(m=M, r_s=r_s,
S | nlm=cos_coeff, Tnlm=sin_coeff,
units=galactic)
# scf_potential = HackPotential(m=10., units=galactic)
nbins = 128
rr = np.linspace(0.1, 10., nbins)
xyz = np.zeros((3, nbins))
xyz[0] = rr * np.cos(np.pi/4.) * np.sin(np.pi/4.)
xyz[1] = rr * np.sin(np.pi... |
NB-Dev/django-shop | shop/addressmodel/models.py | Python | bsd-3-clause | 2,375 | 0.001684 | # -*- coding: utf-8 -*-
"""
Holds all the information relevant to the client (addresses for instance)
"""
from django.conf import settings
from django.db import models
from dja | ngo.utils.translation import ugettext_lazy as _
from django.conf import settings
BASE_ADDRESS_TEMPLATE = \
_("""
Name: %(name)s,
Address: %(address)s,
Zip-Code: %(zipcode)s,
City: %(city)s,
State: %(state)s,
Country: %(country)s
| """)
ADDRESS_TEMPLATE = getattr(settings, 'SHOP_ADDRESS_TEMPLATE',
BASE_ADDRESS_TEMPLATE)
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class Country(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return u'%s' % self.name
... |
creffett/reffipe | reffipe/website/models.py | Python | gpl-3.0 | 1,104 | 0 | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.F... | ipe')
quantity = models.FloatField()
unit = models.CharField(choices=MEASUREMENT, max_length=10)
description = models.CharField(max_length=100)
notes = models.TextField()
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
clas... | Field(max_length=100)
def __str__(self):
return self.name
|
whbruce/upm | examples/python/t8100.py | Python | mit | 3,663 | 0.001638 | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# 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 l... | ## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
| print("Exiting...")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# You will need to edit this example to conform to your site and your
# devices, specifically the Device Object Instance ID passed to the
# constructor, an... |
iAddz/allianceauth | eveonline/migrations/0006_allow_null_evecharacter_alliance.py | Python | gpl-2.0 | 719 | 0.002782 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-02 19:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
depe | ndencies = [
('eveonline', '0005_remove_eveallianceinfo_member_count'),
]
operations = [
migrations.AlterField(
model_name='evecharacter',
name='alliance_id',
field=models.CharField(blank=True, default='', max_length=254, null=True),
),
migrat... | null=True),
),
]
|
zhuzhezhe/weibobash | weibo_bash/weibo_bash.py | Python | mit | 2,831 | 0.001602 | #!/usr/bin/env python3
#coding:utf-8
__author__ = 'zhuzhezhe'
'''
功能实现:命令行下发布微博,获取最新微博
'''
from weibo import Client
import getopt
import sys
import configparser
versions = '0.1.5'
# 写入用户数据
def write_data(uname, pwd):
conf = configparser.ConfigParser()
conf['LOGIN'] = {}
conf['LOGIN']['username'] = uname... |
try:
opts, args = getopt.getopt(sys.argv[1:], "hna:vu", ["help", "new", "add=", "user"])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == "-v":
print(versions)
elif o in ("-h", "--help"):
usage()
s... | o in ("-u", "--user"):
user = input("请输入用户名:")
pwd = input("请输入密码:")
write_data(user, pwd)
else:
assert False, "unhandled option"
if __name__ == "__main__":
main()
|
eldarion/pycon | pycon/profile/views.py | Python | bsd-3-clause | 1,142 | 0.004378 | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Profile
from .forms import ProfileForm
@login_required
def pr | ofile_edit(request):
next = request.GET.get("next")
profile, cre | ated = Profile.objects.get_or_create(
user=request.user,
defaults={
"first_name": request.user.first_name,
"last_name": request.user.last_name,
}
)
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_vali... |
kfirprods/tpp | python/hg-rheads.py | Python | gpl-3.0 | 482 | 0.008299 | import sys
from mercurial import hg, node, ui
def main():
"""print (possibly remote) heads
Prints a series of lines consisting of hashes and branch names.
Specify a local or remote repository, defaulting to the configured remote.
"""
repo = sys.argv[1]
other = hg.peer(ui.ui(), {}, re... | e__ == "__main__":
main()
| |
openaid-IATI/deprecated-version-OIPA-v2 | iati/data/migrations/0009_auto__add_countrystatistics.py | Python | agpl-3.0 | 18,746 | 0.007042 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CountryStatistics'
db.create_table('data_countrystatistics', (
('id', self.gf('d... | ], {'max_length': '3', 'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['data.Country']", 'null': 'True', 'blank': 'True'})
},
'data.financetype': {
'Meta': {'object_name': 'FinanceType'},
'code': ('django.db.models.f... | e': {
'Meta': {'object_name': 'FlowType'},
'code': ('django.db.models.fields.IntegerField', [], {'max_length': '5', 'primary_key': 'True'})
},
'data.iatiactivity': {
'Meta': {'object_name': 'IATIActivity'},
'activity_status': ('django.db.models.fields.rela... |
sloria/sepal | sepal/datasets/admin.py | Python | bsd-3-clause | 1,904 | 0.003676 | from sepal.datasets.models import *
from django.contrib import admin
class InstanceInline(admin.TabularInline):
model = Instance
extra = 1
class FeatureValueInline(admin.TabularInline):
model = FeatureValue
extra = 1
class LabelValueInline(admin.TabularInline):
model = LabelValue
extra = 3
c... | model = Dataset
class DatasetAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name', 'description', 'species', ]}),
('Date information', {'fields': ['created_at'], 'classes': ['collapse']})
]
list_display = ('name', 'created_at', 'description', 'pk')
inlines = [InstanceInl... | (None, {'fields': ['dataset', 'audio']}),
]
list_display = ('dataset', 'pk', 'audio')
inlines = [FeatureValueInline]
class AudioAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['audio_file', 'slug', ]}),
]
list_display = ('audio_file', 'slug',)
class FeatureAdmin(admin... |
mattaustin/django-thummer | thummer/migrations/0001_initial.py | Python | apache-2.0 | 1,008 | 0.003968 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import sorl.thumbnail.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='WebpageSnapshot',
fields=[
... | ail.fields.ImageField(upload_to='thummer/snapshots', null=True, editable=False)),
('capture_width', models.IntegerField(default=1680, editable=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('captured_at', models.DateTimeField(null=True, editable=False)... | ured_at'],
'get_latest_by': 'captured_at',
},
),
]
|
Azure/WALinuxAgent | dcr/scenarios/agent-persist-firewall/run2.py | Python | apache-2.0 | 2,711 | 0.005164 | from dcr.scenario_utils.common_utils import get_current_agent_name
from dcr.scenario_utils.test_orchestrator import TestFuncObj, TestOrchestrator
from persist_firewall_helpers import verify_wire_ip_in_iptables, verify_system_rebooted, generate_svg, \
verify_wire_ip_unreachable_for_non_root, verify_wire_ip_reachable... | enerate SVG", lambda: generate_svg(svg_name="agent_running.svg")),
TestFuncObj("Verify wireIP unreachable for non-root", verify_wire_ip_unreachable_for_non_root),
TestFuncObj("Verify wireIP reachable for root", verify_wire_ | ip_reachable_for_root),
TestFuncObj("Verify_Wire_IP_IPTables", lambda: verify_wire_ip_in_iptables(max_retry=1)),
TestFuncObj("Verify External services", check_external_service_status)
]
test_orchestrator = TestOrchestrator("PersistFirewall-VM2", tests=tests)
test_orchestrator.run_tests()
... |
JackDanger/sentry | src/sentry/interfaces/template.py | Python | bsd-3-clause | 3,261 | 0 | """
sentry.interfaces.template
~~~~~~~~~~~~~~~~~~~~~~~~~~
: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__ = ('Template',)
from sentry.interfaces.base import Interface, InterfaceValidationError
... | ontext])
return '\n'.join(result)
def get_api_context(self, is_public=False):
| return {
'lineNo': self.lineno,
'filename': self.filename,
'context': get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
... |
theelectricbrain/Drones-Drifters | drones_n_drifters/georef/geo_referencing.py | Python | agpl-3.0 | 4,964 | 0.004633 | #!/usr/bin/python2.7
# encoding: utf-8
from __future__ import division
import numpy as np
# from pyproj import Proj, pj_list, pj_ellps
import cv2
def geo_ref_tracks(tracks, frame, uav, debug=False):
"""
Geo-references tracks'points
:param tracks: list of drifters' trajectories
:param frame: CV2 frame... | yr = y*np.cos(yaw) - x*np.sin(yaw)
TR.append([xr, yr])
# Conversion deg. to m. / Version 2.0
y2lat = 1.0 / (110.54 * 1000.0)
x2lon = 1.0 / (111.320 * 1000.0 * np.cos(np.deg2rad(uav.centreCoordinates[1])))
lonC, latC = uav.centreCoordinates[0], uav.centreCoordinates[1]
for tr, trM in z... | cksInRelativeM):
for ptM in trM:
lon, lat = lonC + (ptM[0] * x2lon), latC + (ptM[1] * y2lat)
tr.append([lon, lat])
# Conversion deg. to m. / version 1.0
# proj = raw_input("Use default projection UTM/WGS84 (yes/no)?: ").upper()
# if proj in "YES":
# myproj = Proj(pr... |
khshim/lemontree | lemontree/__init__.py | Python | mit | 117 | 0.017094 | "" | "
LemonTree is simple, flexible, and experimental deep learning package based on Theano.
"""
__version__ = '0.0 | .4' |
dbiesecke/plugin.video.xstream | sites/kinox_to.py | Python | gpl-3.0 | 34,288 | 0.011549 | # -*- coding: utf-8 -*-
import urllib
import logger
from resources.lib.gui.gui import cGui
from resources.lib.gui.guiElement import cGuiElement
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
from resources.lib.util import cUtil
from resources.lib.config import ... | URL_LANGUAGE = URL_MAIN + '/aSET/PageLang/1'
def load():
logger.info("Load %s" % SITE_NAME)
| sSecurityValue = __getSecurityCookieValue()
if sSecurityValue == '':
pass
elif sSecurityValue == False:
return
oParams = ParameterHandler()
oParams.setParam('securityCookie', sSecurityValue)
## Create all main menu entries
oGui = cGui()
oParams.setParam('sUrl', URL_MAI... |
ufo22940268/my-tours | content/prog/tour/list_comprehension.py | Python | bsd-3-clause | 128 | 0.03125 | squares | = [x**2 for x in range(10)]
print squares
couples = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print couples | |
wileeam/airflow | airflow/security/utils.py | Python | apache-2.0 | 2,840 | 0.000352 | #!/usr/bin/env python
# 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
# "Li... | ostname_pattern(components, host=None):
"""Replaces hostname with the right pattern including lowercase of the name."""
fqdn = host
if not fqdn or fqdn == '0.0.0.0':
fqdn = get_hostname()
return '%s/%s@%s' % (components[0], fqdn.lower(), components[2])
def get_fqdn(hostname_or_ip=None):
""... | fqdn = socket.gethostbyaddr(hostname_or_ip)[0]
if fqdn == 'localhost':
fqdn = get_hostname()
else:
fqdn = get_hostname()
except OSError:
fqdn = hostname_or_ip
return fqdn
def principal_from_username(username, realm):
"""Retrieves principal ... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/ubuntuone-client/ubuntuone/platform/windows/ipc_client.py | Python | gpl-3.0 | 23,763 | 0.00021 | # -*- coding: utf-8 -*-
#
# Authors: Manuel de la Pena <manuel@canonical.com>
# Alejandro J. Cura <alecu@canonical.com>
#
# Copyright 2011 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by ... | """
def __init__(self, cb):
"""Create a new instance."""
self.cb = cb
def remote_execute(self):
"""Execute the callback."""
if self.cb:
self.cb()
def callbacks(callbacks_indexes=None, callbacks_names=None):
" | ""Ensure that the callbacks can be remotely called."""
def decorator(function):
"""Decorate the function to make sure the callbacks can be executed."""
@wraps(function)
def callbacks_wrapper(*args, **kwargs):
"""Set the paths to be absolute."""
fixed_args = list(args)... |
concordusapps/alchemist | alchemist/db/operations/shell.py | Python | mit | 1,145 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
from .. import engine
import os
def shell(database='default'):
"""Runs the command-line client for the specified database.
"""
target = engine[database]
dialect = engine[database].dialect.name
if dialect =... | arget.url.password]
if 'unix_socket' in target.url.query:
args += ["--socket=%s" % target.url.query['unix_socket']]
elif target.url.host:
args += ["--host=%s" % target.url.host]
if target.url.port:
| args += ["--port=%s" % target.url.port]
if target.url.database:
args += [target.url.database]
elif dialect == 'sqlite':
args = ['sqlite3', target.url.database]
else: # pragma: nocoverage
raise RuntimeError(
'Database shell not available for the ... |
mchristopher/PokemonGo-DesktopMap | app/pylibs/win32/Cryptodome/Hash/keccak.py | Python | mit | 8,329 | 0.001201 | # ===================================================================
#
# Copyright (c) 2015, Legrandin <helderijs@gmail.com>
# 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. Redi... | bits", None)
if None not in (digest_bytes, digest_bits):
raise TypeError("Only one digest parameter must be provided")
if (None, None) == (digest_bytes, digest_bits):
raise TypeError("Digest size (bits, bytes) not provided")
if digest_bytes is not None:
if digest_bytes not in (... | not in (224, 256, 384, 512):
raise ValueError("'digest_bytes' must be: 224, 256, 384 or 512")
digest_bytes = digest_bits // 8
|
jaidevd/scikit-learn | sklearn/neighbors/base.py | Python | bsd-3-clause | 30,649 | 0 | """Base and mixin classes for nearest neighbors"""
# Authors: Jake Vanderplas <vanderplas@astro.washington.edu>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Sparseness support by Lars Buitinck
# Multi-output support by Arnaud Jol... | s import check_classification_targets
from ..externals import six
from ..externals.joblib import Parallel, delayed
from ..exceptions import NotFittedError
from ..exce | ptions import DataConversionWarning
VALID_METRICS = dict(ball_tree=BallTree.valid_metrics,
kd_tree=KDTree.valid_metrics,
# The following list comes from the
# sklearn.metrics.pairwise doc string
brute=(list(PAIRWISE_DISTANCE_FUNCTIONS.... |
YuhanLin1105/Multi-User-Blog | utils/helper_cookie.py | Python | mit | 368 | 0 | import hmac
class Helper_cookie:
secret = 'This is a secret'
| @classmethod
def make_secure_val(self, val):
return '%s|%s' % (val, hmac.new(self.secret, val).hexdigest())
@classmethod
def check_secure_val(self, secure_val):
val = secure_val.split('|')[0]
if secure_val == se | lf.make_secure_val(val):
return val
|
chrischambers/django-calendartools | test_project/event/tests/test_managers.py | Python | bsd-3-clause | 8,416 | 0.001188 | from datetime import datetime, timedelta
from django.test import TestCase
from django.contrib.auth.models import User
from nose.tools import *
from event.models import Calendar, Event, Occurrence, Attendance
class TestCommonManager(TestCase):
def setUp(self):
self.user = User.objects.create(username='Test... | nt(self):
self.event.status = Eve | nt.STATUS.hidden
self.event.save()
assert_equal(
set(Occurrence.objects.visible()),
set(Occurrence.objects.none())
)
assert_equal(
set(Occurrence.objects.visible(self.user)),
set(Occurrence.objects.none())
)
self.user.is_sta... |
huggingface/transformers | src/transformers/data/data_collator.py | Python | apache-2.0 | 76,850 | 0.004608 | # Copyright 2020 The HuggingFace Team. 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 applicabl... | batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
elif "label_ids" in first and first["label_ids"] is not None:
if isinstance(first["label_ids"], torch.Tensor):
| batch["labels"] = torch.stack([f["label_ids"] for f in features])
else:
dtype = torch.long if type(first["label_ids"][0]) is int else torch.float
batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype)
# Handling of all other possible keys.
# Aga... |
uehara1414/serverctl-prototype | serverctl_prototype/settings.py | Python | mit | 3,666 | 0.001091 | """
Django settings for serverctl_prototype project.
Generated by 'django-admin startproject' using Django 1.10.6.
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/
""... |
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': 'postgres',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttri... | ib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.... |
GrimRanger/GeneticAlgorithm | GeneticLib/genetic_engine.py | Python | mit | 512 | 0.011719 |
class GeneticEngine:
genomLength = 10
generationCount = 10
individualCount = 10
selectionType = 10
crossingType = 10
useMutation = 1
mutationPercent = 50
"""constructor"""
def __init__(self, fitnessFunction):
return 0
"""main body"""
def run():
ret... |
def selection():
return 0
def crossing( | ):
return 0
def mutation():
return 0
|
nicproulx/mne-python | mne/viz/tests/test_raw.py | Python | bsd-3-clause | 11,805 | 0.000085 | # Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: Simplified BSD
import numpy as np
import os.path as op
import warnings
from numpy.testing import assert_raises, assert_equal
from mne import read_events, pick_types, Annotations
from mne.io import read_raw_fif
from mne.utils import requires_version, run_t... | kind='release')
plt.close('all')
# test if meas_date has only one element
raw.info['meas_date'] = np.array([raw.info['meas_date'][0]],
dtype=np.int32)
raw.annotations = Annotations([1 + raw.first_samp / raw.info['sfreq']... | [5], ['bad'])
raw.plot()
plt.close('all')
def test_plot_annotations():
"""Test annotation mode of the plotter."""
raw = _get_raw()
_annotation_helper(raw)
raw.annotations = Annotations([42], [1], 'test' |
aaibfer/mtoaUtils | scripts/aiDistanceLocator.py | Python | mit | 13,950 | 0.041864 | """
aiDistanceLocator v1.0.2
----------------------------------------------------------------------------------------------------
- create a locator as a reference to adjust camera's focus distance or light attenuation parameters
--------------------------------------------------------------------------------------... | ghtDecay")
cmds.select(lgt)
# constrain group's position and rotation to light's
cmds.parentConstraint(l, "grp_" + l + "_lightDecay", name = "grp_" + l + "_lightDecay" + "_parentConstraint", maintainOffset = False, decompRotationToChild = False, skipTranslate = "none", skipRotate = "none")
... | cmds.expression(string = "lct_" + l + "_nearStart.translateZ = -(" + f + ".nearStart)", name = "expression_" + l + "_nearStart")
cmds.expression(string = "lct_" + l + "_nearEnd.translateZ = -(" + f + ".nearEnd)", name = "expression_" + l + "_nearEnd")
cmds.expression(string = "lct_" + l + "_farS... |
sergey-senozhatsky/anaconda-11-vlan-support | iw/bootloader_advanced_gui.py | Python | gpl-2.0 | 3,639 | 0.007969 | #
# bootloader_advanced.py: gui advanced bootloader configuration dialog
#
# Jeremy Katz <katzj@redhat.com>
#
# Copyright 2001-2002 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# alo... | getNext(self):
# forcing lba32 can be a bad idea.. make sure they really want to
if (self.forceLBA.get_active() and not self.bl.forceLBA32):
rc = self.intf.messageWindow(_("Warning"),
_("Forcing the use of LBA32 for your bootloader when "
"not suppo... | type = "custom",
custom_buttons = [_("Cancel"),
_("Force LBA32")])
if rc != 1:
raise gui.StayOnScreen
# set forcelba
self.bl.setForceLBA(self.forceLBA.get_ac... |
alinasirbu/eurora_job_power_prediction | Python_scripts_regression/one_user_apply.py | Python | gpl-2.0 | 6,590 | 0.044613 | ##this script applies component models to the data of the selected month
#component predictions are summed to obtain global prediction
##where the component model does not exist (because data is too little), averages are used in the spitrit of the EAM
import csv
import gzip
import datetime
import numpy as np
import ma... | _power)**2))
nrmse=math.sqrt(np.average(((prediction-test_power)/test_power)**2))
corr=np.corrcoef(prediction,test_power)[0,1]
r2=1-(sum((prediction-test_power)**2)/sum((test_power-np.average(test_power))**2))
pl.figure(figsize=(6,7))
pl.subplot(211)
pl.plot(prediction*max_power,test_power*max_p... | )
else:
pl.title("RMSPE="+str(int(nrmse*1000)/1000.0)+" RMSE="+str(int(rmse*1000)/1000.0)+" Corr="+str(int(corr*1000)/1000.0)+" R2="+str(int(r2*1000)/1000.0))
pl.xlabel('Predicted power')
pl.ylabel('Real power')
pl.plot([max(pl.xlim()[0],pl.ylim()[0]),min(pl.xlim()[1],pl.ylim()[1])],[max(pl.xlim... |
keras-team/keras | keras/optimizers/optimizer_v2/nadam_test.py | Python | apache-2.0 | 6,798 | 0.006325 | # Copyright 2015 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... | m_cache_t
def nadam_update_numpy(param,
g_t,
t,
m,
v,
m_cache,
alpha=0 | .001,
beta1=0.9,
beta2=0.999,
epsilon=1e-8):
mu_t = beta1 * (1 - 0.5 * 0.96**(0.004 * (t + 1)))
mu_t_1 = beta1 * (1 - 0.5 * 0.96**(0.004 * (t + 2)))
m_cache_t_1 = m_cache * mu_t_1
g_prime_t = g_t / (1 - m_cache)
m_t = beta1 * m + (1 - beta1... |
google/grumpy | compiler/block.py | Python | apache-2.0 | 12,060 | 0.009227 | # coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of t | he License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific langu... | se.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pyt... |
alexmgr/scapy-ssl_tls | src/examples/example_full_handshake_rsa_aes_sha.py | Python | gpl-2.0 | 5,347 | 0.019637 | #! /usr/bin/env python
# -*- coding: UTF-8 -*-
# Author : tintinweb@oststrom.com <github.com/tintinweb>
def sendrcv(sock, p, bufflen=1024):
sock.settimeout(5)
print "sending TLS payload"
sock.sendall(p)
resp=''
try:
while 1:
t = sock.recv(1)
if not(len(... | lo[TLSServerHello].gmt_unix_time)+server_hello[TLSServerHello].random_bytes)
print "master", repr(secparams.master_secret)
|
# encrypt pms with server pubkey from first cert
#extract server cert (first one counts)
cert = SSL(r)[TLSCertificateList].certificates[0].data
pubkey = ssl_tls_crypto.x509_extract_pubkey_from_der(cert)
print repr(pubkey.exportKey(format="DER"))
#print pubkey
print... |
staranjeet/fjord | fjord/alerts/api_views.py | Python | bsd-3-clause | 6,843 | 0 | from rest_framework import exceptions
from rest_framework import permissions
from rest_framework import serializers
import rest_framework.response
import rest_framework.views
from fjord.alerts.models import Alert, AlertFlavor, AlertSerializer, Link
from fjord.api_auth.api_utils import TokenAuthentication
from fjord.ba... |
permission_classes = (FlavorPermission,)
def get(self, request):
serializer = AlertsGETSerializer(data=request.GET)
if not | serializer.is_valid():
raise exceptions.ValidationError({'detail': serializer.errors})
data = serializer.validated_data
max_count = min(data['max'], 10000)
flavors = data['flavors']
# Make sure the token has permission to view each flavor.
for flavor in flavors:
... |
varunkumta/azure-linux-extensions | VMBackup/main/PluginHost.py | Python | apache-2.0 | 11,336 | 0.010586 | import time
import sys
import os
import threading
import ConfigParser
from common import CommonVariables
from pwd import getpwuid
from stat import *
import traceback
# [pre_post]
# "timeout" : (in seconds),
#
# .... other params ...
#
# "pluginName0" : "oracle_plugin", the python plugin f... | not root', True, 'Error' | )
errorCode = CommonVariables.FailedPrepostPluginhostConfigPermissionError
else :
errorCode,dobackup,fsFreeze_on = self.load_modules()
return errorCode,dobackup,fsFreeze_on
def load_modules(self):
# Imports all plugin modules using the information in config.jso... |
Odingod/mne-python | examples/stats/plot_cluster_stats_spatio_temporal_2samp.py | Python | bsd-3-clause | 4,284 | 0 | """
========================================================= | ================
2 samples permutation test on source data with spatio-temporal clustering
=========================================================================
Tests if the source space data are significantly different between
2 groups of subjects (simulated here using one subject's data).
The multiple comparison... | th a cluster-level
permutation test across space and time.
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from scipy import stats as stats
import mne
from mne import spatial... |
tijoytom/coreclr | src/ToolBox/SOS/tests/t_cmd_dumpmodule.py | Python | mit | 1,304 | 0.000767 | import lldb
import re |
import | testutils as test
def runScenario(assembly, debugger, target):
process = target.GetProcess()
res = lldb.SBCommandReturnObject()
ci = debugger.GetCommandInterpreter()
# Run debugger, wait until libcoreclr is loaded,
# set breakpoint at Test.Main and stop there
test.stop_in_main(debugger, asse... |
ChristinaHammer/Client_Database | cdbgui.py | Python | mit | 60,561 | 0.01856 | """cdbgui.py
Developers: Christina Hammer, Noelle Todd
Last Updated: August 19, 2014
This file contains a class version of the interface, in an effort to
make a program with no global variables.
"""
from datetime import datetime, timedelta, date
from tkinter import *
from tkinter import ttk
from cdbifunc2 import *
i... | _listbox.config(exportselection=0)
self.scrollb = Scrollbar(self.gridframe)
self.client_listbox.bind('<<ListboxSelect>>',self.displayInfo )
self.client_listbox.config(yscrollcommand=self.scrollb.set)
self.scrollb.config(command=self.client_listbox.yview)
self.client_lis... | S)
self.firstSep = ttk.Separator(self.gridframe, orient='vertical')\
.grid(row=1,column=2,rowspan=40,sticky=NS)
self.NCButton = Button(self.gridframe, text='New Client',
command=self.newClientDisplay, width=25)\
.g... |
eos87/Booktype | lib/booktype/apps/core/admin.py | Python | agpl-3.0 | 217 | 0 | from django.contrib import admin
from .models import Permission, Role, BookRole, BookSkeleton
admin.site.register | (Permission)
admin | .site.register(Role)
admin.site.register(BookRole)
admin.site.register(BookSkeleton)
|
kdopen/pep8-naming | run_tests.py | Python | mit | 1,995 | 0.002005 | import sys
import os
import pep8ext_naming
import re
PyCF_ONLY_AST = 1024
IS_PY3 = sys.version_info[0] == 3
IS_PY3_TEST = re.compile("^#\s*python3\s*only")
IS_PY2_TEST = re.compile("^#\s*python2\s*only")
def main():
print('Running pep8-naming tests')
test_count = 0
errors = 0
for filename in os.list... | h.join('testsuite', filename)) as fd:
lines = list(fd)
if not is_test_allowed(lines):
continue
for testcase, codes in load_tests(lines):
| test_count += 1
errors += test_file(filename, testcase, codes)
if errors == 0:
print("%s tests run successful" % test_count)
sys.exit(0)
else:
print("%i of %i tests failed" % (errors, test_count))
sys.exit(1)
def is_test_allowed(lines):
if IS_PY3 and any(I... |
legionus/billing | lib/bc/sockets.py | Python | gpl-3.0 | 4,022 | 0.037046 | #!/usr/bin/env python
#
# sockets.py
#
# Copyright (c) 2012-2013 by Alexey Gladkov
# Copyright (c) 2012-2013 by Nikolay Ivanov
#
# This file is covered by the GNU General Public License,
# which should be included with billing as the file COPYING.
#
import socket as pysocket
import threading, time, struct, errno, logg... | mily=pysocket.AF_INET, typ=pysocket.SOCK_STREAM, proto=0):
self.sock = socket or pysocket.socket(family, typ, proto)
for n in [ 'setsockopt', 'accept', 'bind', 'connect', 'listen' ]:
self.__dict__[n] = getattr(self.sock, n)
self.rd_lock = threading.Lock()
self.wr_lock = threading.Lock()
def __recv_failu... | ck.recv(bytes)
if not buf: break
bytes -= len(buf)
res.append(buf)
except pysocket.error, e:
if e.errno != errno.EINTR:
raise e
return ''.join(res)
def recv(self, bytes):
try:
self.rd_lock.acquire()
return self.__recv_failure_retry(bytes)
finally:
self.rd_lock.release()
ret... |
chrisbrake/PythonSandbox | toDo/app.py | Python | bsd-3-clause | 195 | 0 | import | responder
api = responder.API()
@api.route("/{greeting}")
async def greet_world(req, resp, *, greeting):
resp.text = f"{greeting}, world!"
if __name__ == '__m | ain__':
api.run()
|
fastly/ftw | test/integration/test_htmlcontains.py | Python | apache-2.0 | 1,658 | 0.016285 | from ftw import ruleset, testrunner, http, errors
import pytest
import re
import random
import threading
def test_logcontains(ruleset, test):
runner = testrunner.TestRunner()
for stage in test.stages:
runner.run_stage(stage)
# Should return a test error because its searching before response
def test_s... | with pytest.raises(AssertionError):
runner.test_response(http_ua.response_object,re.compile('dog'))
# Should return a success because it is searching for a word not there
def test_search3():
runner = testrunner.TestRunner()
x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"})
... | d for'))
# Should return a success because we found our regex
def test_search4():
runner = testrunner.TestRunner()
x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"})
http_ua = http.HttpUA()
http_ua.send_request(x)
runner.test_response(http_ua.response_object,re.compi... |
stvstnfrd/edx-platform | openedx/core/djangoapps/credentials/signals.py | Python | agpl-3.0 | 6,532 | 0.003368 | """
This file contains signal handlers for credentials-related functionality.
"""
from logging import getLogger
from django.contrib.sites.models import Site
from common.djangoapps.course_modes.models import CourseMode
from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate
from lms.... | grade.pe | rcent
send_grade_to_credentials.delay(user.username, str(course_run_key), True, letter_grade, percent_grade)
def handle_grade_change(user, course_grade, course_key, **kwargs):
"""
Notifies the Credentials IDA about certain grades it needs for its records, when a grade changes.
"""
send_grade_if_i... |
bigblindbais/pytk | src/pytk/factory/factory.py | Python | mit | 1,952 | 0.000512 | value_None = object()
class FactoryException(Exception):
pass
class Factory:
class Item:
def __init__(self, factory, i):
self.factory = factory
self.i = i
@property
def value(self):
return self.factory.value(se | lf.i)
@value.setter
def value(self, value):
self.i = self.factory.i(value)
def copy(self):
return self.factory.item(self.i)
def __eq__(self, other):
try:
return self.factory is other.factory and self.i == other.i
except A... | ther
def __hash__(self):
return hash(self.factory) ^ hash(self.i)
def __int__(self):
return self.i
def __str__(self):
return self.factory.istr(self)
def __repr__(self):
return f'Item({self.factory.istr(self)})'
@staticmethod
de... |
ekozlowski/ansible-minecraft | fabfile.py | Python | mit | 717 | 0.015342 | from fabric import api as fab
from contextlib import contextmanager
@contextmanager
def with_vagrant():
with fab.settings(user="vagrant",host_string="127.0.0.1:2222",key_filename=".vagrant | /machines/minecraft/virtualbox/private_key"):
yield
def ping(ip):
with with_vagrant():
return fab.run('ping -c 4 {}'.format(ip))
def save():
with with_vagrant():
fab.sudo('/etc/init.d/minecraft backup')
fab.get(remote_path='/srv/minecraft-server/backups/*', local_path="/Users/e... | x/minecraft_backups")
def restore():
with with_vagrant():
fab.put(remote_path='/srv/minecraft-server/backups/', local_path="/Users/e003070/Dropbox/minecraft_backups")
|
Infinidat/lanister | flask_app/auth.py | Python | bsd-3-clause | 172 | 0 | from flask.ext.security import SQLAlchemyUserDatastore
from .models import Role, User, | db
# Setup Flask-Security
user_datastore = SQLAlchemyUs | erDatastore(db, User, Role)
|
carlesm/ambrosio | ambrosio/actions/__init__.py | Python | gpl-3.0 | 202 | 0 |
from Action impo | rt Action
from MusicPlayer import MusicPlayer
from SensorAction import SensorAction
from WakeAction import WakeAction
__all__ = ["Action", "MusicPlayer", "SensorAction", "WakeActio | n"]
|
SymbiFlow/icestorm | icebox/icebox_html.py | Python | isc | 26,039 | 0.004839 | #!/usr/bin/env python3
#
# Copyright (C) 2015 Clifford Wolf <clifford@clifford.at>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTW... | print("""<p>This documentation is auto-generated by <tt>icebox_html.py</tt> from IceBox.<br/>
A machine-readable form of the database can be downloaded <a href="%s">here</a>.</p>""" % chipdbfile)
print("""<p>The iCE40 FPGA fabric is organized into tiles. The configuration bits
themselves have the same meaning in a... | the left border and an IO tile on
the top border.</p>""")
print("""<p>Click on a highlighted tile below to view the bitstream details for the
tile. The highlighted tiles cover all combinations of neighbouring cells that can be found
in iCE40 FPGAs.</p>""")
print('<p><table border="1">')
for y in range(ic.... |
RedhawkSDR/integration-gnuhawk | components/sub_ff_3i/tests/test_sub_ff_3i.py | Python | gpl-3.0 | 4,061 | 0.006895 | #!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by ... | ))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be ca... | omp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluef... |
nearlyfreeapps/python-googleadwords | examples/adspygoogle/adwords/v201109/basic_operations/update_campaign.py | Python | apache-2.0 | 1,970 | 0.007614 | #!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ssions and
# limitations under the License.
"""This example updates budget delivery method for a given campaign. To get
campaigns, run get_campaigns.py.
Tags: CampaignService.mutate
"""
__author__ = 'api.kwinter@gmail | .com (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import AdWordsClient
campaign_id = 'INSERT_CAMPAIGN_ID_HERE'
def main(client, campaign_id):
# Initialize appropriate service.
campaign... |
scollis/iris | lib/iris/tests/unit/fileformats/pp/test_save.py | Python | gpl-3.0 | 4,803 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | field):
target_filelike = mock.Mock(name='target')
target_filelike.mode = ('b')
pp.save(cube, target_filelike)
# Return pp-field mock with a | ll the written properties
return pp_field
class TestLbfcProduction(tests.IrisTest):
def setUp(self):
self.cube = stock.lat_lon_cube()
def check_cube_stash_yields_lbfc(self, stash, lbfc_expected):
if stash:
self.cube.attributes['STASH'] = stash
lbfc_produced = _pp_save_... |
googleapis/python-network-security | google/cloud/network_security_v1beta1/types/client_tls_policy.py | Python | apache-2.0 | 8,077 | 0.001238 | # -*- 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... | by the ListClientTlsPolicies method.
Attributes:
parent (str):
Required. The project and location from which the
ClientTlsPolicies should be listed, specified in the format
``projects/*/locations/{location}``.
page_size (int):
| Maximum number of ClientTlsPolicies to return
per call.
page_token (str):
The value returned by the last
``ListClientTlsPoliciesResponse`` Indicates that this is a
continuation of a prior ``ListClientTlsPolicies`` call, and
that the system sh... |
hehongliang/tensorflow | tensorflow/python/util/tf_should_use_test.py | Python | apache-2.0 | 4,460 | 0.007399 | # Copyright 2017 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... | atal.call_args[0])
self.assertIn('Object was never used', msg)
self.assertIn('blah0:0', msg)
self.assertIn('in_this_function', msg)
self.assertFalse(gc.garbage)
def _testAddShouldUseWarningWhenUsed(self, fn, name):
c = constant_op.constant(0, name=name)
with reroute_error() as (error, fatal):... | del h
error.assert_not_called()
fatal.assert_not_called()
def testAddShouldUseWarningWhenUsedWithAdd(self):
def add(h):
_ = h + 1
self._testAddShouldUseWarningWhenUsed(add, name='blah_add')
gc.collect()
self.assertFalse(gc.garbage)
def testAddShouldUseWarningWhenUsedWithGetName(self)... |
phantomii/restalchemy | restalchemy/tests/functional/restapi/ra_based/test_resources.py | Python | apache-2.0 | 13,940 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2016 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... | insert_vm_to_db(uui | d=RESOURCE_ID2, name="test2", state="on")
vm_response_body = [{
"uuid": str(RESOURCE_ID1),
"name": "test1",
"state": "off"
}, {
"uuid": str(RESOURCE_ID2),
"name": "test2",
"state": "on"
}]
response = requests.get(se... |
delphcf/sis | sis/contacts/migrations/0009_auto_20150205_1942.py | Python | bsd-3-clause | 1,435 | 0.002091 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contacts', '0008_auto_20150205_1853'),
]
operations = [
migrations.AlterModelOptions(
name='organizationmember',... | name='activate_date',
field=models.DateTimeField(help_text='keep empty for an i | mmediate activation', null=True, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='organizationmember',
name='deactivate_date',
field=models.DateTimeField(help_text='keep empty for indefinite activation', null=True, blank=True),
... |
Aigrefin/py3learn | learn/migrations/0002_auto_20160517_1353.py | Python | mit | 427 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-17 11:53
from __future__ import unicode_literals
f | rom django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('learn', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='languagedictionnary',
old_name='name',
new_name='language',
),
] | |
deepmind/dm_control | dm_control/mujoco/thread_safety_test.py | Python | apache-2.0 | 3,604 | 0.009156 | # Copyright 2017 The dm_control 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 i... | tring(MODEL)
# Check that frames aren't repeated - make the cartpole move.
physics.set_control([1.0])
unique_frames = set()
for _ in range(NUM_STEPS):
physics.step()
frame = physics.render(width=320, height=240, camera_id=0)
unique_frames.add(fram | e.tobytes())
self.assertLen(unique_frames, NUM_STEPS)
@decorators.run_threaded(num_threads=NUM_THREADS, calls_per_thread=5)
def test_render_multiple_physics_instances_per_thread_parallel(self):
physics1 = engine.Physics.from_xml_string(MODEL)
physics2 = engine.Physics.from_xml_string(MODEL)
for _ ... |
yukezhu/tensorflow-reinforce | run_cem_cartpole.py | Python | mit | 2,013 | 0.022851 | from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def observation_to_action(ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, thet | a, num_steps, render = False):
| total_rewards = 0
observation = env.reset()
for t in range(num_steps):
action = observation_to_action(observation, theta)
observation, reward, done, _ = env.step(action)
total_rewards += reward
if render: env.render()
if done: break
return total_rewards, t
MAX_EPISODES = 10000
MAX_STEPS ... |
DewarM/oppia | core/domain/user_jobs_continuous.py | Python | apache-2.0 | 15,896 | 0.000189 | # Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apach | e 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 ... | S OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Jobs for queries personalized to individual users."""
import ast
import logging
import math
from core import jobs
from core.domain import exp_services
from core.domain i... |
m-rossi/matplotlib2tikz | tikzplotlib/_util.py | Python | mit | 1,258 | 0.000795 | import matplotlib.transforms
import numpy
def has_legend(axes):
return axes.get_legend() is not None
def get_legend_text(obj):
"""Check if line is in legend."""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [h.get_label() for h in leg.legendHandles if h is not None]
... | .axes is not None and obj.get_transform() != obj.axes.transData:
po | ints = numpy.array([xdata, ydata]).T
transform = matplotlib.transforms.composite_transform_factory(
obj.get_transform(), obj.axes.transData.inverted()
)
return transform.transform(points).T
return xdata, ydata
|
eedf/jeito | accounting/migrations/0008_auto_20170224_1912.py | Python | mit | 631 | 0 | # -*- co | ding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-24 18:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration): |
dependencies = [
('accounting', '0007_bankstatement'),
]
operations = [
migrations.AddField(
model_name='entry',
name='scan',
field=models.FileField(blank=True, upload_to='justificatif'),
),
migrations.AlterField(
model_name=... |
skeelogy/maya-skNoiseDeformer | python/libnoise/perlin.py | Python | mit | 12,633 | 0.078287 | # Copyright (c) 2008, Casey Duncan (casey dot duncan at gmail dot com)
# see LICENSE.txt for details
"""Perlin noise -- pure python implementation"""
"""
Skeel Lee, 1 Jun 2014
-added SimplexNoise.snoise3() which calculates fBm based on SimplexNoise.noise3()
(I need the same function name, signature and behavi... | rs
_GRAD3 = ((1,1,0),(-1,1,0),(1,-1,0),(-1,-1,0),
(1,0,1),(-1,0,1),(1,0,-1),(-1,0,-1),
(0,1,1),(0,-1,1),(0,1,-1),(0,-1,-1),
(1,1,0),(0,-1,1),(-1,1,0),(0,-1,-1),
)
# 4D Gradient vectors
_GRAD4 = ((0,1,1,1), | (0,1,1,-1), (0,1,-1,1), (0,1,-1,-1),
(0,-1,1,1), (0,-1,1,-1), (0,-1,-1,1), (0,-1,-1,-1),
(1,0,1,1), (1,0,1,-1), (1,0,-1,1), (1,0,-1,-1),
(-1,0,1,1), (-1,0,1,-1), (-1,0,-1,1), (-1,0,-1,-1),
(1,1,0,1), (1,1,0,-1), (1,-1,0,1), (1,-1,0,-1),
(-1,1,0,1), (-1,1,0,-1), (-1,-1,0,1), (-1,-1,0,-1),
(1,1,1,0), (1,1,-1... |
theboocock/plinkseq_utilities | pseq_util/phenotypes_snpmax.py | Python | mit | 4,546 | 0.011219 | """
Parses Phenotype Data from SNPMAX and places the data in a format for use
in plink/seq.
Format looks something like the one shown below.
PATIENT<TAB>PHENO1<TAB>PH | ENO2<TAB>
| 1<TAB>1<TAB>RED
2<TAB>0<TAB>BLUE
"""
from phenotype import Phenotype
import argparse
import tempfile
sample_list_pheno={}
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def is_int(s):
try:
n = float(s)
if n % 1 == 0:
r... |
LogicalDash/kivy | kivy/core/camera/camera_picamera.py | Python | mit | 2,837 | 0 | '''
PiCamera Camera: Implement CameraBase with PiCamera
'''
#
# TODO: make usage of thread or multiprocess
#
__all__ = ('CameraPiCamera', )
from math import ceil
from kivy.logger import Logger
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.core.camera import CameraBase
from picame... | ))
self._copy_to_gpu()
except KeyboardInterrupt:
raise
except Exception:
Logger.exception('PiCamera: Couldn\'t get image from Camera')
def start(self):
super(CameraPiCamera, self).start()
if self._update_ev is not None:
self._update_e... | , self.fps)
def stop(self):
super(CameraPiCamera, self).stop()
if self._update_ev is not None:
self._update_ev.cancel()
self._update_ev = None
|
douze12/music-metadata-modifier | main.py | Python | gpl-2.0 | 48,079 | 0.015808 | #!/usr/bin/python3
# -*-coding:UTF-8 -*
# Needed modules : python-mutagen python-glade2
# Application to manage the metadatas information on music track files
# @author douze12
# @date 26/04/2015
import time
try:
import thread
except ImportError as e:
import _thread as thread
import os
#import pygtk
#pygtk.re... | self.stop=Tr | ue
# method called when the user click on a row in the file tree view
def onSelectRow(self, source=None, event=None):
(index,elem)=source.get_cursor()
self.builder.get_object("scrolledwindow2").set_visible(True)
if index == None:
return
... |
ju1ius/clisnips | clisnips/tui/widgets/table/__init__.py | Python | gpl-3.0 | 127 | 0 | from .column import Column
from .store import TableStore
| from .t | able import Table
__all__ = ['TableStore', 'Table', 'Column']
|
bsquidwrd/Squid-Bot | gaming/utils.py | Python | mit | 1,639 | 0.002441 | import json
import sys
from django.core import serializers
from inspect import getframeinfo, getouterframes, currentframe
DISCORD_MSG_CHAR_LIMIT = 2000
def paginate(content, *, length=DISCORD_MSG_CHAR_LIMIT, reserve=0):
"""
Split up a large string or list of strings into chunks for sending to Discord.
""... | ist = content
else:
raise ValueError("Content must be str or list, not %s" % type(content))
chunks = []
currentchunk = ''
for line in contentlist:
if len(currentchunk) + len(line) < length - reserve:
currentchunk += line + '\n'
else:
chunks.append(curren... | turn chunks
def logify_object(obj):
"""
Returns a JSON string containing usually a Queryset of items based on :attr:`obj`
"""
return json.dumps(json.loads(serializers.serialize("json", obj)), sort_keys=True, indent=4)
def logify_dict(d):
"""
Returns a JSON string containing the information w... |
kn45/LTR-DNN | train.py | Python | mit | 6,330 | 0.000316 | #!/usr/bin/env python
import dataproc
import itertools
import numpy as np
import random
import time
import sys
import tensorflow as tf
from collections import defaultdict
from ltrdnn import LTRDNN
flags = tf.flags
FLAGS = flags.FLAGS
# model related:
flags.DEFINE_integer('vocab_size', 1532783, 'vocabulary size')
fla... | vec = map(float, flds[1:])
emb[word_idx] = np.array(vec)
return np.array(emb)
def inp_fn(data):
"""Extract training data.
@data : line in training file.
@return : training data in required format
"""
def _random_choose(l): return random.sample(l, 1)[0]
sp_feed = d... | flds = inst.split('\t')
query = map(int, flds[0].split(' '))
pos_title_num = int(flds[1])
pos_titles = flds[2:2+pos_title_num]
neg_title_num = int(flds[2+pos_title_num])
neg_titles = flds[2+pos_title_num+1:]
pos_title = _random_choose(pos_titles)
pos_title = m... |
sahabi/opt | rl/keras_future.py | Python | mit | 618 | 0 | import keras
import keras.layers
import keras.models
def concatenate(x):
if hasattr(keras.layers, 'Concatenate'):
return keras.layers.Concatenate()(x)
else:
return keras.layers.merge(x, mode='concat')
def add(x):
| if hasattr(keras.layers, 'Add'):
return keras.layers.Add()(x)
else:
return keras.layers.merge(x, mode='sum')
def Model(input, output, **kwargs):
if int(keras.__version__.split('.')[0]) >= 2:
return keras.models.Model(inputs=input, outputs=output, **kwargs)
else:
return ker... | ut=input, output=output, **kwargs)
|
ebagdasa/tinycloud | setup.py | Python | bsd-3-clause | 861 | 0.012776 | from distutils.core import setup
setup(
name='TinyCloud',
version='0.4dev',
packages=['tinycloud',],
license='BSD',
long_description=open('README.md').read(),
scripts=['bin/tiny-add-node', 'bin/tiny-add-app', 'bin/tiny-delete-app', 'bin/tiny-draw', 'bin/tiny-get-apps',
'bin/tiny-ge... | [
'ansible',
'redis',
'networkx',
'scipy',
'fabric', 'knapsack'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: BSD License',
'Programm... | ux',
],
)
|
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/__init__.py | Python | unlicense | 20,811 | 0.000048 | from __future__ import unicode_literals
from .abc import ABCIE
from .abc7news import Abc7NewsIE
from .academicearth import AcademicEarthCourseIE
from .addanime import AddAnimeIE
from .adobetv import (
AdobeTVIE,
AdobeTVVideoIE,
)
from .adultswim import AdultSwimIE
from .aftenposten import AftenpostenIE
from .a... | from .franceculture import FranceCultureIE
from .franceinter import FranceInterIE
from .francetv import (
PluzzIE,
FranceTvInfoIE,
FranceTVIE,
GenerationQuoiIE,
CultureboxIE,
)
from .freesound import FreesoundIE
from .freespeech import FreespeechIE
from .freevideo import FreeVideoIE
from .funnyordie... | from .gameone import (
GameOneIE,
GameOnePlaylistIE,
)
from .gamersyde import GamersydeIE
from .gamespot import GameSpotIE
from .gamestar import GameStarIE
from .gametrailers import GametrailersIE
from .gazeta import GazetaIE
from .gdcvault import GDCVaultIE
from .generic import GenericIE
from .gfycat import Gf... |
bhargavasana/activitysim | activitysim/tests/test_mnl.py | Python | agpl-3.0 | 3,724 | 0 | # ActivitySim
# Copyright (C) 2014-2015 Synthicity, LLC
# See full license in LICENSE.txt.
import os.path
import numpy as np
import pandas as pd
import pandas.util.testing as pdt
import pytest
from ..activitysim import eval_variables
from .. import mnl
# this is lifted straight from urbansim's test_mnl.py
@pytest.... | mnl.utils_to_probs(
pd.DataFrame([[1, 2, np.inf, 3]]))
def test_make_choices_only_one():
probs = pd.DataFrame(
[[1, 0, 0], [0, 1, 0]], columns=['a', 'b', 'c'], index=['x', 'y'])
choices = mnl.make_choices(probs)
pdt.assert_series_equal(
choices,
pd.Series([0, 1], index... | , 'y']))
def test_make_choices_real_probs(random_seed, utilities):
probs = mnl.utils_to_probs(utilities)
choices = mnl.make_choices(probs)
pdt.assert_series_equal(
choices,
pd.Series([1, 2], index=[0, 1]))
@pytest.fixture(scope='module')
def interaction_choosers():
return pd.DataFra... |
rhyswhitley/spatial_plots | src/create_matplotlib_savanna_patch.py | Python | cc0-1.0 | 3,093 | 0.005496 | #!/usr/bin/env python2.7
import os
import pickle
from matplotlib.path import Path
from shapely.geometry import Polygon, MultiPolygon
import fiona
def define_clipping(_shapePath):
"""
Reads in a shapefile from some folder and creates a Matplotlib Patch artist
from which one can clip gridded data plotted o... | h], 'lat':[y_low, y_high]}
# return to user
return {'clip': clip, 'extent': extent, 'poly':vert_2Dlist}
# --------------------------------------------------------------------------------
def list_flat(List2D):
"""Flattens a 2D list"""
return [item for sublist in List2D for item in sublist]
# -------... | _codes(plen):
"""
Returns a list of matplotlib artist drawing codes based on the number of
polygon coordinates; First index is the starting point, Last index closes
the polygon, and all other indices draw the polygon (coordinates always
loop back to origin)
"""
return [Path.MOVETO] + [Path.L... |
thinkle/gourmet | gourmet/plugins/email_plugin/emailer_plugin.py | Python | gpl-2.0 | 1,934 | 0.00879 | from gi.repository import Gtk
import gourmet.gtk_extras.dialog_extras as de
from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin
from .recipe_emailer import RecipeEmailer
from gettext import gettext as _
class EmailRecipePlugin (MainPlugin, UIPlugin):
ui_string = '''
<menubar name="Rec... | itle',1)])
return recs
def email_selected (self, *args):
recs = self.get_selected_recs()
l = len(recs)
if l > 20:
if not de.getBoolean(
title=_('Email recipes'),
# only called for l>20, so fancy gettext methods
# shouldn't ... | erves me
sublabel=_('Do you really want to email all %s selected recipes?')%l,
custom_yes=_('Yes, e_mail them'),
cancel=False,
):
return
re = RecipeEmailer(recs)
re.send_email_with_attachments()
|
CCI-MOC/GUI-Backend | api/v2/serializers/post/account.py | Python | apache-2.0 | 11,411 | 0.002717 | from core.models import (
AtmosphereUser, AccountProvider, Group, Identity, Provider, Quota
)
from core.query import only_current, contains_credential
from api.v2.serializers.details.credential import CredentialSerializer
from service.driver import get_esh_driver, get_account_driver
from rtwo.exceptions import Keys... | _keys = ['key', 'secre | t', 'ex_project_name']
return required_keys
def _validate_credentials(self, provider, credentials, required_keys):
provider_type = provider.get_type_name().lower()
# NOTE: Looking to add a new provider type? validate the credentials here!
if provider_type == 'openstack':
... |
cookie-master/raspRobot | raspRobot.py | Python | gpl-2.0 | 1,012 | 0.005929 | from yapsy.PluginManager import PluginManager
from parameters import *
from raspTwitter import *
#from time import sleep
import time
def parseConfigFile(fileName):
conf = {}
f = open(fileName, 'r')
for l in f.readlines():
ls = l.split()
if ls and ('#' not in ls[0]):
conf[ls[0]]... | while True:
print(time.ctime())
param.dm = param.pi.getDirectMessages()
param.dmParsed = param.pi.parseDirectMessage | s(param.dm)
# Load the plugins from the plugin directory.
manager = PluginManager()
manager.setPluginPlaces(["plugins/enabled"])
manager.collectPlugins()
for plugin in manager.getAllPlugins():
plugin.plugin_object.start(param)
time.sleep(60)
if __name... |
mbodock/django-cepfield | cep/forms.py | Python | mit | 2,390 | 0 | # encoding: utf-8
from __future__ import unicode_literals
import requests
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import Cep
from .parser import Parser
class CepField(forms.RegexField):
SERVICE_URL = ('http:... | cep.logradouro = self.dados.get('logradouro',
self.dados.get('cliente', ''))
cep.bairro = self.dados.get('bairro', '')
cep.estado = self.dados.get('estado', '')
| cep.cidade = self.dados.get('cidade', '')
cep.complemento = self.dados.get('complemento', '')
cep.save()
return cep
def valida_correios(self, codigo):
try:
response = requests.post(
self.SERVICE_URL,
data={'relaxation': codigo},... |
TheR3ason/map-your-location-history | LatitudePlot.py | Python | apache-2.0 | 4,022 | 0.01641 | #!/usr/bin/env python
# LatitudePlot.py
# Created 30 July 2013
# Created by snowdonjames@googlemail.com
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns... | x2=(LongToX(KmlD[0][d+1],ileft,iright,im.size[0]))+xnudge
y2=(LatToY(KmlD[1][d+1],itop,ibottom,im.size[1])) | +ynudge
if(EuclidDistance(x1,y1,x2,y2) < 10000):
#setting this around 80 works okay. Attempts to remove some noise
draw.line((x1,y1, x2,y2), fill=80)
cnt+=1
if cnt % 10000 ==0:
print "Drawing point number " + str(cnt)
im.save(Output... |
apache/incubator-airflow | airflow/providers/amazon/aws/sensors/s3_key.py | Python | apache-2.0 | 8,164 | 0.001592 | #
# Licensed to the Apache Software Foundation (ASF) un | der one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
| # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT... |
JohnLunzer/flexx | flexx/app/examples/flexx_in_thread.py | Python | bsd-2-clause | 1,287 | 0.002331 | """
Example showing running Flexx' event loop in another thread.
This is not a recommended use in general.
Most parts of Flexx are not thread-save. E.g. setting properties
should generally only be done from a single thread. Event handlers
are *always* called from the same thread that runs the event loop
(unless manual... | rt() from the same
thread, or using ``new_loop=True`` (as is done here).
"""
import time
import threading
from flexx import app, event
class | MyModel1(event.HasEvents):
@event.prop
def foo(self, v=0):
return v
@event.connect('foo')
def on_foo(self, *events):
for ev in events:
print('foo changed to', ev.new_value)
# Create model in main thread
model = MyModel1()
# Start server in its own thread
app.create_ser... |
icarito/sugar | src/jarabe/model/shell.py | Python | gpl-3.0 | 28,033 | 0 | # Copyright (C) 2006-2007 Owen Williams.
# Copyright (C) 2006-2008 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 3 of the License, or
# (at your option) any late... | tivity.LAUNCHING
if color is not None:
self._color = color
else:
self._color = profile.get_color()
if window is not None:
self.add_window(window)
self._retrieve_service()
self._name_owner_changed_handler = None
if not self._service:... | wnerChanged',
dbus_interface='org.freedesktop.DBus')
self._launch_completed_hid = \
get_model().connect('launch-completed',
self.__launch_completed_cb)
self._launch_failed_hid = get_model().connect('launch-failed',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.