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 |
|---|---|---|---|---|---|---|---|---|
Melraidin/docker-py | docker/constants.py | Python | apache-2.0 | 173 | 0 | DEFAULT_DOCKER_API_VERSIO | N = '1.19'
DEFAULT_TIMEOUT_SECONDS = 60
STREAM_HEADER_SIZE_BYTES = 8
CONT | AINER_LIMITS_KEYS = [
'memory', 'memswap', 'cpushares', 'cpusetcpus'
]
|
tylercal/dragonfly | dragonfly/test/test_contexts.py | Python | lgpl-3.0 | 4,426 | 0.000226 | #
# This file is part of Dragonfly.
# (c) Copyright 2018 by Dane Finlay
# Licensed under the LGPL.
#
# Dragonfly 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... | fly. If not, see
# <http://www.gnu.org/lice | nses/>.
#
import unittest
from dragonfly import CompoundRule, MimicFailure
from dragonfly.test import (RuleTestCase, TestContext, RuleTestGrammar)
# ==========================================================================
class TestRules(RuleTestCase):
def test_multiple_rules(self):
""" Verify that ... |
tulikavijay/vms | vms/shift/views.py | Python | gpl-2.0 | 26,821 | 0.003169 | # standard library
from datetime import date
# third party
from braces.views import LoginRequiredMixin, AnonymousRequiredMixin
# Django
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlreso... | status=403
)
if request.method == 'POST':
try:
cancel_shift_registration(volunteer_id, shift_id)
if admin:
return HttpResponseRedirect(reverse(
'shift:manage_volunteer_shifts',
... | args=(volunteer_id, )
))
elif volunteer:
return HttpResponseRedirect(reverse(
'shift:view_volunteer_shifts',
args=(volunteer_id, )
))
else:
... |
xifle/home-assistant | homeassistant/components/binary_sensor/enocean.py | Python | mit | 2,747 | 0 | """
Support for EnOcean binary sensors.
For more details about this platform, please refer to the documentation at
https://hom | e-assistant.io/components/binary_sensor.enocean/
"""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA, SENSOR_CLASSES_SCHEMA)
fro | m homeassistant.components import enocean
from homeassistant.const import (CONF_NAME, CONF_ID, CONF_SENSOR_CLASS)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['enocean']
DEFAULT_NAME = 'EnOcean binary sensor'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
... |
gitesei/faunus | examples/pythontest.py | Python | mit | 4,462 | 0.032048 | #!/usr/bin/env python
import json
import unittest
import numpy as np
from math import pi
import sys
sys.path.insert(0,'../')
from pyfaunus import *
# Dictionary defining input
d = {}
d['geometry'] = { 'type': 'cuboid', 'length': 50 }
d['atomlist'] = [
{ 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) },
... | , 300)
# Loop over atom types
for i in atoms:
print("atom name and diameter:", i.name, i.sigma)
# Test Coulomb
class TestCoulomb(unittest.TestCase):
# this doesn't test anything yet
def test_pairpot(self):
d = { 'default' : [
{ 'coulomb': { 'epsr': 80, 'type': 'qpotential', 'cutoff'... | }
pot = FunctorPotential( d )
r = np.linspace(1,10,5)
u = np.array( [pot.energy( spc.p[0], spc.p[1], [0,0,i] ) for i in r] )
pot.selfEnergy(spc.p[0])
# Test SASA calculations
class TestSASA(unittest.TestCase):
def test_pairpot(self):
d = { 'default' : [
{ 'sasa... |
BITalinoWorld/python-serverbit | twisted-ws/txws.py | Python | gpl-3.0 | 19,519 | 0.000768 | # Copyright (c) 2011 Oregon State University Open Source Lab
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, mod... | (key, guid)).digest().encode("base64").strip()
# Frame helpers.
# Separated out to make unit testing a lot easier.
# Frames are bonghits in newer WS versions, so helpers are appreciated.
def make_hybi00_frame(buf):
"""
Make a HyBi-00 f | rame from some data.
This function does exactly zero checks to make sure that the data is safe
and valid text without any 0xff bytes.
"""
return "\x00%s\xff" % buf
def parse_hybi00_frames(buf):
"""
Parse HyBi-00 frames, returning unwrapped frames and any unmatched data.
This function doe... |
midokura/python-neutron-plugin-midonet | midonet/neutron/plugin.py | Python | apache-2.0 | 35,809 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Midokura Japan K.K.
# Copyright (C) 2013 Midokura PTE LTD
# Copyright (C) 2014 Midokura SARL.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the Licen... | e_api_error
def create_network(self, context, network):
"""Create Neutron network.
Create a new Neutron network and its corresponding MidoNet bridge.
"""
LOG.info(_('MidonetPluginV2.create_network called: network=%r'),
network)
net = self._process_create_ne | twork(context, network)
try:
self.api_cli.create_network(net)
except Exception as ex:
LOG.error(_("Failed to create a network %(net_id)s in Midonet:"
"%(err)s"), {"net_id": net["id"], "err": ex})
with excutils.save_and_reraise_exception():
... |
johanfrisk/Python_at_web | notebooks/code/geoxml.py | Python | mit | 743 | 0.012113 | import urllib
import xml.etree.ElementTree as ET
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/xml?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh =... | ress').text
print 'la | t',lat,'lng',lng
print location
|
NicovincX2/Python-3.5 | Algorithmique/Mathématiques discrètes/Combinatoire/Nombre de Catalan/nb_catalan_3methods.py | Python | gpl-3.0 | 1,091 | 0 | # -*- coding: utf-8 -*-
import os
from math import factorial
import functools
def memoize(func):
cache = {}
def memoized(key):
# Returned, new, memoized version of decorated function
if key not in cache:
cache[key] = func(key)
return cache[key]
return functools.updat... | atR1(n):
return (1 if n == 0
else sum(catR1(i) * catR1(n - 1 - i)
for i in range(n)))
@memoize
def catR2(n):
return (1 if n == 0
else ((4 * n - 2) * catR2(n - 1)) // (n + 1))
if __name__ == '__main__':
def pr(results):
fmt = '%-10s %-10s %-10s'
... | ())
print(fmt % (('=' * 10,) * 3))
for r in zip(*results):
print(fmt % r)
defs = (cat_direct, catR1, catR2)
results = [tuple(c(i) for i in range(15)) for c in defs]
pr(results)
os.system("pause")
|
orbitfp7/nova | nova/scheduler/filter_scheduler.py | Python | apache-2.0 | 7,412 | 0.00027 | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | filter_properties)
# Find our local list of acceptable hosts by repeatedly
# filtering and weighing our options. Each time we choose a
# host, we virtually consume resources on it so subsequent
# selections can adjust accordingly.
# Note: remember... | iterator here. So only
# traverse this list once. This can bite you if the hosts
# are being scanned in a filter or weighing function.
hosts = self._get_all_host_states(elevated)
selected_hosts = []
num_instances = request_spec.get('num_instances', 1)
for num in xrange(n... |
matteo88/gasistafelice | gasistafelice/rest/views/blocks/basket.py | Python | agpl-3.0 | 8,830 | 0.013024 | from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
from django.core import urlresolvers
from gasistafelice.rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction, CREATE_PDF, SENDME_PDF
from gasistafelice.consts import EDIT, CONFIRM
from gasistafelice.lib.shortcuts import render_... | er(__name__)
#--------------------------------- | ---------------------------------------------#
# #
#------------------------------------------------------------------------------#
class Block(BlockSSDataTables):
BLOCK_NAME = "basket"
BLOCK_DESCRIPTION = _("Basket")
BLOCK_VALID... |
gaamy/INF4215_IA | tp1/breadthfirst_search.py | Python | gpl-2.0 | 634 | 0.003155 | # Breadth-first Search
#
# Author: Michel Gagnon
# michel.gagnon@polytml.ca
from node import *
from state import *
def breadthfirst_search(initialState):
frontier = [Node(initi | alState)]
visited = set()
while frontier:
node = frontier.pop(0)
visited.add(node.state)
# node.state.show()
# print '----------------'
if node.state.isGoal():
node.state.show()
return node
elif node.isRepeated():
continue
... | frontier + [child for child in node.expand() if child.state not in visited]
return None
|
grahamhayes/designate | designate/api/v2/controllers/tsigkeys.py | Python | apache-2.0 | 4,349 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/... | mitations
# under the License.
import pecan
from oslo_log import log as logging
from designate import utils
from designate.api.v2.controllers import rest
from designate.objects import TsigKey
from designate. | objects.adapters import DesignateAdapter
LOG = logging.getLogger(__name__)
class TsigKeysController(rest.RestController):
SORT_KEYS = ['created_at', 'id', 'updated_at', 'name']
@pecan.expose(template='json:', content_type='application/json')
@utils.validate_uuid('tsigkey_id')
def get_one(self, tsigk... |
suziesparkle/wagtail | wagtail/vendor/django-treebeard/treebeard/tests/test_treebeard.py | Python | bsd-3-clause | 90,877 | 0.000044 | # -*- coding: utf-8 -*-
"""Unit/Functional tests"""
from __future__ import with_statement, unicode_literals
import datetime
import os
import sys
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.models import User
from django.contrib.messa... | rn _prepare_db_test(request)
@pytest.fixture(scope='function', params=[models.MP_TestNodeShortPath])
def mpshortnotsorted_model(request):
return _prepare_db_test(request)
@pytest.fixture(scope='function', params=[models.MP_TestNodeAlphabet])
def mpalphabet_model(request):
return _prepare_db_test(request)
... | l(request):
return _prepare_db_test(request)
@pytest.fixture(scope='function', params=[models.MP_TestNodeSmallStep])
def mpsmallstep_model(request):
return _prepare_db_test(request)
@pytest.fixture(scope='function', params=[models.MP_TestManyToManyWithUser])
def mpm2muser_model(request):
return _prepare... |
wq/xlsform-converter | tests/files/input_types/models.py | Python | mit | 2,324 | 0 | from django.contrib.gis.db import models
class InputTypes(models.Model):
int_field = models.IntegerField(
null=True,
blank=True,
verbose_name="Integer field",
help_text="Enter an integer number.",
)
dec_field = models.FloatField(
null=True,
blank=True,
... | ,
verbose_name="Char field",
help_text="Enter some text.",
)
point_field = models.PointField(
srid=4326,
verbose_name="Point field",
| help_text="Enter a point.",
)
linestring_field = models.LineStringField(
srid=4326,
null=True,
blank=True,
verbose_name="Line string field",
help_text="Enter a line.",
)
polygon_field = models.PolygonField(
srid=4326,
null=True,
blank=True,... |
gradiuscypher/internet_illithid | mirror_shield/endpoints/filestore.py | Python | mit | 2,550 | 0.001176 | import traceback
import requests
import time
import imghdr
from os.path import exists, isfile, join, isdir
from os import makedirs, listdir, walk
from flask import Blueprint, request, send_from_directory, render_template
filestore = Blueprint('callback', __name__)
@filestore.route('/clone', methods=["POST"])
def clo... | filepath = "files/"
for f in list | dir(filepath):
if isdir(join(filepath, f)):
services.append(f)
return render_template('servicelist.html', services=services)
@filestore.route('/<service>/userlist', methods=["GET"])
def userlist(service):
users = []
filepath = "files/{}".format(service)
for f in listdir(filepath):... |
toddpalino/kafka-tools | kafka/tools/protocol/responses/__init__.py | Python | apache-2.0 | 2,328 | 0.000859 | import abc
import pprint
import six
def _decode_plain_type(value_type, buf):
if value_type == 'int8':
return buf.getInt8()
elif value_type == 'int16':
return buf.getInt16()
elif va | lue_type == 'int32':
return buf.getInt32()
elif value_type == 'int64':
return buf.getInt64()
elif value_type == 'string':
val_len = buf.getInt16()
return None if val_len == -1 else buf.get(val_len).decode("utf-8")
elif value_type == 'bytes':
val_len = buf.getInt32()
... | en == -1 else buf.get(val_len)
elif value_type == 'boolean':
return buf.getInt8() == 1
else:
raise NotImplementedError("Reference to non-implemented type in schema: {0}".format(value_type))
def _decode_array(array_schema, buf):
array_len = buf.getInt32()
if array_len == -1:
ret... |
IEEEDTU/CMS | Course/views/CourseCurriculum.py | Python | mit | 2,775 | 0 | from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Course.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_POST
def addCourseCurriculum(request):
respon... | data = serializers.serialize('json', [C, ])
response_data | ["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_POST
def deleteCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.deleteCourseCurriculum(request.POST)
except Exception as e:
response_data['success'] = '0'
... |
zhuango/python | sklearnLearning/statisticalAndSupervisedLearning/adaboost.py | Python | gpl-2.0 | 2,852 | 0.002454 | print(__doc__)
# Author: Noel Dawe <noel.dawe@gmail.com>
#
# License: BSD 3 clause
from sklearn.externals.six.moves import zip
import matplotlib.pyplot as plt
from sklearn.datasets import make_gaussian_quantiles
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score
from sklearn.... | Classifier(
DecisionTreeClassifier(max_depth=2),
n_estimators=600,
learning_rate=1)
bdt_discrete = AdaBoostC | lassifier(
DecisionTreeClassifier(max_depth=2),
n_estimators=600,
learning_rate=1.5,
algorithm="SAMME")
bdt_real.fit(X_train, y_train)
bdt_discrete.fit(X_train, y_train)
real_test_errors = []
discrete_test_errors = []
for real_test_predict, discrete_train_predict in zip(
bdt_real.staged_predi... |
manazag/hopper.pw | hopperpw/hopperpw/settings/test.py | Python | bsd-3-clause | 229 | 0.004367 | # coding=utf-8
from __future__ import | absolute_import
from .base import *
# ######### IN-MEMORY TEST DATABASE
DATABASES = {
"default": {
"ENGINE": " | django.db.backends.sqlite3",
"NAME": ":memory:",
},
} |
chrys87/orca-beep | test/keystrokes/gtk-demo/role_table.py | Python | lgpl-2.1 | 3,344 | 0.001794 | #!/usr/bin/python
"""Test of table output."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("End"))
sequence.append(KeyComboAction("Up"))
sequence.append(KeyComboAction("<Shift>Right"))
sequence.append(KeyComboAction("Down"))
sequence.append(KeyComboAction("R... | ', cursor=1",
"SPEECH OUTPUT: '5 packages of noodles.'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_Enter"))
sequence.append(utils.AssertPresentationAction(
"3. Table Where Am I (again)",
["BRAILLE LINE: 'gtk-demo application Shopping list frame table Number column... | "SPEECH OUTPUT: 'table cell.'",
"SPEECH OUTPUT: '5.'",
"SPEECH OUTPUT: 'column 1 of 3'",
"SPEECH OUTPUT: 'row 2 of 5.'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyPressAction(0, None, "KP_Insert"))
sequence.append(KeyComboAction("F11"))
sequence.append(KeyReleaseAction(0, Non... |
failys/CAIRIS | cairis/test/test_Attacker.py | Python | apache-2.0 | 4,335 | 0.009919 | # 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... | ]), str(oatkeps[0].roles()[0]))
self.assertEqual(str(iatkeps[0].roles()[0]), o.roles('Day','')[0])
self.assertEqual(iatkeps[0].roles(), list(o.roles('','Maximise')))
self.assertEqual(str(iatkeps[0].motives()[0]), str(oatkeps[0].motives()[0]))
self.assertEqual(str(iatkeps[0].motives()[0]), str(o.motives(... | s()[0][0]), str(oatkeps[0].capabilities()[0][0]))
self.assertEqual(str(iatkeps[0].capabilities()[0][1]), str(oatkeps[0].capabilities()[0][1]))
self.assertEqual(iatkeps[0].capabilities()[0][0], o.capability('Day','')[0][0])
self.assertEqual(iatkeps[0].capabilities()[0][0], list(o.capability('','Maximise'))[0... |
kevin8909/xjerp | openerp/addons/crm/crm_lead.py | Python | agpl-3.0 | 53,864 | 0.005607 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | d, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
access_rights_uid = access_rights_uid or uid
stage_obj = self.pool.get('crm.case.stage')
order = stage_obj._order
# lame hack to allow reverting search, should jus | t work in the trivial case
if read_group_order == 'stage_id desc':
order = "%s desc" % order
# retrieve section_id from the context and write the domain
# - ('id', 'in', 'ids'): add columns that should be present
# - OR ('case_default', '=', True), ('fold', '=', False): add d... |
teddyrendahl/powermate | tests/conftest.py | Python | apache-2.0 | 1,119 | 0.008937 | ##############
# Standard | #
##############
import io
import logging
import tempfile
##############
# External #
##############
import pytest
##############
# Module #
##############
import powermate
#Enable the logging level to be set from the command line
def pytest_addoption(parser):
parser.addoption('--log', action='store', def... | (pytestconfig):
#Read user input logging level
log_level = getattr(logging, pytest.config.getoption('--log'), None)
#Report invalid logging level
if not isinstance(log_level, int):
raise ValueError("Invalid log level : {}".format(log_level))
#Create basic configuration
logging.basicCon... |
manhhomienbienthuy/pythondotorg | sponsors/migrations/0057_auto_20211026_1529.py | Python | apache-2.0 | 416 | 0 | # Generated by Django 2.2.24 on 2021-1 | 0-26 15:29
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0056_textasset'),
]
operations = [
migrations.AlterField(
model_name='genericasset',
name='uuid',
field=models.UUIDFi... | ]
|
odoousers2014/odoo | addons/l10n_co/__openerp__.py | Python | agpl-3.0 | 1,792 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) David Arnold (devCO).
# Author David Arnold (devCO), dar@devco.co
# Co-Authors Juan Pablo Aries (devCO), jpa@devco.co
# Hector Ivan ... | r option) any later version.
#
# This program 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 A | ffero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Colombian - Accounting',
... |
guilhermedallanol/dotfiles | vim/plugged/vial-http/server/dswf.py | Python | mit | 2,837 | 0.003525 | """Thin wrapper around Werkzeug because Flask and Bottle
do not play nicely with async uwsgi"""
import json
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.utils import redirect
from covador import ValidationD... | adapter = self._url_map.bind_to_environ(request.environ)
try:
endpoint, values = adapter.match()
return endpoint(request, **values)
except HTTPException as e:
return e
def _ | _call__(self, env, sr):
request = AppRequest(env)
response = self._dispatch(request)
after_handlers = getattr(request, '_after_request_handlers', None)
if after_handlers:
for h in after_handlers:
response = h(response) or response
return response(env, ... |
CLVsol/odoo_addons | clv_patient/seq/clv_patient_category_seq.py | Python | agpl-3.0 | 3,797 | 0.007638 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | str(code[6]) + str(code[7]),
| str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6... |
kmonsoor/windenergytk | windenergytk/gwindtk.py | Python | gpl-3.0 | 30,991 | 0.008648 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# gwindetk.py #
# #
# Part of UMass Amherst's Wind... | from the original Visual Basic code at #
# http://www.ceere.org/rerl/projects/software/mini-code-overview.html #
# | #
# These tools can be used in conjunction with the textbook #
# "Wind Energy Explained" by J.F. Manwell, J.G. McGowan and A.L. Rogers #
# http://www.ceere.org/rerl/rerl_windenergytext.html #
# ... |
UManPychron/pychron | pychron/lasers/tasks/panes/ablation.py | Python | apache-2.0 | 4,882 | 0.004506 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licens... | rs.tasks.laser_panes import ClientPane
class AblationCO2ClientPane(ClientPane):
def trait_context(self):
ctx = super(AblationCO2ClientPane, self).trait_context()
ctx['tray_calibration'] = self.model.stage_manager.tray_calibration_manager
ctx['stage_m | anager'] = self.model.stage_manager
return ctx
def traits_view(self):
pos_grp = VGroup(UItem('move_enabled_button',
editor=ButtonEditor(label_value='move_enabled_label')),
VGroup(HGroup(Item('position'),
... |
ahmadiga/min_edx | lms/djangoapps/oauth2_handler/tests.py | Python | agpl-3.0 | 9,001 | 0.001333 | # pylint: disable=missing-docstring
from django.core.cache import cache
from django.test.utils import override_settings
from lang_pref import LANGUAGE_KEY
from xmodule.modulestore.tests.factories import (check_mongo_calls, CourseFactory)
from student.models import anonymous_id_for_user
from student.models import UserP... | elf.profile = UserProfileFactory(user=s | elf.user)
class IDTokenTest(BaseTestMixin, IDTokenTestCase):
def setUp(self):
super(IDTokenTest, self).setUp()
# CourseAccessHandler uses the application cache.
cache.clear()
def test_sub_claim(self):
scopes, claims = self.get_id_token_values('openid')
self.assertIn('... |
ImTheTom/discordBot | cogs/search.py | Python | mit | 12,276 | 0.008635 | #import list
import asyncio
import discord
from discord.ext import commands
import importlib.machinery
import datetime
import requests
import json
from bs4 import BeautifulSoup as BS
from requests import get as re_get
from random import *
from re import findall, match, search
TooBig = ["You know you make a cool bot an... | iption.contents
i=0
length=len(description)
d=""
while(i<length):
d = d +str(description[i])
i+=1
d = stripOfSpecialCharacters(d)
message= "Search URL: "+url+"\n\nResults: "+resul | ts+".\n\nFirst URL: "+link+"\n\nTitle: "+string+".\n\nDescription: "+d
return message
except:
message = "Something went wrong here. Either I fucked up or you fucked up. My money is on you that fucked it up."
return message
def urbanSearch(url):
try:
bs = BS(re_get(url).text, "ht... |
Awingu/open-ovf | py/tests/OvfEnvironmentTestCase.py | Python | epl-1.0 | 22,345 | 0.002775 | #!/usr/bin/python
# vi: ts=4 expandtab syntax=python
##############################################################################
# Copyright (c) 2008 IBM Corporation
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which acco... | self.assertEquals(section.length, 3)
# Verify that a new PlatformSection is added to an
# existin | g Entity.
self.ovfEnv.createSection(self.entID, "PlatformSection", self.platdata)
section = self.ovfEnv.findElementById(self.entID)
element = section.getElementsByTagName("Version")
self.assertEquals(element.length, 1)
# Verify that a new PropertySection is added to an
# ... |
gratipay/gratipay.com | gratipay/utils/icons.py | Python | mit | 341 | 0.046921 | STATUS_ICONS = { "success": ""
, "warning": ""
| , "failure": ""
, "feature": ""
}
REVIEW_MAP = { 'approved': 'success'
| , 'unreviewed': 'warning'
, 'rejected': 'failure'
, 'featured': 'feature'
}
|
crashtack/django-imager | imager_profile/apps.py | Python | mit | 260 | 0 | from django.apps import AppConfig
class ImagerProfileAppConfig(AppConf | ig):
name = "imager_profile"
verbose_name = "Imager User Profile"
def ready(self):
"""code to run when t | he app is ready"""
from imager_profile import handlers
|
scheib/chromium | third_party/blink/web_tests/external/wpt/webdriver/tests/perform_actions/support/mouse.py | Python | bsd-3-clause | 927 | 0.004315 | def get_viewport_rect(session):
return session.execute_script("""
return {
height: window.innerHeight || document.documentElement.clientHeight,
width: window.innerWidth || document.documentElement.clientWidth,
};
""")
def get_inview_center(elem_rect, viewport_rect):
x =... | ight"])),
}
return {
"x": (x["left"] + x["right"]) / 2,
| "y": (y["top"] + y["bottom"]) / 2,
}
|
neuropoly/spinalcordtoolbox | spinalcordtoolbox/scripts/sct_compute_mtr.py | Python | mit | 2,861 | 0.003146 | #!/usr/bin/env python
#########################################################################################
#
# Compute magnetization transfer ratio (MTR).
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
#... | rser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
fname_mtr = arguments.o
# compute MTR
printv('\nCompute MTR...', verbose)
nii_mtr = compute_mtr(nii_mt1=Image(arguments.mt1), nii_mt0=Image(arguments.mt0), threshold_mtr=arguments.th... | ame__ == "__main__":
init_sct()
main(sys.argv[1:])
|
Discountrobot/Headless | headless/checkLogins.py | Python | mit | 715 | 0.020979 | import json
import urllib
import urllib2
import sys
for login in json.load(open(sys.argv[1])):
if login['EmailAddress']:
try:
# encode the json
data = urllib.urlencode(login)
# make the POST request
#
response = urllib2.urlopen('https://login.eovendo.com', data, 10)
# encode ... | led with msg: ' + jr['Message'].encode('utf-8')
except Exception, e:
pr | int e
else:
print str(login) + " isn't valid"
|
liqd/a4-meinberlin | meinberlin/apps/organisations/migrations/0007_remove_organisation_type.py | Python | agpl-3.0 | 420 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-04 16:09 |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('meinberlin_organisations', '0006_update_orga_type_string'),
]
operations = [
migrations.RemoveField(
model_name='organisation', |
name='type',
),
]
|
johnnyliu27/openmc | openmc/lattice.py | Python | mit | 53,509 | 0.000523 | from abc import ABCMeta
from collections import OrderedDict
from collections.abc import Iterable
from copy import deepcopy
from math import sqrt, floor
from numbers import Real, Integral
from xml.etree import ElementTree as ET
import numpy as np
import openmc.checkvalue as cv
import openmc
from openmc._xml import get... | universes : dict
| Dictionary mapping universe IDs to instances of
:class:`openmc.Universe`.
Returns
-------
openmc.Lattice
Instance of lattice subclass
"""
lattice_id = int(group.name.split('/')[-1].lstrip('lattice '))
name = group['name'].value.decode(... |
dilawar/moose-core | python/moose/neuroml2/hhfit.py | Python | gpl-3.0 | 8,486 | 0.001414 | # -*- coding: utf-8 -*-
# hhfit.py ---
# Description:
# Author:
# Maintainer:
# Created: Tue May 21 16:31:56 2013 (+0530)
# Commentary:
# Functions for fitting common equations for Hodgkin-Huxley type gate
# equations.
import traceback
import warnings
import numpy as np
import logging
logger_ = logging.getLogger('moo... | rnings.warn(
'Maximum iteration %d reached. Could not find a decent fit. %s' %
(maxiter, msg), RuntimeWarning)
return p_best
def find_ratefn(x, y, **kwargs):
"""Find the function that fits the rate function best. This will try
exponential, sigmoid and linoid and return the best fit... | y: 1D array
function values.
**kwargs: keyword arguments
passed to randomized_curve_fit.
Returns
-------
best_fn: function
the best fit function.
best_p: tuple
the optimal parameter values for the best fit function.
"""
rms_error = 1e10 # arbitrarily setting this
... |
UrbanCCD-UChicago/plenario | plenario/models/SensorNetwork.py | Python | mit | 8,829 | 0.00068 | import json
from geoalchemy2 import Geometry
from sqlalchemy import BigInteger, Boolean, Column, DateTime, Float, ForeignKey, ForeignKeyConstraint, String, Table, \
func as sqla_fn
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, JSONB
from sqlalchemy.orm import relationship
from plenario.database imp... | for feature in sensor.values():
keys += feature.values()
return set([k.split('.')[0] for k in keys])
class NodeMeta(postgres_base):
__tablename__ = 'sensor__node_metadata'
id = Column(String, primary_key=True)
sensor_network = Column(String, ForeignKey('sensor__network_met... | ensorMeta', secondary='sensor__sensor_to_node')
info = Column(JSONB)
address = Column(String)
column_editable_list = ('sensors', 'info')
@staticmethod
def all(network_name):
query = NodeMeta.query.filter(NodeMeta.sensor_network == network_name)
return query.all()
@staticmethod... |
MehmetNuri/ozgurlukicin | beyin2/__init__.py | Python | gpl-3.0 | 188 | 0.005376 | #!/usr/bin/python
# -*- coding: | utf-8 -*-
#
# Copyright 2010 TÜBİTAK UEKAE
# Licensed under the GNU General Public License, ve | rsion 3.
# See the file http://www.gnu.org/copyleft/gpl.txt. |
geographika/mappyfile | docs/scripts/class_diagrams.py | Python | mit | 3,102 | 0.000645 | r"""
Create MapServer class diagrams
Requires https://graphviz.gitlab.io/_pages/Download/Download_windows.html
https://stackoverflow.com/questions/1494492/graphviz-how-to-go-from-dot-to-a-graph
For DOT languge see http://www.graphviz.org/doc/info/attrs.html
cd C:\Program Files (x86)\Graphviz2.38\bin
dot -Tpng D:\Git... | (gviz_path):
os.environ['PATH'] = gviz_path + ";" + os.environ['PATH']
| def add_child(graph, child_id, child_label, parent_id, colour):
"""
http://www.graphviz.org/doc/info/shapes.html#polygon
"""
node = pydot.Node(child_id, style="filled", fillcolor=colour, label=child_label, shape="polygon", fontname=FONT)
graph.add_node(node)
graph.add_edge(pydot.Edge(parent_id, ... |
caesar2164/edx-platform | openedx/stanford/lms/djangoapps/instructor/urls.py | Python | agpl-3.0 | 1,465 | 0.004096 | from django.conf.urls import url
urlpatterns = [
url(
r'delete_report_download',
'openedx.stanford.lms.djangoapps.instructor.views.api.delete_report_download',
name='delete_report_download',
),
url(
r'^get_blank_lti$',
'openedx.stanford.lms.djangoapps.instructor.view... | 'openedx.stanford.lms.djangoapps.instructor.views.api.get_student_responses_view',
name='get_student_responses',
| ),
url(
r'^graph_course_forums_usage',
'openedx.stanford.lms.djangoapps.instructor.views.api.graph_course_forums_usage',
name='graph_course_forums_usage',
),
url(
r'^upload_lti$',
'openedx.stanford.lms.djangoapps.instructor.views.api.upload_lti',
name='upl... |
buma/TogglViz | setup.py | Python | gpl-2.0 | 438 | 0 | from setuptools import setup
setup(
name='TogglViz',
version='0.1de | v',
author='Marko Burjek',
packages=['togglviz', ],
scripts=['bin/fill.py', ],
license='LICENSE.txt',
long_description=o | pen('README.txt').read(),
install_requires=[
"SQLAlchemy==0.7.9",
"docopt==0.5.0",
"schema==0.1.1",
"python-dateutil==2.1",
],
)
|
tylerdave/reqcli | reqcli/cli.py | Python | mit | 1,667 | 0.004199 | import click
import requests
@click.command()
@click.argument('url')
@click.option('--show-headers', '-H', is_flag=True, default=False)
@click.option('--show-status', '-S', is_flag=True, default=False)
@click.option('--quiet', '-Q', is_flag=True, default=False)
@click.option('--allow-redirects/--no-allow-redirects', d... | e), err=True, fg='yellow' )
raise click.Abort()
except Exception as e:
click.secho(str(e), err=True, fg='red' )
raise click.Abort()
status_colors = {
2: 'green',
3: 'blue',
4: 'yellow',
5: 'red',
}
# Show the response stat... | .status_code) / 100)
click.secho('Status: {0}'.format(response.status_code), err=True, fg=status_color)
# Show the response headers
if show_headers:
click.echo(format_headers(response.headers), err=True)
# Show the response body
if not quiet:
click.echo(response.text)
if __nam... |
mfherbst/spack | lib/spack/spack/util/environment.py | Python | lgpl-2.1 | 3,500 | 0 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermo | re National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
| # Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed ... |
svenhertle/django_image_exif | image_exif/migrations/0001_initial.py | Python | mit | 1,140 | 0.005263 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('filer', '0002_auto_20150606_2003'),
]
operations = [
migrations.CreateModel(
name='ExifData',
fields... | , models.CharField(max_length=100, verbose_name='Fo | cal length', blank=True)),
('iso', models.CharField(max_length=100, verbose_name='ISO', blank=True)),
('fraction', models.CharField(max_length=100, verbose_name='Fraction', blank=True)),
('exposure_time', models.CharField(max_length=100, verbose_name='Exposure time', blan... |
CPSC491FileMaker/project | calTimer.QThread.py | Python | gpl-2.0 | 717 | 0.013947 | #rew | rite of original calTimer to use qthreads as opposed to native python threads
#needed to make UI changes (impossible from native)
#also attempting to alleviate need for sigterm to stop perm loop
from PyQt4 import QtCore
import time,os,ctypes
import sys
class ca | lTimer(QtCore.QThread):
xml_file = './data/data.xml'
fileSize = os.stat(xml_file)
def initFileSize(self):
print "initfilesize run"
fileToCheck = os.stat(self.xml_file)
self.fileSize = fileToCheck.st_size
def run(self):
self.initFileSize()
testFileSize = self.fi... |
serefimov/billboards | billboards/boards/parsing/__init__.py | Python | mit | 57 | 0.017544 | # -*- c | oding: utf-8 - | *-
__author__ = 'Sergey Efimov'
|
marco-lancini/Showcase | app_collaborations/options.py | Python | mit | 5,831 | 0.008918 | from django.utils.translation import ugettext as _
#=========================================================================
# HELPERS
#=========================================================================
def get_display(key, list):
d = dict(list)
if key in d:
return d[key]
return None
def ... | ', 'Information Technology'): (
| ('I1', _('Mobile Programming')),
('I2', _('Programming')),
('I3', _('Software Engineering')),
('I4', _('User Interface Design')),
('I5', _('Videogame Design')),
('I6', _('Web Design... |
TelekomCloud/virt-manager | tests/nodedev.py | Python | gpl-2.0 | 9,369 | 0.000534 | #
# 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 the hope that it will be useful,
... | Ricoh Co Ltd"}
self._testCompare(devname, vals)
def testPCIDevice2(self):
devname = "pci_8086_1049"
vals = {"name": "pci_8086_1049", "parent": "computer",
"device_type": nodeparse.CAPABIL | ITY_TYPE_PCI,
"domain": "0", "bus": "0", "slot": "25", "function": "0",
"product_id": "0x1049", "vendor_id": "0x8086",
"product_name": "82566MM Gigabit Network Connection",
"vendor_name": "Intel Corporation"}
self._testCompare(devname, vals)
d... |
jaja14/lab5 | main/main.py | Python | mit | 5,013 | 0.007181 | # -*- coding: utf-8 -*-
import logging
from flask.ext import wtf
from google.appengine.api import mail
import flask
import config
import util
app = flask.Flask(__name__)
app.config.from_object(config)
app.jinja_env.line_statement_prefix = '#'
app.jinja_env.line_comment_prefix = '##'
app.jinja_env.globals.update(sl... |
sender=config.CONFIG_DB.feedback_email,
to=config.CONFIG_DB.feedback_email,
subject='[%s] %s' % (
config.CONFIG_DB.brand_name,
form.subject.data,
| ),
reply_to=form.email.data or config.CONFIG_DB.feedback_email,
body='%s\n\n%s' % (form.message.data, form.email.data)
)
flask.flash('Thank you for your feedback!', category='success')
return flask.redirect(flask.url_for('welcome'))
return flask.render_template(
'feedback.... |
TresAmigosSD/SMV | src/test/python/testModuleHash/after/src/main/python/stage/modules.py | Python | apache-2.0 | 4,078 | 0.012016 | #
# This file is 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... | veTable, SmvCsvFile
def sameFunc():
"""a function which is the same in before/after"""
return "I'm the same!"
def differentFunc():
"""a function that has different source in before/a | fter"""
return "I'm in after!"
class ChangeCode(SmvModule):
def requiresDS(self):
return []
def run(self, i):
return self.smvApp.createDF("k:String;v:Integer", "a,;b,3")
class AddComment(SmvModule):
# I ADDED A COMMENT, POP!
def requiresDS(self):
return []
def run(self,... |
indashnet/InDashNet.Open.UN2000 | android/external/chromium_org/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py | Python | apache-2.0 | 20,425 | 0.003329 | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... | ._is_websocket_test(test)
def _is_websocket_test(self, test):
return self.WEBSOCKET_SUBDIR in test
def _http_tests(self, test_names):
return set(test for test in test_names if self._is_http_test(test))
def _is_perf_test(self, test):
return self.PERF_SUBDIR == test or (self.PERF_SU... | hs, test_names):
tests_to_skip = self._finder.skip_tests(paths, test_names, self._expectations, self._http_tests(test_names))
tests_to_run = [test for test in test_names if test not in tests_to_skip]
# Create a sorted list of test files so the subset chunk,
# if used, contains alphabeti... |
LockScreen/Backend | venv/lib/python2.7/site-packages/botocore/credentials.py | Python | mit | 22,856 | 0.000306 | # Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http... | he "licen | se" file accompanying this file. This file 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.
import datetime
import functools
import logging
import os
fro... |
buchuki/opterator | examples/basic.py | Python | mit | 1,198 | 0.000835 | '''So you want a quick and dirty command line app without screwing around
with argparse or ge | topt, but also without a complicated if-else on the length
of sys.argv. You don't really need a comprehensive help file, because it's just
you running the script and knowing what options are | available is enough.
How many boilerplate lines of code is it gonna take?'''
from opterator import opterate # 1
@opterate # 2
def main(filename, color='red', verbose=False): # 3
print(filename, color, verbose)
main() ... |
ergoithz/browsepy | browsepy/manager.py | Python | mit | 24,389 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
import sys
import argparse
import warnings
import collections
from flask import current_app
from werkzeug.utils import cached_property
from . import mimetype
from . import compat
from .compat import deprecated, usedoc
def defaultsnamedtuple(name, fields, defa... | e(
'Script',
('place', 'type', | 'endpoint', 'filename', 'src'),
{'type': 'script'}),
'html': defaultsnamedtuple(
'Html',
('place', 'type', 'html'),
{'type': 'html'}),
}
def clear(self):
'''
Clear plugin manager state.
Registered widgets will be disposed after c... |
vedgar/ip | Chomsky/util.py | Python | unlicense | 14,523 | 0.002998 | import random, itertools, operator, types, pprint, contextlib, collections
import textwrap, string, pdb, copy, abc, functools
memoiziraj = functools.lru_cache(maxsize=None)
def djeljiv(m, n):
"""Je li m djeljiv s n?"""
return not m % n
def ispiši(automat):
"""Relativno uredan ispis (konačnog ili potisnog... | """Sažimanje 1-torki u njihove elemente. Ostale n-torke ne dira."""
with contextlib.suppress(TypeError, ValueError):
komponenta, = vrijednost
return komponenta
return vrijednost
def naniži(vrijednost):
"""Pretvaranje vrijednosti koja nije n-torka u 1-torku."""
return vrijednost if isi... | kcija_iz_relacije(relacija, *domene):
"""Pretvara R⊆A×B×C×D×E (uz domene A, B) u f:A×B→℘(C×D×E)."""
m = len(domene)
funkcija = {sažmi(x): set() for x in Kartezijev_produkt(*domene)}
for n_torka in relacija:
assert len(n_torka) > m
for x_i, domena_i in zip(n_torka, domene):
as... |
xiaoyongaa/ALL | 网络编程第四周/socket_client.py | Python | apache-2.0 | 717 | 0.038052 | import socket
ip_port=("127.0.0.1",9999)
#买手机
s=socket.socket()
| #直接打电话
s.connect(ip_port)
while True:
#发消息
send_data=input("please ").strip()
if len(send_data)==0:
continue
send_data=bytes(send_data,encoding="utf8")
#客户端发消息 s相当于服务端的conn
s.send(send_data)
print("----------------------------1")
if str(send_data,encoding="utf-8")=="exit" or st... | ------2")
recv_data=str(recv_data,encoding="utf-8")
# if recv_data=="exit" or recv_data=="EXIT":
# break
print(recv_data)
#挂电话
s.close() |
kived/python-for-android | pythonforandroid/bootstraps/pygame/build/build.py | Python | mit | 18,072 | 0.000664 | #!/usr/bin/env python2.7
from os.path import dirname, join, isfile, realpath, relpath, split, exists
from zipfile import ZipFile
import sys
sys.path.insert(0, 'buildlib/jinja2.egg')
sys.path.insert(0, 'buildlib')
from fnmatch import fnmatch
import tarfile
import os
import shutil
import subprocess
import time
import j... | NS, name)
def match_filename(pattern_list, name):
for pattern in pattern_list:
if pattern.startswith('^'):
pattern = pattern[1:]
else:
pattern = '*/' + pattern
if fnmatch(name, pattern):
return True
def listfiles(d):
basedir = d
subdirlist = []... | n):
yield fn
else:
subdirlist.append(os.path.join(basedir, item))
for subdir in subdirlist:
for fn in listfiles(subdir):
yield fn
def make_pythonzip():
'''
Search for all the python related files, and construct the pythonXX.zip
According to
# htt... |
jimarnold/gomatic | gomatic/__init__.py | Python | mit | 484 | 0.002066 | from gomatic.go_cd_configurator import HostRestClient, GoCdConfigurator
from gomatic.gocd.agents import Agent
from gomatic.gocd.materials import GitMaterial, PipelineMaterial
from gomatic.gocd.pipelines import Tab, Job, Pipeline, PipelineGroup
from gomatic.gocd.tasks import FetchArtifactTask, ExecTask, RakeTask
from go... | g
| |
digwanderlust/pants | tests/python/pants_test/backend/jvm/targets/test_jvm_binary.py | Python | apache-2.0 | 9,783 | 0.00828 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
from... | vm()
def test_simple(self):
self.add_to_build_file('BUILD', dedent('''
jvm_binary(name='foo',
main='com.example.Foo',
basename='foo-base',
)
'''))
target = self.target('//:foo')
self.assertEquals('com.example.Foo', target.main)
self.ass | ertEquals('com.example.Foo', target.payload.main)
self.assertEquals('foo-base', target.basename)
self.assertEquals('foo-base', target.payload.basename)
self.assertEquals([], target.deploy_excludes)
self.assertEquals([], target.payload.deploy_excludes)
self.assertEquals(JarRules.default(), target.dep... |
zoff/torrentz-deluge-plugin | torrentztrackersautoload/__init__.py | Python | gpl-2.0 | 1,603 | 0.000624 | #
# __init__.py
#
# Deluge is free software.
#
# You may 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.
#
# deluge is distributed in the hope that it will be u... | eral Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to | do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.
#
from deluge.plugins.init import PluginInitBase
class CorePlugin(PluginInitBase):
def __init__(self, plugin_name)... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/python/estimator/model_fn.py | Python | mit | 12,173 | 0.004354 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | odeKeys.EVAL`: required field is `loss`.
* For `mode == ModeKeys.PREDICT`: required fields are `predictions`.
model_fn can populate | all arguments independent of mode. In this case, some
arguments will be ignored by an `Estimator`. E.g. `train_op` will be
ignored in eval and infer modes. Example:
```python
def my_model_fn(mode, features, labels):
predictions = ...
loss = ...
train_op = ...
return tf.estimator... |
camm/dsfinterp | setup.py | Python | mit | 880 | 0.027273 | '''
Created on Jan 15, 2014
@author: Jose Borreguero
'''
from setuptools import setup
setup(
name = 'dsfinterp',
packages = ['dsfinterp','dsfinterp/test' ],
version = '0.1',
description = 'Cubic Spline Interpolation of Dynamics Structure Factors',
long_description = open('R | EADME.md').read(),
author = 'Jose Borreguero',
author_email = 'jose@borreguero.com',
url = 'https://github.com/camm-sns/dsfinterp',
download_url = 'http://pypi.python.org/pypi/dsfinterp',
keywords = ['AMBER', 'mdend', 'energy', 'molecular dynami | cs'],
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering :: Ph... |
spatialcollective/watsan | watsan/views/settings_views.py | Python | mit | 4,402 | 0.024989 | import json
import uuid
from django.contrib.auth import logout
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from watsan.models import WatsanUserMeta, Organization, N... | rect('/watsan/settings')
else:
new_name_form = EditUserNameForm({'first_name': request.user.first_name, 'last_name': request.user.last_name })
return render(request, 'watsan/dashboard/change_user_name.html', { 'new_name_form': new_name_form })
@login_required(login_url='/watsan/login/?next=/watsan')
def change_us... | l(request):
if request.method == 'POST':
new_email_form = ChangeUserEmailForm(request.POST)
if new_email_form.is_valid():
new_email = new_email_form.save(commit=False)
if User.objects.filter(email=new_email.email).exists():
new_email_form._errors['email'] = new_email_form.error_class([u"That email is al... |
webkom/holonet | holonet/settings/development.py | Python | mit | 1,029 | 0.000972 | from .base import BASE_DIR, INSTALLED_APPS, MIDDLEWARE_CLASSES, REST_FRAMEWORK
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
SECRET_KEY = 'secret'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'holonet',
'USER': 'holonet',
'PASSWORD': '',
... | , )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddlew | are', )
INTERNAL_IPS = ('127.0.0.1', )
POSTFIX_TRANSPORT_MAPS_LOCATION = '{0}/../mta/shared/'.format(BASE_DIR)
|
mashedkeyboard/Headlights | runtests.py | Python | gpl-3.0 | 1,771 | 0.003953 | # Headlights testing
# Designed to be run by Travis CI. Should work for humans too, we suppose. But humans? Bleh.
# Remember to set the HEADLIGHTS_TESTMODE and HEADLIGHTS_DPKEY env-vars before testing.
import tests.configuration, tests.printer, tests.server, tests.plugins
import main
try:
| # Run the configuration tests
tests.configuration.headlightsConfTest()
print("Headlights.cfg.sample configuration test passed")
tests.configuration.weatherConfTest()
print("Weather.cfg.sample configuration test passed")
tests.configuration.webConfTest()
print("Web.cfg configuration test passed")... | sSaveCfgTest()
print("Test.cfg configuration save test passed")
# Run printer-related tests with dummy printers
tests.printer.testSetFont()
print("Dummy printer font set test passed")
tests.printer.testPrintText()
print("Dummy printer text print test passed")
tests.printer.testPrintImage()
... |
StefanRijnhart/bank-statement-import | account_bank_statement_import/__init__.py | Python | agpl-3.0 | 102 | 0 | # -*- encoding: utf-8 -*-
from . import res_partner_bank
from . import account_bank_statement_imp | ort
| |
ianzhengnan/learnpy | coroutine.py | Python | apache-2.0 | 413 | 0.004843 |
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
| r = '200 OK'
def produce(c):
c.send(None)
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer retu | rn: %s' % r)
c.close()
c = consumer()
produce(c) |
Freso/listenbrainz-server | listenbrainz_spark/stats/tests/test_utils.py | Python | gpl-2.0 | 2,000 | 0.0035 | from datetime import datetime
import listenbrainz_spark.stats.utils as stats_utils
from listenbrainz_spark.path import LISTENBRAINZ_DATA_DIRECTORY
from listenbrainz_spark import utils
from listenbrainz_spark.tests import SparkTestCase
from listenbrainz_spark.stats import offset_months, | offset_days
from pyspark.sql import Row
class UtilsTestCase(SparkTestCase):
# use path_ as prefix for all paths in this class.
path_ = LISTENBRAINZ_DATA_DIRECTORY
def tearDown(self):
path_found = utils.path_exists(self.path_)
if path_found:
utils.delete_dir(self.path_, recur... | =date), schema=None)
df = df.union(utils.create_dataframe(Row(listened_at=offset_days(date, 7)), schema=None))
utils.save_parquet(df, '{}/2020/5.parquet'.format(self.path_))
result = stats_utils.get_latest_listen_ts()
self.assertEqual(date, result)
def test_filter_listens(self):
... |
shanot/imp | modules/domino/test/test_bandb_sampler.py | Python | gpl-3.0 | 1,701 | 0.000588 | from __future__ import print_function
import IMP
import IMP.test
import IMP.domino
import IMP.core
class TrivialParticleStates(IMP.domino.ParticleStates):
def __init__(self, n):
IMP.domino.ParticleStates.__init__(self)
self.key = IMP.IntKey("hi")
self.n = n
def get_number_of_particle... | for p in ps:
pst.set_particle_states(p, TrivialParticleStates(ns))
cs = dsst.create_sample()
self.assertEqual(cs.get_number_of_configurations(), ns ** len(ps))
all_states = []
for i in range(0, cs.get_number_of_configurations()):
cs.load_configuration(i)
... | ss = IMP.domino.Assignment(s)
# print all_states
self.assertNotIn(s, all_states)
all_states.append(s)
if __name__ == '__main__':
IMP.test.main()
|
mholgatem/GPIOnext | cursesmenu/items/external_item.py | Python | mit | 1,040 | 0.002885 | import curses
from cursesmenu import clear_terminal
from cursesmenu.items import MenuItem
class ExternalItem(MenuItem):
"""
A base class for items that need to do stuff on the console ou | tside of curses mode.
Sets the terminal back to standard mode until the action is done.
Should probably be subclasse | d.
"""
def __init__(self, text, menu=None, should_exit=False):
# Here so Sphinx doesn't copy extraneous info from the superclass's docstring
super(ExternalItem, self).__init__(text=text, menu=menu, should_exit=should_exit)
def set_up(self):
"""
This class overrides this met... |
blag/django-cities | cities/south_migrations/0001_initial.py | Python | mit | 19,791 | 0.007124 | # -*- 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 model 'Country'
db.create_table(u'cities_country', (
... | ('from_country', models.ForeignKey(orm[u'cities.country'], null=False)),
('to_country', models.ForeignKey(orm[u'cities.country'], null=False))
))
db.create_unique(m2m_table_name, ['from_country_id', 'to_country_id'])
# Adding model 'Region'
db.create_table(u' | cities_region', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=200, db_index=True)),
('slug', self.gf('django.db.models.fields.CharField')(max_length=200)),
('name_std', self.gf('... |
smileboywtu/LTCodeSerialDecoder | netease/const.py | Python | apache-2.0 | 163 | 0.01227 | # encoding: UTF-8
import os
class Constant:
conf_dir = os.path.join(os.path.expanduser('~'), '.netease-musicbox' | )
download_dir = conf_dir + "/cach | ed"
|
odoomrp/odoomrp-wip | mrp_operations_rejected_quantity/models/operation_time_line.py | Python | agpl-3.0 | 1,038 | 0 | # -*- coding: utf-8 -*-
# (c) 20 | 16 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class OperationTimeLine(models.Model):
_inherit = 'operation.time.line'
@api.depends('accepte | d_amount', 'rejected_amount')
@api.multi
def _compute_total_amount(self):
for line in self:
line.total_amount = line.accepted_amount + line.rejected_amount
employee_id = fields.Many2one(
comodel_name='hr.employee', string='Employee', readonly=True)
accepted_amount = fields.I... |
AbletonAG/abl.util | test/test_bunch.py | Python | mit | 1,113 | 0.002695 | from unittest import TestCase
import pickle
from abl.util import (
Bunch,
)
class Derived(Bunch):
pass
class TestBunch(TestCase):
def test_as_dict(self):
bunch = Bunch(a='a', b='b')
assert bunch == dict(a='a', b='b')
def test_as_obj(self):
bunch = Bunch(a='a', b='b')
... | _ is Bunch
def test_pickling_derived_class(sel | f):
derived = Derived(a='a', b='b')
dump = pickle.dumps(derived)
from_pickle = pickle.loads(dump)
assert derived == from_pickle
assert from_pickle.__class__ is Derived
|
smartsheet-platform/smartsheet-python-sdk | smartsheet/models/access_token.py | Python | apache-2.0 | 2,612 | 0 | # pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101
# Smartsheet Python SDK.
#
# Copyright 2018 Smartsheet.com, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.... | self._access_token = String()
self._expires_at = Timestamp()
self._expires_in = Number()
self._refresh_token = String()
self._token_type = String(
accept=self.allowed_values['token_type']
)
if props:
d | eserialize(self, props)
# requests package Response object
self.request_response = None
@property
def access_token(self):
return self._access_token.value
@access_token.setter
def access_token(self, value):
self._access_token.value = value
@property
def expires... |
ekivemark/my_device | bbp/bbp/settings.py | Python | apache-2.0 | 11,481 | 0.002178 | """
Django settings for bbp_oa project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# TIM... | to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datet... |
forkbong/qutebrowser | scripts/dev/update_version.py | Python | gpl-3.0 | 3,202 | 0.000312 | #!/usr/bin/env python3
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2018-2021 Andy Mender <andymenderunix@gmail.com>
# Copyright 2019-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
... | help="Only show commands to run post-release.")
args = parser.parse_args()
utils.change_cwd()
if not args.commands:
bump_version(args.bump)
show_commit()
import qutebrowser
version = qutebrowser.__version__
x_version = '.'.join([str(p) for p in qutebrowser.__version... | to create a new release:")
print("* git push origin; git push origin v{v}".format(v=version))
if args.bump == 'patch':
print("* git checkout master && git cherry-pick v{v} && "
"git push origin".format(v=version))
else:
print("* git branch v{x} v{v} && git push --set-upstream ... |
sfu-fas/coursys | oldcode/alerts/forms.py | Python | gpl-3.0 | 1,401 | 0.012848 | from django import forms
from django.forms.models import ModelForm
from .models import Alert, AlertType, AlertUpdate, AlertEmailTemplate
from django.template import Template, TemplateSyntaxError
class AlertTypeForm(ModelForm):
class Meta:
model = AlertType
exclude = ('hidden', 'config')
class Ema... | SyntaxError as e:
raise forms.ValidationError('Syntax error in template: ' + str(e))
return content
class ResolutionForm(ModelForm):
class Meta:
model = AlertUpdate
exclude = ('alert', 'update_type', 'created_at', 'hidden')
class EmailResoluti | onForm(ModelForm):
from_email = forms.CharField( label="From", required=True )
to_email = forms.CharField( label="To", required=True )
subject = forms.CharField( label="Subject", required=True )
class Meta:
model = AlertUpdate
fields = ('to_email', 'from_email', 'subject', 'comments', 'r... |
rosscdh/django-crocodoc | setup.py | Python | gpl-2.0 | 911 | 0.021954 | # -*- coding: utf-8 -*-
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because n | ow 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-crocodoc",
packages=['dj_crocodoc'],
description = ("Django app for int... | cense = "MIT",
keywords = "django crocdoc app",
url = "https://github.com/rosscdh/django-crocodoc",
install_requires = [
'crocodoc',
'django-braces',
'django-jsonfield',
'django-uuidfield',
'bunch',
'HTTPretty', # for testing
]
)
|
yorgenisparacare/tuconsejocomunal | tcc_consejocomunales/__openerp__.py | Python | gpl-3.0 | 943 | 0.002123 | # -*- coding: utf-8 -*-
{
'name': "Gestión de los Consejos Comunales",
'summary': """
Short (1 phrase/line) summary of th | e module's purpose, used as
subtitle on modules listing or apps.openerp.com""",
'description': """
Long description of module's purpose
""",
'author': "Your Company",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules listing
# Check... | ithub.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# for the full list
'category': 'Uncategorized',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base','usuarios_venezuela'],
# always loaded
'data': [
# 'security/ir.mod... |
djangobrasil/djangobrasil.org | src/djangobrasil/success_cases/moderator.py | Python | gpl-3.0 | 104 | 0.028846 | #from | moderation import moderation
#from .models import Su | ccessCase
#moderation.register(SuccessCase)
|
broderboy/ai-stager | stager/staging/management/commands/cleanupslides.py | Python | mit | 596 | 0.011745 |
from django.core.management.base imp | ort NoArgsCommand |
from django.conf import settings
class Command(NoArgsCommand):
help = "Removes CompSlides from the database that do not have matching files on the drive."
def handle_noargs(self, **options):
from stager.staging.models import CompSlide
import os.path
slides = CompSlide.objects.all()... |
sxjscience/tvm | python/tvm/relay/op/_transform.py | Python | apache-2.0 | 26,343 | 0.000835 | # 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 u... | inputs[0])]
_reg.register_schedule("argwhere", strategy.schedule_argwhere)
# scatter
@_reg.register_compute("scatter")
def compute_scatter(attrs, inputs, output_type):
"""Compute definition of sc | atter"""
return [topi.scatter(inputs[0], inputs[1], inputs[2], attrs.axis)]
_reg.register_schedule("scatter", strategy.schedule_scatter)
# scatter_add
@_reg.register_compute("scatter_add")
def compute_scatter_add(attrs, inputs, output_type):
"""Compute definition of scatter_add"""
return [topi.scatter_ad... |
sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/ete2/tools/phylobuild_lib/task/cog_selector.py | Python | mit | 10,562 | 0.008426 | # #START_LICENSE#################### | #######################################
#
#
# This file is part of the Environment for Tree Explor | ation program
# (ETE). http://etetoolkit.org
#
# ETE 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.
#
# ETE is distributed in the... |
alexforencich/python-ivi | ivi/rigol/rigolDS4014.py | Python | mit | 1,674 | 0.002987 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... | _digital_channel_count = 0
self._channe | l_count = self._analog_channel_count + self._digital_channel_count
self._bandwidth = 100e6
self._bandwidth_limit = {'20M': 20e6}
self._init_channels()
|
gurunars/dict-validator | dict_validator/fields/choice_field.py | Python | mit | 1,274 | 0 | from dict_validator import Field
class Choice(Field):
"""
Accept any type of input a | s long as it matches on of the choices
mentioned in the provided list.
:param choices: list of choices to match against
>>> fr | om dict_validator import validate, describe
>>> class Schema:
... field = Choice(choices=["ONE", "TWO", 3, 4])
>>> list(validate(Schema, {"field": "ONE"}))
[]
>>> list(validate(Schema, {"field": 4}))
[]
>>> list(validate(Schema, {"field": "4"}))
[(['field'], 'Not among the choice... |
cubicdaiya/neoagent | build/config.py | Python | bsd-3-clause | 660 | 0.00303 | # -*- coding: utf-8 -*-
import sys
cflags = [
'-std=c99',
'-Wall',
'-g',
'-O2',
# '-fno-strict-aliasing',
'-D_GNU_SOURC | E',
'-Wimplicit-function-declaration',
'-Wunuse | d-variable',
]
libs = [
'pthread',
'ev',
'json',
]
if sys.platform != 'darwin':
libs.append('rt')
includes = [
#'ext',
]
headers = [
'stdint.h',
'stdbool.h',
'unistd.h',
'sys/stat.h',
'sys/types.h',
'sys/socket.h',
'sys/un.h',
'sys/ioctl.h',
'arpa/inet.h',
... |
mhvk/astropy | astropy/cosmology/io/row.py | Python | bsd-3-clause | 5,402 | 0.002777 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import numpy as np
from astropy.table import Row
from astropy.cosmology.connect import convert_registry
from astropy.cosmology.core import Cosmology
from .mapping import from_mapping
def from_row(row, *, move_to_meta=False, cosmology=None... | ] = meta
# build cosmology from map
return from_mapping(mapping, move_to_meta=move_to_meta, cosmology=cosmology)
def to_row(cosmology, *args, cosmology_in_meta=False):
"""Serialize the cosmology into a `~astropy.table.Row`.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology` sub... | : bool
Whether to put the cosmology class in the Table metadata (if `True`) or
as the first column (if `False`, default).
Returns
-------
`~astropy.table.Row`
With columns for the cosmology parameters, and metadata in the Table's
``meta`` attribute. The cosmology class name... |
benzkji/django-cms | cms/wizards/views.py | Python | bsd-3-clause | 5,882 | 0 | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtool... | ed_data_for_step('0')
return data.get('language')
def get_success_url(self, instance):
entry = self.get_selected_entry()
language = self.get_origin_language()
success_url = entry.get_success_url(
obj=instance,
language=language,
)
return s | uccess_url
|
cwebster2/pyMeteo | pymeteo/cm1/hodographs/straight.py | Python | bsd-3-clause | 1,428 | 0.014706 | import numpy as np
from pymeteo import constants
from .. import OptionsWidget
class straight(OptionsWidget.OptionsWidget):
def __init__(self):
super(straight,self).__init__()
name = 'straight (linear increase)'
variables = [ ('z_constabv', '6000', 'm'),
('z_constblo', '0', 'm'... | ax')
sf = self.getOption('u_scaling')
vmax = self.getOption('v_max')
cx = self.getOption('u_adjust')
cy = self.getOption('v_adjust')
for k in range(len(z)):
if (z[k] < zdep0): # constant below this height
u[k] = 0
elif (z[k] < zdep1): # shear
u[k] = ((z[k]-zdep0)/(zdep... | u[k]* (1 + (sf-1)*((z[k]-zdep0)/(zdep1-zdep0)))
else: # constant section
u[k] = umax*sf
v[:] = vmax
u[:] = u[:] - cx
v[:] = v[:] - cy
#emit
return (z,u,v)
|
TheBB/badger | grevling/__init__.py | Python | agpl-3.0 | 38,535 | 0.001972 | from collections.abc import Sequence
from contextlib import contextmanager
from datetime import datetime
from difflib import Differ
import inspect
from itertools import product
import json
import multiprocessing
import operator
import os
from pathlib import Path
import pydoc
import re
import shlex
import shutil
import ... | = dict(data.get('constants', {}))
self.types = {
'_index': int,
'_logdir': str,
'_started': 'datetime64[ns]',
'_finished': 'datetime64[ns]',
}
self.types.update(data.get('types', {}))
# Guess types of parameters
for name, param i... | if any(name not in self.types for name in self.evaluables):
contexts = list(self.parameters.fullspace())
for ctx in contexts:
self.evaluate_context(ctx, verbose=False)
for name in self.evaluables:
if name not in self.types:
values ... |
consbio/gis-metadata-parser | gis_metadata/iso_metadata_parser.py | Python | bsd-3-clause | 32,703 | 0.003792 | """ A module to contain utility ISO-19115 metadata parsing helpers """
from _collections import OrderedDict
from copy import deepcopy
from frozendict import frozendict as FrozenOrderedDict
from parserutils.collections import filter_empty, reduce_value, wrap_value
from parserutils.elements import get_element_name, get... | arrierOfCharacteristi | cs/FC_FeatureAttribute'),
('_attr_def', '{_attr_base}/definitionReference/FC_DefinitionReference/definitionSource/FC_DefinitionSource'),
('_attr_src', '{_attr_def}/source/CI_Citation/citedResponsibleParty/CI_ResponsibleParty'),
# References to separate file ISO-19110 from: MD_Metadata
('_attr_citation'... |
ihmeuw/vivarium | src/vivarium/framework/resource.py | Python | bsd-3-clause | 12,125 | 0.000495 | """
===================
Resource Management
===================
This module provides a tool to manage dependencies on resources within a
:mod:`vivarium` simulation. These resources take the form of things that can
be created and utilized by components, for example columns in the
:mod:`state table <vivarium.framework.p... | _producer = self._resource_group_map[resource] | .producer
raise ResourceError(
f"Both {producer} and {other_producer} are registered as "
f"producers for {resource}."
)
self._resource_group_map[resource] = resource_group
def _get_resource_group(
self,
resource_ty... |
tensorflow/gan | tensorflow_gan/examples/progressive_gan/layers.py | Python | apache-2.0 | 9,208 | 0.005213 | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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 applicabl... | t_scaling=True,
scope='custom_conv2d',
reuse=None):
"""Custom conv2d layer.
In comparison with tf.layers.conv2d this implementation use the He initializer
to initialize convolutional kernel and the wei | ght scaling trick (if
`use_weight_scaling` is True) to equalize learning rates. See
https://arxiv.org/abs/1710.10196 for more details.
Args:
x: A `Tensor` of NHWC format.
filters: An int of output channels.
kernel_size: An integer or a int tuple of [kernel_height, kernel_width].
strides: A list o... |
WorldBank-Transport/open-transit-indicators | python/django/datasources/tasks/osm.py | Python | gpl-3.0 | 4,966 | 0.001611 | """Handles downloading and importing OSM Data"""
import os
import subprocess
import tempfile
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from django.db import connection
from datasources.models import OSMData, OSMDataProblem
from datasources.tasks.shapefile import E... | err_msg = 'Error obtaining SRID from gtfs_stops table'
logger.exception(err_msg)
handle_error(err_msg, e.message)
_, temp_filename = tempfile.mkstemp()
logger.debug('Generated tempfile %s to download osm data into', te | mp_filename)
osm_data.source_file = temp_filename
osm_data.status = OSMData.Statuses.DOWNLOADING
osm_data.save()
try:
response = requests.get(OSM_API_URL % bbox, stream=True)
logger.debug('Downloading OSM data from overpass/OSM api')
# Download OSM data
with open(temp_f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.