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 |
|---|---|---|---|---|---|---|---|---|
mdeff/ntds_2017 | projects/reports/terrorist_attacks/project/visualization.py | Python | mit | 8,333 | 0.022081 | """
Visualization module.
"""
import numpy as np
from matplotlib import animation
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from pca import create_handles
i... | ate animation
ani = animation.Fu | ncAnimation(fig, update, interval=1000, frames=frames, blit=True)
ani.save('visualization.mp4', writer = 'ffmpeg', fps=1, bitrate=-1)
plt.show()
def get_group_markers(attacks, group):
"""
Gives all the information about the markers for the
group passed in argument.
"""
data_given_group = attacks[attac... |
bitmaintech/p2pool | config.py | Python | gpl-3.0 | 545 | 0 |
TestNet = False
Address = "1MjeEv3WDgycrEaaNeSESrWvRfkU6s81TX"
workerEndpoint = "3333"
DonationPercentage = 0.0
Upnp = True
BitcoindConfigPath = "/opt/bitcoin/bitcoindata/bitcoin.conf"
WORKER_STATUS_REFRESH_TIME = 10
dbService = {}
worker | Status = {}
NodeService = {
'authentication': 'http://127.0.0.1:8080/service/node/authentication.htm'
}
DbOptions = {
't | ype': 'sql',
'engine': 'mysql',
'dbopts': {
'host': '127.0.0.1',
'db': 'antpooldb',
'user': 'antpool',
'password': 'antpool',
}
}
|
dmpayton/django-flanker | tests/settings.py | Python | mit | 609 | 0 | DEBUG = False
TEMPLATE_DEBUG = DEBUG
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-US'
SITE_ID = 1
USE_L10N = True
USE_TZ = | True
SECRET_KEY = 'local'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends | .locmem.LocMemCache',
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfile... |
wgwoods/anaconda | translation-canary/translation_canary/translated/test_markup.py | Python | gpl-2.0 | 2,842 | 0.002463 | # Check translations of pango markup
#
# This will look for translatable strings that appear to contain markup and
# check that the markup in the translation matches.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subjec... | .translated_entries():
if is_markup(entry.msgid):
# If this is a plural, check each of the plural translations
if entry.msgid_plural:
xlations = entry.msgstr_plural
else:
xlations = {None: entry.msgstr}
| for plural_id, msgstr in xlations.items():
# Check if the markup is valid at all
try:
# pylint: disable=unescaped-markup
ET.fromstring('<markup>%s</markup>' % msgstr)
except ET.ParseError:
if entry.msgi... |
nickmckay/LiPD-utilities | Python/lipd/retreive_dataset.py | Python | gpl-2.0 | 12,806 | 0.003983 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:25:09 2018
@author: deborahkhider
Script to batch download LiPD files from the wiki after query
"""
# 1. Query the wiki (note this is taken directly from the Jupyter Notebook on
# GitHub) The query can be changed but doesn't matter in the gr... | ort requests
import sys
import urllib.request
import os
# %% 1.1 Query terms
# By archive
archiveT | ype = ["marine sediment", "Marine Sediment"]
# By variable
proxyObsType = ["Mg/Ca", "Mg Ca"]
infVarType = ["Sea Surface Temperature"]
# By sensor
sensorGenus = ["Globigerinoides"]
sensorSpecies = ["ruber"]
# By interpretation
interpName = ["temperature", "Temperature"]
interpDetail = ["sea surface"]
# By Age
ageUni... |
Kjir/papyon | papyon/gnet/proxy/SOCKS4.py | Python | gpl-2.0 | 4,827 | 0.002486 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... | only handles INET address family"
assert(client.type == SOCK_STR | EAM), \
"SOCKS4 CONNECT only handles SOCK_STREAM"
assert(client.status == IoStatus.CLOSED), \
"SOCKS4Proxy expects a closed client"
AbstractProxy.__init__(self, client, proxy_infos)
self._transport = TCPClient(self._proxy.host, self._proxy.port)
self._tra... |
don-github/edx-platform | lms/djangoapps/certificates/views/webview.py | Python | agpl-3.0 | 23,455 | 0.00469 | """
Certificate HTML webview.
"""
from datetime import datetime
from uuid import uuid4
import logging
import urllib
from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.template import RequestContext
from django.utils.translation import ugettext ... | llname = user.profile.name
platform_name = microsite.get_value("platform_name", settings.PLATFORM_NAME)
certificate_type = context.get('certificate_type')
partner_short_name = course.org
partner_long_name = None
or | ganizations = organization_api.get_course_organizations(course_id=course.id)
if organizations:
#TODO Need to add support for multiple organizations, Currently we are interested in the first one.
organization = organizations[0]
partner_long_name = organization.get('name', partner_long_name)
... |
edx/edx-platform | common/djangoapps/third_party_auth/apps.py | Python | agpl-3.0 | 919 | 0.003264 | # lint-amnesty, pylint: disable=missing-module-docstring
from django.apps import AppConfig
from django.conf import settings
class ThirdPartyAuthConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class-docstring
| name = 'common.djangoapps.third_party_auth'
verbose_name = "Third-party authentication"
def ready(self):
# To override the settings before loading social_django.
if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
| self._enable_third_party_auth()
def _enable_third_party_auth(self):
"""
Enable the use of third_party_auth, which allows users to sign in to edX
using other identity providers. For configuration details, see
common/djangoapps/third_party_auth/settings.py.
"""
... |
goinnn/deldichoalhecho | ddah_web/views.py | Python | gpl-3.0 | 3,903 | 0.000769 | from django.template.response import TemplateResponse
from ddah_web.models import DDAHInstanceWeb, DdahFlatPage
from django.views.generic.detail import DetailView
from pystache import Renderer
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
import markdown
from django.utils.safestrin... | edError("Subclasses should implement this!")
def get_template(self):
raise NotImplementedError("Subclasses should implement this!")
def get_partials(self):
template = self.get_templat | e()
return {
"head": template.head,
"header": template.header,
"style": template.style,
"footer": template.footer,
}
def get_content(self):
return self.get_template().content
@property
def rendered_content(self):
renderer = Re... |
fasaas/owne-coursera | documentation/Crafting-Quality-Code/Doctest/vowels.py | Python | apache-2.0 | 653 | 0 | def collect_vowels(s):
""" (str) -> str
Return the vowels (a, e, i, o, and u) from s.
>>> collect_vowels('Happy Anniversary!')
'aAiea'
>>> col | lect_vowels('xyz')
''
"""
vowels = ''
for char in s:
if char in 'aeiouAEIOU':
vowels = vowels + char
return | vowels
def count_vowels(s):
""" (str) -> int
Return the number of vowels (a, e, i, o, and u) in s.
>>> count_vowels('Happy Anniversary!')
5
>>> count_vowels('xyz')
0
"""
num_vowels = 0
for char in s:
if char in 'aeiouAEIOU':
num_vowels = num_vowels + 1
... |
pygeo/pycmbs | pycmbs/benchmarking/models/mpi_esm.py | Python | mit | 41,720 | 0.004938 | # -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
from cdo import Cdo
from pycmbs.data import Data
import tempfile as tempfile
import copy
import glob
import os
import sys
import numpy as np
from pycmbs.benchmarking ... | shift_lon=self.shift_lon,
mask=ls_mask.data.data)
return albedo
def get_tree_fraction(self, interval='season'):
"""
todo implement this for data from a real run !!!
"""
if interval != 'season':
raise ValueError('Other temporal samplin... | ib/python/pyCMBS/framework/external/vegetation_benchmarking/VEGETATION_COVER_BENCHMARKING/example/historical_r1i1p1-LR_1850-2005_forest_shrub.nc'
v = 'var12'
tree = Data(filename, v, read=True,
label='MPI-ESM tree fraction ' + self.experiment, unit='-', lat_name='lat', lon_name='lon'... |
Ghalko/waterbutler | waterbutler/providers/figshare/provider.py | Python | apache-2.0 | 13,916 | 0.001653 | import http
import json
import asyncio
import aiohttp
import oauthlib.oauth1
from waterbutler.core import streams
from waterbutler.core import provider
from waterbutler.core import exceptions
from waterbutler.core.path import WaterButlerPath
from waterbutler.providers.figshare import metadata
from waterbutler.provid... | return wbpath
@asyncio.coroutine
def _assert_contains_article(self, article_id):
articles_json = yield from self._list_articles()
try:
return next(
each for each in articles_json
if each['id'] == int(article_id)
)
except StopItera... | raise exceptions.ProviderError(
'Article {0} not found'.format(article_id),
code=http.client.NOT_FOUND,
)
@asyncio.coroutine
def _make_article_provider(self, article_id, check_parent=True):
article_id = str(article_id)
if check_parent:
... |
waseem18/bedrock | bin/update/deploy_base.py | Python | mpl-2.0 | 5,260 | 0.00019 | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELI... | s = {'x-api-key': NEW_RELIC_API_KEY}
try:
request = urllib2.Request(NEW_RELIC_URL, data, headers)
urllib2.urlopen(request)
except urllib.URLError as exp:
print 'Error notifying New Relic: {0}'.format(exp)
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
comma... | ate_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def deploy(ctx):
commands['checkin_changes']()
commands['deploy_app']()
commands['ping_newrelic']()
@task
def update_bedrock(ctx, tag):
"""Do typical bedrock update"""
comm... |
mrmuxl/keops | keops/middleware/__init__.py | Python | agpl-3.0 | 85 | 0.011765 | from .db import SingleDBMiddleware, MultiDBMidd | leware, get_db, g | et_user, get_request
|
arthurfurlan/django-shortim | src/shortim/migrations/0002_auto__add_field_shorturl_collect_date__add_field_shorturl_title__add_f.py | Python | gpl-3.0 | 2,839 | 0.007045 | # encoding: 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 field 'ShortURL.collect_date'
db.add_column('shortim_shorturl', 'collect_date', self.gf('django.d... | ango.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'title': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'db_index': 'True'})
},
... | 'object_name': 'ShortURLHit'},
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'remote_user': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'... |
HybridF5/jacket | jacket/tests/compute/unit/virt/hyperv/test_livemigrationops.py | Python | apache-2.0 | 5,845 | 0 | # Copyright 2014 Cloudbase Solutions Srl
# 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 r... | ock_disconnect_volumes.assert_called_once_with(
mock.sentinel.block_device_info)
self._livemigrops._pathutils.get_instance_dir.assert_called_once_with(
mock.sentinel.instance.name, create_dir=False, remove_dir=True)
| @mock.patch('compute.virt.hyperv.vmops.VMOps.log_vm_serial_output')
def test_post_live_migration_at_destination(self, mock_log_vm):
mock_instance = fake_instance.fake_instance_obj(self.context)
self._livemigrops.post_live_migration_at_destination(
self.context, mock_instance, network_i... |
mesosphere/marathon | tests/performance/apps.py | Python | apache-2.0 | 445 | 0.011236 | import requests
i | mport json
def generate_apps():
apps = [{'id': '/app-{}'.format(i), 'cmd': 'sleep 3600', 'cpus': 0.1, 'mem': 32, 'instances': 0} for i in range(1000)]
groups = {'id': '/', | 'groups': [], 'apps': apps}
return groups
def main():
apps = generate_apps()
r = requests.put("http://localhost:8080/v2/groups?force=true", json=apps)
print(r.text)
r.raise_for_status()
if __name__ == "__main__":
main()
|
bygreencn/DIGITS | plugins/data/imageGradients/digitsDataPluginImageGradients/data.py | Python | bsd-3-clause | 3,492 | 0.001145 | # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from digits.utils import subclass, override, constants
from digits.extensions.data.interface import DataIngestionInterface
from .forms import DatasetForm, InferenceForm
import numpy as np
import os
TEMPLATE = "temp... | , context)
@override
def get_inference_form(self):
return InferenceForm()
@staticmethod
@override
def get_inference_template(form):
extension_dir = os.path.dirname(os.path.abspath(__file__))
template = open(os.path.join(extension_dir, INFERENCE_TEMPLATE), "r").read()
... | ide
def get_title():
return "Gradients"
@override
def itemize_entries(self, stage):
count = 0
if self.userdata['is_inference_db']:
if stage == constants.TEST_DB:
if self.test_image_count:
count = self.test_image_count
e... |
rezoo/chainer | tests/chainer_tests/iterators_tests/test_iterator_compatibility.py | Python | mit | 2,915 | 0 | from __future__ import division
import unittest
import itertools
import numpy
from chainer import iterators
from chainer import serializer
from chainer import testing
class DummySerializer(serializer.Serializer):
def __init__(self, target):
super(DummySerializer, self).__init__()
self.target = ... | y.ndarray):
numpy.copyto(value, self.target[key])
else:
value = type(value)(numpy.asarray(self.target[key]))
return value
@testing.parameterize(*testing.product({
'n_prefetch': [1, 2],
'share | d_mem': [None, 1000000],
}))
class TestIteratorCompatibility(unittest.TestCase):
def setUp(self):
self.n_processes = 2
self.options = {'n_processes': self.n_processes,
'n_prefetch': self.n_prefetch,
'shared_mem': self.shared_mem}
def test_iterato... |
bhallen/pyparadigms | hypothesize.py | Python | bsd-3-clause | 15,896 | 0.006102 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## Based on learner.js (by Blake Allen and Michael Becker)
import itertools
import collections
from collections import defaultdict
import pdb
import phoment
class Change(object):
def __init__(self, change_type, position, input_material, output_material):
... | _position+(i*2)] != s:
raise Exception('Deletion incompatible with base: no {} to delete.'.format(s))
changed_derivative[change_pos | ition+(i*2)] = None
if change.change_type == 'mutate':
for i, s in enumerate(change.output_material):
if orientation == 'source' and current_base[change_position+(i*2)] != chang |
portfoliome/foil | tests/test_logger.py | Python | mit | 936 | 0 | import json
import unitte | st
from logging import INFO, LogRecord
from foil.logger import JSONFormatter
class TestLogFormatter(unittest.TestCase):
def test_json_formatter(self):
name = 'name'
line = 42
| module = 'some_module'
func = 'some_function'
msg = {'content': 'sample log'}
log_record = LogRecord(
name, INFO, module, line, msg, None, None, func=func
)
formatter = JSONFormatter()
log_result = formatter.format(log_record)
result = json.lo... |
bjpop/complexo_pipeline | src/pipeline.py | Python | bsd-3-clause | 6,819 | 0.002346 | '''
Build the pipeline workflow by plumbing the stages together.
'''
from ruffus import Pipeline, suffix, formatter, add_inputs, output_from
from stages import Stages
def make_pipeline(state):
'''Build the pipeline by constructing stages and connecting them together'''
# Build an empty pipeline
pipeline ... | .follows('snp_recalibrate_gatk'))
# Apply INDEL recalibration using GATK
(pipeline.transform(
task_func=stages.apply_indel_recalibrate_gatk,
name='apply_indel_recalibrate_gatk',
input=output_from('genotype_gvcf_gatk'),
filter=suffix('.genotyped.vcf'),
add_inputs=a... | ibrate_gatk'))
# Combine variants using GATK
(pipeline.transform(
task_func=stages.combine_variants_gatk,
name='combine_variants_gatk',
input=output_from('apply_snp_recalibrate_gatk'),
filter=suffix('.recal_SNP.vcf'),
add_inputs=add_inputs(['PCExomes.recal_INDEL.vcf'])... |
Chrisplus/HeyoDict | Dict.py | Python | gpl-2.0 | 2,929 | 0.034141 | #! /user/bin/python
#! -*- coding: utf-8 -*-
import sys
import urllib, urllib2
import json
"""
Reversion HeyooDic
Transfer from unoffical API to offical API
Chrisplus
2014-6
"""
# Key and name
url = "http://fanyi.youdao.com/openapi.do?%s"
keyFrom = "SunnyArtStudio"
key = "1884243682"
dataType = "data"
docType = "jso... | a['web']
#Then show word and its phonetic
basic_meaning = words + bcolors.HEADER + " [" + phonetic + "]" + bcolors.ENDC
#Then show the explainations from dict
print '======== ' + basic_meaning + ' ========'
for ex in explains:
print ' ' + bcolors.OKGREEN + ex + bcolors.ENDC + ' '
print '======== ' + 'more ref... | ors.ENDC + ' '
if __name__ == "__main__":
raw = ""
while True:
raw = raw_input('=> ')
if raw == core_command_quit:
break;
else:
main(['-d',raw])
|
RedHatInsights/insights-core | insights/parsers/tests/test_docker_inspect.py | Python | apache-2.0 | 10,303 | 0.002038 | import pytest
import doctest
from insights.parsers import docker_inspect, SkipException
from insights.tests import context_wrap
DOCKER_CONTAINER_INSPECT = """
[
{
"Id": "97d7cd1a5d8fd7730e83bb61ecbc993742438e966ac5c11910776b5d53f4ae07",
"Created": "2016-06-23T05:12:25.433469799Z",
"Path": "/bin/bash",
... | : "docker-253:0-71431059-97d7cd1a5d8fd7730e83bb61ecbc993742438e966ac5c11910776b5d53f4ae07",
"DeviceSize": "107374182400"
}
},
"Mounts": [],
"Config": {
"Hostname": "97d7cd1a5d8f",
"Domainname": "",
"User": "root",
"AttachStdi | n": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"container=docker",
"PKGM=yum",
"PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin"
],
"Cmd": [
... |
srome/jacksearch | search.py | Python | apache-2.0 | 922 | 0.007592 | # Copyright (C) 2016 Scott Rome. 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 applicable law ... | # See the License for the specific language governing permissions and
# limitations under the License.
import glob
class Searcher:
ALLOWED_FILE_TYPES = ['*.*pg','*.png','*.tif*']
@staticmethod
def search_from_dir(base_dir):
files = []
for file_type in Searcher.ALLOWED_FILE_TYPES:
... | .extend(glob.glob('%s/**/%s' % (base_dir,file_type), recursive=True))
return files
|
rbuffat/pyidf | tests/test_coilheatingdxvariablespeed.py | Python | apache-2.0 | 38,214 | 0.005548 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.coils import CoilHeatingDxVariableSpeed
log = logging.getLogger(__name__)
class TestCoilHeatingDxVariableSpeed(unittest.TestCase):
def setUp(self):
self.fd, self.pa... | obj.number_of_speeds = var_number_of_speeds
# integer
var_nominal_speed_level = 5
obj.nominal_speed_level = var_nominal_speed_level
# real
var_rated_heating_capacity_at_selected_nominal_speed_level = 6.6
obj.rated_heating_capacity_at_selected_nominal_speed_level = ... | ate_at_selected_nominal_speed_level = var_rated_air_flow_rate_at_selected_nominal_speed_level
# object-list
var_energy_part_load_fraction_curve_name = "object-list|Energy Part Load Fraction Curve Name"
obj.energy_part_load_fraction_curve_name = var_energy_part_load_fraction_curve_name
# ... |
jakereps/qiime-workshops | config/urls/callback.py | Python | bsd-3-clause | 890 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | debug__/', include(debug_toolbar.urls)),
url(r'^400/$', default_views.bad_request),
url(r'^403/$', default_views.permission_denied),
url(r'^404/$', default_views.page_not_found),
url(r'^500/$', def | ault_views.server_error),
]
|
jaswal72/hacker-rank | Python/Math/Polar_Coordinates.py | Python | mit | 69 | 0.014493 | impo | rt cmath
n = complex(input())
print(abs(n))
print(cmath.phase( | n)) |
robofab-developers/fontParts | Lib/fontParts/base/component.py | Python | mit | 11,222 | 0.000089 | from fontTools.misc import transform
from fontParts.base import normalizers
from fontParts.base.errors import FontPartsError
from fontParts.base.base import (
BaseObject,
TransformationMixin,
InterpolationMixin,
PointPositionMixin,
SelectionMixin,
IdentifierMixin,
dynamicProperty,
refere... | andles backwards compatibility with
# point pens that have not been upgraded
# to point pen protocol 2.
try:
pen.addComponent(self.baseGlyph, self.transformation,
identifier=self.identifier, **kwargs)
except TypeError:
pen.addComponent... | , self.transformation, **kwargs)
# --------------
# Transformation
# --------------
def _transformBy(self, matrix, **kwargs):
"""
Subclasses may override this method.
"""
t = transform.Transform(*matrix)
transformation = t.transform(self.transformation)
... |
r-singh/Test2 | webapp_project/website/migrations/0003_initial.py | Python | mit | 351 | 0.005698 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from djan | go.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
|
models = {
}
complete_apps = ['website'] |
yesudeep/tisshrmlr | app/jinja2/tests/test_debug.py | Python | mit | 1,268 | 0 | # -*- coding: utf-8 -*-
"""
Test debug interface
~~~~~~~~~~~~~~~~~~~~
Tests the traceback rewriter.
:copyright: (c) 2009 by the Jinja Team.
:license: BSD.
"""
from jinja2 import Environment
from test_loaders import filesystem_loader
env = Environment(loader=filesystem_loader)
def test_runtime_e... | \\syntaxerror.html", line 4
{% endif %}
'''
def test_regular_syntax_error():
'''
>>> from jinja2.exceptions import TemplateSyntaxE | rror
>>> raise TemplateSyntaxError('wtf', 42)
Traceback (most recent call last):
...
File "<doctest test_regular_syntax_error[1]>", line 1, in <module>
raise TemplateSyntaxError('wtf', 42)
TemplateSyntaxError: wtf
line 42
'''
|
astrobin/astrobin | astrobin/auth.py | Python | agpl-3.0 | 1,134 | 0.002646 | from annoying.functions import get_object_or_None
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
# Class to permit the authentication using email or username, with case sensitive and insensitive matches.
class CustomBackend(ModelBack... | gs):
UserModel = get_user_model()
case_sensitive = UserModel.objects.filter(Q(username__exact=username) | Q(email | __iexact=username)).distinct()
case_insensitive = UserModel.objects.filter(Q(username__iexact=username) | Q(email__iexact=username)).distinct()
user = None
if case_sensitive.exists():
user = case_sensitive.first()
elif case_insensitive.exists():
count = case_inse... |
patrickbeeson/diy-trainer | diytrainer/diytrainer/preview_urls.py | Python | mit | 761 | 0.001314 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic import TemplateView
from views import RobotsView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_vi... | RobotsView.as_view()),
url(r'^', include('g | uides.urls')),
)
# Uncomment the next line to serve media files in dev.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
... |
jasonge27/picasso | python-package/pycasso/libpath.py | Python | gpl-3.0 | 1,608 | 0.003731 | # coding: utf-8
"""Find the path to picasso dynamic library files."""
import os
import platform
import sys
class PicassoLibraryNotFound(Exception):
"""Error thrown by when picasso is not found"""
pass
def find_lib_path():
"""Find the path to picasso dynamic library files.
:return: List of all found ... | ibpicasso.so') for p in dll_path] \
+[os.path.join(p, 'libpicasso.dylib') for p in dll_path]
lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
if not lib_path:
print('Library file does not exist. Need to be updated!')
return lib_path
# From... | issues, most of installation errors come from machines w/o compilers
if not lib_path and not os.environ.get('PICASSO_BUILD_DOC', False):
raise PicassoLibraryNotFound(
'Cannot find Picasso Library in the candidate path, ' +
'did you install compilers and make the project in root path... |
bartdag/recodoc2 | recodoc2/apps/doc/admin.py | Python | bsd-3-clause | 2,534 | 0.001184 | from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.contenttypes import generic
from codebase.models import SingleCodeReference, CodeSnippet
from doc.models import Document, Page, Section, DocDiff, SectionChanger,\
LinkChange
class SingleCodeReferenceInline(generic.Gen... | Inline):
model = Page
extra = 0
ordering = ('title',)
class DocumentAdmin(admin.ModelAdmin):
inlines = [PageInline]
class SectionChangerInline(admin.StackedInline):
model = SectionChanger
fields = ('section_from', 'section_to', 'words_from', 'words_to',
'change')
readonly_fie... | only_fields = ('removed_pages', 'added_pages', 'removed_sections',
'added_sections')
inlines = [SectionChangerInline]
class LinkChangeAdmin(admin.ModelAdmin):
read_only_fields = ('link_from', 'link_to')
list_filter = ('diff', 'from_matched_section')
link_display = ('link_from', 'link_to', ... |
santidltp/viprcommand | ViPRCommand/bin/CLIInputs.py | Python | mit | 1,681 | 0.009518 | """
Copyright EMC Corporation 2015.
Distributed under the MIT License.
(See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
"""
""" Class to store parsed WADL and XSD data. """
class CLIInputs:
wadl_context = dict()
xsd_elements_dict = dict()
unknown_xsd_elements_dict = dict()
... | curs=0, max_occurs=1, base=None, ref=None):
self.name = name
self.type = type
self.min_occurs = min_occurs
self.max_occurs = max_occurs
self.base = base
| self.ref = ref
self.children = None
def __str__(self):
return 'name: %s type: %s base: %s ref: %s' %(self.name, self.type, self.base, self.ref)
def __repr__(self):
return 'name: %s type: %s base: %s ref: %s' %(self.name, self.type, self.base, self.ref)
|
scjrobertson/xRange | kalman/sensor_array.py | Python | gpl-3.0 | 2,075 | 0.004337 | """
Module containing the SensorArray class which
models an array of FMCW radars.
@author: scj robertson
@since: 03/04/16
"""
import numpy as np
C = 3e8
class SensorArray(object):
'''
Class for representing an array of identical FMCW radars. For viable multilateration
four or more sensors must always b... | ValueError
If the are less than four distinct sensor locations.
'''
def __init__(self, sensor_locatio | ns, f_c, del_r, r_max, del_v, v_max):
self.K, _ = sensor_locations.shape
if (self.K < 4):
ValueError('There must be K > 4 distinct sensor locations')
self.f_c = f_c
self.del_r = del_r
self.r_max = r_max
self.del_v = del_v
self.v_max =... |
openego/oeplatform | dataedit/migrations/0009_tablerevision_path.py | Python | agpl-3.0 | 488 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-04 15:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("dataedit", "0008_auto_2 | 0170504_1651")]
operations = [
migra | tions.AddField(
model_name="tablerevision",
name="path",
field=models.CharField(default="", max_length=100),
preserve_default=False,
)
]
|
ohaut/ohaut-core | ohaut/config.py | Python | gpl-3.0 | 1,064 | 0.00188 | from oslo_config import cfg
OPTS = [
cfg.StrOpt('openhab_config_dir',
default='/opt/openhab/config',
help='The open | hab configuration path'),
cfg.StrOpt('mqtt_id',
default='mosquitto',
help='The mqtt id inside openhab config'
'to connect the items to'),
]
MQTT_OPTS = [
cfg.HostnameOpt('server',
default='localhost',
help='MQTT server address'),
... | help='MQTT connection username'),
cfg.StrOpt('password',
default=None,
help='MQTT connection username')]
_conf = None
def get():
"""Load the configuration and return the CONF object."""
global _conf
if _conf is None:
cfg.CONF.register_opts(OPTS)
cfg.CONF... |
lcostantino/healing-os | external/ceilometer/compute/virt/libvirt/inspector.py | Python | apache-2.0 | 8,169 | 0 | #
# Copyright 2012 Red Hat, Inc
#
# Author: Eoghan Glynn <eglynn@redhat.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | nstance_name):
domain = self._lookup_by_name(instance_name)
state = domain.info()[0]
if state == libvirt.VIR_DOMAIN_SHUTOFF:
LOG.warn(_('Failed to inspe | ct disks of %(instance_name)s, '
'domain is in state of SHUTOFF'),
{'instance_name': instance_name})
return
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
f... |
todaychi/hue | desktop/core/ext-py/thrift-0.9.1/src/transport/TSocket.py | Python | apache-2.0 | 6,194 | 0.008718 | #
# 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... | self.port,
self._socket_family,
socket.SOCK_STREAM,
0,
socket.AI_PASSIVE | socket.AI_ADDRCONFIG)
def close(self):
if self.handle:
self.han | dle.close()
self.handle = None
class TSocket(TSocketBase):
"""Socket implementation of TTransport base."""
def __init__(self, host='localhost', port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC):
"""Initialize a TSocket
@param host(str) The host to connect to.
@param port(int) The ... |
alexcasgarcia/GCJ | 2008/1A/MinimumScalarProduct/MinScalarProduct.py | Python | mit | 1,138 | 0.02812 | def MinScalarProduct(vector1,vector2,case):
vector1.sort(reverse=False)
vector2.sort(reverse=True)
scalarProduct=0
i=0
while i<len(vector1):
scalarProduct+=vector1[i]*vector2[i]
i+=1
return "Case #"+str(case)+": "+str(scalarProduct) | +"\n"
def readTestFile(inputFile,outputFile):
r = open(outputFile, 'w')
with open(inputFile) as f:
i=0
n=1
vector1=[]
vector2=[]
for line in f:
if i==0:
| NumberOfRecords=int(line)
else:
if (i+2)%3==0:
vectorLength=int(line.strip('\n'))
else:
textInput=line.strip('\n')
stringList=textInput.split()
integerList=[int(x) for x in stringList]
... |
javierj/kobudo-katas | Kata-RestConsumer/DjangoGIndexDemo/gindex/gindex_logic/gindex.py | Python | apache-2.0 | 1,609 | 0.002486 | __author__ = 'Javier'
import urlli | b.request
import json
class Repo(object):
def __init__(self, fork, stars, watchers):
self._fork = int(fork)
self._stars = int(stars)
self._watchers = int(watchers)
@property
def forks(self):
return self._fork
@property
def stars(self):
return self._stars
... | repo_info.forks *3) + repo_info.stars + repo_info.watchers
class RepositoryService(object):
def get_repos_from(self, user):
url = "https://api.github.com/users/"+user+"/repos"
connection = urllib.request.urlopen(url)
result_raw = connection.read().decode('utf-8')
repos = json.loads... |
Nukesor/Pueuew | pueue/client/factories.py | Python | mit | 2,761 | 0.001811 | import pickle
from pueue.client.socket import connect_socket, receive_data, process_response
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which ... | type of payload this should be. This determines
| as what kind of instruction this will be interpreted by the daemon.
Returns:
function: The created function.
"""
def communicate(body={}, root_dir=None):
client = connect_socket(root_dir)
body['mode'] = command
# Delete the func entry we use to call the correct function... |
sciCloud/OLiMS | fields/file_field.py | Python | agpl-3.0 | 449 | 0.01559 | from openerp import fields
from fields_utils im | port direct_mapper
class FileField(fields.Binary):
# type = 'binary' will auto inherit from the base class of Binary
| def __bika_2_odoo_attrs_mapping(self):
direct_mapper(self, 'description', 'help')
def _setup_regular_base(self, model):
super(FileField, self)._setup_regular_base(model)
self.__bika_2_odoo_attrs_mapping()
pass |
meteoswiss-mdr/precipattractor | pyscripts/radar_extrapolation.py | Python | gpl-3.0 | 15,346 | 0.015379 | #!/usr/bin/env python
from __future__ import division
from __future__ import print_function
# General libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import sys
import argparse
import datetime
import getpass
import os
import time
# OpenCV
import cv2
#... | timeAccumMin
timeAccum24hStr = '%05i' % (24*60)
######## GIS stuff
# Limits of CCS4 domain
Xmin = 255000
Xmax = 965000
Ymin = -160000
Ymax = 480000
allXcoords = np.arange(Xmin,Xmax+resKm*1000,resKm*1000)
allYcoords = np.arange(Ymin,Ymax+resKm*1000,resKm*1000)
# Shapefile filename
fileNameShapefile = ... | Name + "/pyscripts/shapefiles/CHE_adm0.shp"
proj4stringWGS84 = "+proj=longlat +ellps=WGS84 +datum=WGS84"
proj4stringCH = "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \
+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs"
######## Colormaps
co... |
gsingers/rtfmbot | src/python/run.py | Python | mit | 2,559 | 0.004299 | import ConfigParser
import sys, traceback
from slackclient import SlackClient
from chatterbot import ChatBot
import os
from os import listdir
from os.path import isfile, join
from chatterbot.trainers import ChatterBotCorpusTrainer
config = ConfigParser.SafeConfigParser({"host": "searchhub.lucidworks.com", "port":... | e in files:
print "Training on " + file
chatbot.t | rain("training." + file.replace(".json", ""))
# Train based on english greetings corpus
chatbot.train("chatterbot.corpus.english")
# Train based on the english conversations corpus
#chatbot.train("chatterbot.corpus.english.conversations")
print "Starting Chatbot"
while True:
try:
bot_input = chatbot.get_re... |
breathe-free/breathe-see | example_publisher/__main__.py | Python | gpl-3.0 | 10,411 | 0.0073 | #!/usr/bin/env python
import socket
import sys
import os
import time
import random
import csv
import json
import random
from sentence_generator import make_sentence
from copy import deepcopy
from subprocess import check_output
# csv file columns are timestamp, pressure, CO2, ...
SAMPLE_DATA_DIR = os.path.join(os.pat... | TH = '/tmp/lucidity.socket'
TIME_WARP = float(os.environ.get('TIME_WARP', 1.0))
MAX_LINES_AT_ONCE = int(os.environ.get('MAX_LINES_AT_ONCE', 1))
EMIT_RANDOM_MSGS = bool(os.environ.get('GIBBERISH', False))
class SocketNotFound(Exception):
pass
# Read in data from the example csv file
datapoints = []
... | |
rbramwell/pulp | server/pulp/server/event/http.py | Python | gpl-2.0 | 2,330 | 0.001717 | """
Forwards events to a HTTP call. The configuration used by this notifier
is as follows:
url
Full URL to contact with the event data. A POST request will be made to this
URL with the contents of the events in the body.
Eventually this should be enhanced to support authentication credentials as well.
"""
import... | ection(scheme, server)
# Pr | ocess authentication
if 'username' in notifier_config and 'password' in notifier_config:
raw = ':'.join((notifier_config['username'], notifier_config['password']))
encoded = base64.encodestring(raw)[:-1]
headers['Authorization'] = 'Basic ' + encoded
connection.request('POST', '/' + path... |
tonysyu/deli | deli/stylus/rect_stylus.py | Python | bsd-3-clause | 543 | 0 | from en | able.api import ColorTrait
from | .base_patch_stylus import BasePatchStylus
class RectangleStylus(BasePatchStylus):
""" A Flyweight object for drawing filled rectangles.
"""
edge_color = ColorTrait('black')
fill_color = ColorTrait('yellow')
def draw(self, gc, rect):
with gc:
gc.set_stroke_color(self.edge_co... |
mwv/babycircle | visualization/colors.py | Python | gpl-3.0 | 1,039 | 0.006737 | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for gen | erating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import | math
def _hsv_to_rgb(h,f):
"""Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1-f, v
elif h == 4:
ret... |
argriffing/numpy | numpy/ma/tests/test_core.py | Python | bsd-3-clause | 167,699 | 0.00102 | # pylint: disable-msg=W0401,W0511,W0611,W0612,W0614,R0201,E1102
"""Tests suite for MaskedArray & subclassing.
:author: Pierre Gerard-Marchant
:contact: pierregm_at_uga_dot_edu
"""
from __future__ import division, absolute_import, print_function
__author__ = "Pierre GF Gerard-Marchant"
import warnings
import pickle
i... | dArray(data)
assert_equal(dma_1.mask, data.mask)
dma_2 = MaskedArray(dma_1)
assert_equal(dma_2.mask, dma_1.mask)
dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6)
fail_if_equal(dma_3.mask, dma_1.mask)
x = array([1, 2, 3], mask=True)
assert_equal(x._mask, [True, T... | (np.may_share_memory(x.mask, y.mask))
y = array([1, 2, 3], mask=x._mask, copy=True)
assert_(not np.may_share_memory(x.mask, y.mask))
def test_creation_with_list_of_maskedarrays(self):
# Tests creating a masked array from a list of masked arrays.
x = array(np.arange(5), mask=[1, 0, 0... |
mephizzle/wagtail | wagtail/wagtailcore/management/commands/fixtree.py | Python | bsd-3-clause | 5,041 | 0.004761 | import operator
import functools
from optparse import make_option
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Q
from django.utils import six
from wagtail.wagtailcore.models import Page
class Comma... | correct depth value found for pages: %s" % self.numberlist_to_string(bad_depth))
if bad_numchild:
self.stdout.write("Incorrect numchild value found for pages: %s" % self.numberlist_to_string(bad_numchild))
if bad_depth or bad_numchild:
Page.fix_tree(destructive=False)
... | ludes pages that are
# missing an immediate parent; descendants of orphans are not included.
# Deleting only the *actual* orphans is a bit silly (since it'll just create
# more orphans), so generate a queryset that contains descendants as well.
orphan_paths = Page.objects... |
AASHE/hub | hub/apps/content/management/commands/import_conf_presentations_2020.py | Python | mit | 5,266 | 0.001709 | import csv
import os
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.utils import timezone
from hub.apps.content.models import Author
from hub.apps.content.types.presentations import Presentation
from hub.apps.metadata.models import (
Organization,
... | row["Author_Org_{}_id".format(idx)]
org = None
if org_id:
try:
org = Organization.objects.get(membersuite_id=org_id)
except Organization.DoesNotExist:
... |
Author.objects.create(
ct=presentation,
name=author_name,
title=author_title,
organization=org,
)
#
# Files
#
... |
OiNutter/rivets | test/test_scss.py | Python | mit | 6,467 | 0.032473 | import sys
sys.path.insert(0,'../')
if sys.version_info[:2] == (2,6):
import unittest2 as unittest
else:
import unittest
import os
import lean
import shutil
import datetime
import time
from rivets_test import RivetsTest
import rivets
CACHE_PATH = os.path.relpath("../../.sass-cache", __file__)
COMPASS_PATH = os.path... | ertEqual(self.render('sass/variables.scss'),example_css)
def testProcessNesting(self):
''' Test process nesting '''
example_css = '''table.hl {
margin: 2em 0;
}
table.hl td.ln {
text-align: right;
}
li {
font-family: serif;
font-weight: bold;
font-size: 1.2em;
}
'''
self.assertEqual(self.render(' | sass/nesting.scss'),example_css)
def testImportScssPartialFromScss(self):
''' Test @import scss partial from scss '''
example_css = '''#navbar li {
border-top-radius: 10px;
-moz-border-radius-top: 10px;
-webkit-border-top-radius: 10px;
}
#footer {
border-top-radius: 5px;
-moz-border-radius-top: 5px;
-... |
lepture/oauthlib | tests/oauth2/rfc6749/clients/test_legacy_application.py | Python | bsd-3-clause | 2,383 | 0.002098 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from mock import patch
from oauthlib.oauth2 import LegacyApplicationClient
from ....unittest import TestCase
@patch('time.time', new=lambda: 1000)
class LegacyApplicationClientTest(TestCase):
client_id = "someclientid"
scope ... | ody=self.body, **self.kwargs)
self.assertFormBodyEqual(body, self.body_kwargs)
def test_parse_token_response(self):
client = LegacyApplicationClient(self.client_id)
# Parse code and state
response = client.parse_request_body_response(self.token_json, scope=self.scope)
self. | assertEqual(response, self.token)
self.assertEqual(client.access_token, response.get("access_token"))
self.assertEqual(client.refresh_token, response.get("refresh_token"))
self.assertEqual(client.token_type, response.get("token_type"))
# Mismatching state
self.assertRaises(Warni... |
timkrentz/SunTracker | IMU/VTK-6.2.0/IO/MINC/Testing/Python/TestMNITagPoints.py | Python | mit | 3,826 | 0.000261 | #!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Test label reading from an MNI tag file
#
# The current directory must be writeable.
#
try:
fname = "mni-tagtest.tag"
channel = open(fname, "wb")
... | e.SetRadius(0.01)
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(glyphSource.GetOutputPort())
glyph.SetInputConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
... | .SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
#
ren1.AddViewProp(actor)
ren1.AddViewProp(labelActor)
ren1.SetBackground(0, 0, 0)
renWin.SetSize(... |
hiryou/pandora_extractor | src/PandoraExtractor.py | Python | mit | 232 | 0.017241 | __author__="longuy | en"
__date__ ="$8-Feb-2013 3:29:44 AM$"
from app.Welcome import Welcome
from app.FlowControl import FlowControl
if __name_ | _ == '__main__':
Welcome.disclaimer()
control = FlowControl()
control.start()
|
HybridF5/tempest_debug | tempest/services/orchestration/json/orchestration_client.py | Python | apache-2.0 | 16,844 | 0 | # Copyright 2013 IBM Corp.
# 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 app... | k %s failed to reach %s status (current: %s) '
'within the required time (%s s).' %
(stack_name, status, stack_status,
self.build_timeout))
raise exceptions.TimeoutException(message)
time.sleep(self.build_inter... | """Returns the resource's metadata."""
url = ('stacks/{stack_identifier}/resources/{resource_name}'
'/metadata'.format(**locals()))
resp, body = self.get(url)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(res... |
yquant/gn-standalone | src/build/find_depot_tools.py | Python | apache-2.0 | 2,084 | 0.013436 | #!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Small utility function to find depot_tools and add it to the python path.
Will throw an ImportError exception if depot_tools can... | 'tools')
if IsRealDepotTools(depot_tools_lite_dir):
return depot_tools_lite_dir
# First look if depot_tools is already in PYTHONPATH.
for i in sys.path:
if i.rstrip(os.sep).endswith('depot_tool | s') and IsRealDepotTools(i):
return i
# Then look if depot_tools is in PATH, common case.
for i in os.environ['PATH'].split(os.pathsep):
if IsRealDepotTools(i):
sys.path.append(i.rstrip(os.sep))
return i
# Rare case, it's not even in PATH, look upward up to root.
root_dir = os.path.dirname... |
nishad-jobsglobal/odoo-marriot | openerp/addons/tapplicant_webcam/__openerp__.py | Python | agpl-3.0 | 1,685 | 0 | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2013 | Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff | ero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI... |
ericholscher/pinax | pinax/apps/projects/management.py | Python | mit | 922 | 0.005423 | from django.conf import settings
from django.db.models import signals
from django.utils.translation import ugettext_noop as _
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
|
def create_notice_types(app, created_models, verbosity, **kwargs):
notification.create_notice_type("projects_new_member", _("New Project Member"), _("a project you are a member of has a new member"), default=1)
notification.create_notice_type("projects_created_new_member", _("New Member Of Project... | default=2)
notification.create_notice_type("projects_new_project", _("New Project Created"), _("a new project has been created"), default=1)
signals.post_syncdb.connect(create_notice_types, sender=notification)
else:
print "Skipping creation of NoticeTypes as notification app not found"
|
apache/incubator-allura | Allura/allura/model/repo_refresh.py | Python | apache-2.0 | 23,508 | 0.000468 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | actor = user or TransientActor(
activity_name=new.committed.name or new.committed.emai)
g.director.create_activity(actor, 'committed', new,
related_nodes=[repo.app_config.project],
tags=['commit', repo.to... | all_commits, new_clone)
# Send notifications
if notify:
send_notifications(repo, commit_ids)
def refresh_commit_trees(ci, cache):
'''Refresh the list of trees included withn a commit'''
if ci.tree_id is None:
return cache
trees_doc = TreesDoc(dict(
_id=ci._id,
tree... |
klahnakoski/intermittents | pyLibrary/testing/fuzzytestcase.py | Python | mpl-2.0 | 5,448 | 0.006057 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from collections import Mapping
import unittes... | except Exception, e:
Log.error(
"{{test|json}} does not match expected { | {expected|json}}",
test=test if show_detail else "[can not show]",
expected=expected if show_detail else "[can not show]",
cause=e
)
def assertAlmostEqualValue(test, expected, digits=None, places=None, msg=None, delta=None):
"""
Snagged from unittest/case.py, then m... |
diegojromerolopez/djanban | src/djanban/apps/recurrent_cards/migrations/0002_auto_20170602_1726.py | Python | mit | 2,903 | 0.0031 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-02 15:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('boards', '0071_auto_20170530_1711'),
('recurrent_card... | model_name='weeklyrecurrentcard',
name='create_on_sundays',
field=models.BooleanField(default=False, verbose_name='Create card on sundays'),
),
migrations.AlterField(
model_name='weeklyrecurrentcard',
name='create_on_thursdays',
field=... |
name='create_on_tuesdays',
field=models.BooleanField(default=False, verbose_name='Create card on tuesdays'),
),
migrations.AlterField(
model_name='weeklyrecurrentcard',
name='create_on_wednesdays',
field=models.BooleanField(default=False, verb... |
vaishnavsm/spardha17 | spardha/spardha/wsgi.py | Python | gpl-3.0 | 392 | 0 | """
WSGI config for spardha project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
ht | tps://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spardha.settings")
application = get_ | wsgi_application()
|
Valeureux/wezer-exchange | __unreviewed__/project_assignment/__openerp__.py | Python | agpl-3.0 | 1,833 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron and Valeureux Copyright Valeureux.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | AGPL-3',
'description': """
Project Assignment
=============== | ==
Automatically reassign task to specified partner depending on stage
-------------------------------------------------------------------
* For each stage, the partner can be specified in stage,
then in project and finally task itself
* We use partner instead of user for more flexibility
* Use bas... |
sujoykroy/motion-picture | editor/MotionPicture/commons/camera3d.py | Python | gpl-3.0 | 18,923 | 0.006394 | import numpy, cairo, math
from scipy import ndimage
from .object3d import Object3d
from .point3d import Point3d
from .polygon3d import Polygon3d
from .draw_utils import *
from .colors import hsv_to_rgb, rgb_to_hsv
def surface2array(surface):
data = surface.get_data()
if not data:
return None
rgb_a... | nvas_height = int(height*scale)
pixel_count = canvas_width*canvas_height
canvas_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, canvas_width, canvas_height)
canvas_surf_array = surface2array(canvas_surf)
canvas_z_depths =numpy.repeat(min_depth, pixel_count)
| canvas_z_depths = canvas_z_depths.astype("f").reshape(canvas_height, canvas_width)
obj_pad = max(border_width*4, 0)
for object_3d in self.sorted_items:
if object_3d.border_width:
pad = max(obj_pad, object_3d.border_width*2)
else:
pad = obj_pa... |
geektoni/Influenza-Like-Illness-Predictor | data_analysis/filter_news.py | Python | mit | 2,317 | 0.036254 | """Generate year files with news counts
Usage:
filter_news.py <directory> <output> <lang>
Options:
-h, --help
"""
from docopt import docopt
from os import listdir
from os.path import isfile, join, getsize
import datetime
from tqdm import *
import pandas as pd
def find_index(id, lis):
for i in range(0, len(l... | n i
return -1
if __name__ == "__main__":
# Parse the command line
args = docopt(__doc__)
# Array with the week we are considering
weeks = [42,43,44,45,46,47,48,49,50,51, | 52,1,23,4,5,6,7,8,9,10,11,12,13,14,15]
# Final count dictionary
news_count = {}
# Get only the files in the directory which have a dimension greater than zero
onlyfiles = [f for f in listdir(args["<directory>"])
if isfile(join(args["<directory>"], f)) and getsize(join(args["<directory>"], f))>0]
if (len(on... |
LaoZhongGu/kbengine | kbe/src/lib/python/Lib/test/test_capi.py | Python | lgpl-3.0 | 9,478 | 0.010762 | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
from __future__ import with_statement
import os
import pickle
import random
import subprocess
import sys
import time
import unittest
from test import support
try:
imp... | 1,Z(),3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
# Issue #15736: overflow in _PySequence_BytesToCharpArray()
class Z(object):
def __len__(self):
return sys.maxsize
def __getitem__(self, i):
return b'x'
self.assertRaises(MemoryError, _po... | ss.fork_exec,
1,Z(),3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
@unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
def test_subprocess_fork_exec(self):
class Z(object):
def __len__(self):
return 1
# Issue #15... |
MediaKraken/mkarchive | pipeline-deploy-os-server-ubuntu.py | Python | gpl-2.0 | 5,822 | 0.010649 | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... | uild')
# check status of ubuntu build vm
if PROX_CONNECTION.com_net_prox_node_lxc_status('pve',\
JENKINS_BUILD_VIM_LXC)['data']['status'] == 'stopped':
# start up the vm
PROX_CONNECTION.com_net_prox_node_lxc_start('p | ve', JENKINS_BUILD_VIM_LXC)
time.sleep(120) # wait two minutes for box to boot
# check status of ubuntu deploy vm
if PROX_CONNECTION.com_net_prox_node_lxc_status('pve',\
JENKINS_DEPLOY_VIM_LXC)['data']['status'] == 'stopped':
# start up the vm
PROX_CONNECTION.com_net_prox_node_lxc_start('pve', JEN... |
turekj/iDK | tasks/exchange_file_remote_task.py | Python | gpl-2.0 | 413 | 0.01937 | import core.task
import urllib2
class ExchangeFileWithRemoteTask(core.task.Task):
def execute_task(self, parameters=None):
self._check_mandatory_parameters(['path', 'remote_path'], parameters)
path = | parameters['path']
remote_path = parameters['remote_path']
wit | h open(path, 'w+') as file_handle:
response = urllib2.urlopen(remote_path)
contents = response.read()
file_handle.write(contents)
|
drpngx/tensorflow | tensorflow/contrib/distributions/python/ops/vector_diffeomixture.py | Python | apache-2.0 | 44,484 | 0.004226 | # 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... | , name="probs", dtype=dt)
grid = softmax(
-distribution_util.pad(
(normal_loc[..., array_ops.newaxis] +
np.sqrt(2.) * normal_scale[..., array_ops.newaxis] * grid),
axis=-2,
front=True),
axis=-2) # shape: [B, components, deg]
return grid, probs
... | u "
"should update all references to use `tfp.distributions` "
"instead of `tf.contrib.distributions`.",
warn_once=True)
def quadrature_scheme_softmaxnormal_quantiles(
normal_loc, normal_scale, quadrature_size,
validate_args=False, name=None):
"""Use SoftmaxNormal quantiles to form quadrature on `... |
jamespcole/home-assistant | script/gen_requirements_all.py | Python | apache-2.0 | 10,045 | 0 | #!/usr/bin/env python3
"""Generate an updated requirements_all.txt."""
import importlib
import os
import pkgutil
import re
import sys
import fnmatch
COMMENT_REQUIREMENTS = (
'Adafruit-DHT',
'Adafruit_BBIO',
'avion',
'beacontools',
'blinkt',
'bluepy',
'bme680',
'credstash',
'decora',... | """Write the modules to the requirements_all.txt."""
with open('requirements_all.txt', 'w+', newline="\n") as req_file:
req_file.write(data)
def write_test_requirements_file(data):
"""Write the modules to the requirements_test_all.txt."""
with open('requirements_test_all.txt', 'w+', newline="\n")... | , newline="\n") as req_file:
req_file.write(data |
Azure/azure-sdk-for-python | sdk/servicebus/azure-mgmt-servicebus/azure/mgmt/servicebus/v2021_01_01_preview/aio/operations/_topics_operations.py | Python | mit | 39,140 | 0.004778 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | .mgmt.servicebus.v2021_01_01_preview.models.SBAuthorizationRule
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SBAuthorizationRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: R... | 021-01-01-preview"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_or_update_authorization_rule.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.... |
Tocknicsu/nctuoj_contest | backend/utils/form.py | Python | apache-2.0 | 3,213 | 0.008403 | from dateutil import parser
from datetime import datetime
def form_validation(form ,schema):
err = _form_validation(form, schema)
return (400, err) if err else None
def _form_validation(form, schema):
'''
schema:
[{
### require
'name': <str> # +<str> means require, defaul... | lse:
try: form[name] = item['type'](form[name])
except Exception as e: return name + str(e)
### check except
if 'except' in item:
if form[name] in item['except']:
return 'value of %s: "%s" in except list' % (name, str(form[name]))
... | if not (item['range'][0] <= form[name] <= item['range'][1]):
return 'value of %s: "%s" not in range %s' % (name, str(form[name]), str(item['range']))
### check len_range
if 'len_range' in item:
if not (item['len_range'][0] <= len(form[name]) <= item['len_range'][1]):
... |
FlaminMad/RPiProcessRig | RPiProcessRig/src/yamlImport.py | Python | mit | 521 | 0.003839 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Alexander David Leech
@date: 03/06/2016
@rev: 1
@lang: Python 2. | 7
@deps: YAML
@desc: Class to use as an interface to import YAML files
"""
import yaml
class yamlImport():
@staticmethod
def importYAML(pathToFile):
try:
with open(pathToFile, "r") as f:
config = yaml.load(f)
except IOError:
print("Failed to rea... | config
|
AEDA-Solutions/matweb | backend/Database/Models/Prereq.py | Python | mit | 654 | 0.055046 | from Da | tabase.Controllers.Disciplina import Disciplina
clas | s Prereq(object):
def __init__(self,dados=None):
if dados is not None:
self.id = dados ['id']
self.grupo = dados ['grupo']
self.id_disc_pre = dados ['id_disc_pre']
def getId(self):
return self.id
def setGrupo(self,grupo):
self.grupo = grupo
def getGrupo(self):
return self.grupo
def setId... |
anderson7ru/bienestarues | enfermeriaapp/views.py | Python | mit | 4,242 | 0.016973 | from django.shortcuts import render
from enfermeriaapp.models import Cola_Consulta, Cola_Enfermeria
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils import timezone
import time
from django.contrib import messages
from django.contrib.auth.decorators import login_requir... |
}
form = ColaEnfermeriaForm(data)
existe = Cola_Enfermeria.objects.filter(idPaciente = pk)
if existe:
info="El paciente ya existe en la cola"
else:
if form.is_valid(): |
expediente = form.save(commit=False)
expediente.hora = time.strftime("%H:%M:%S") #Formato de 24 horas
expediente.save()
info = "Datos Guardados Exitosamen"
return render(request,"datospersonales/paciente_list.html",{'personalpaciente':paci... |
chennan47/OSF-Offline | osfoffline/exceptions/tray_icon_exceptions.py | Python | apache-2.0 | 73 | 0 | __author__ = 'himanshu'
# Tray | Icon
class TrayIcon(Exception):
| pass
|
spiceqa/virt-test | qemu/tests/live_snapshot_chain.py | Python | gpl-2.0 | 6,291 | 0.000159 | from vi | rttest import storage
from v | irttest import qemu_storage
from virttest import data_dir
from autotest.client.shared import error
import re
import logging
import time
@error.context_aware
def run_live_snapshot_chain(test, params, env):
"""
live_snapshot chain test:
Will test snapshot as following steps:
1. Boot up guest with base ... |
weigj/django-multidb | tests/regressiontests/fixtures_regress/models.py | Python | bsd-3-clause | 5,996 | 0.002668 | from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
class Animal(models.Model):
name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
count = models.IntegerField()
def __unicode__(self):
return self... | s Meta:
| # For testing when upper case letter in app name; regression for #4057
db_table = "Fixtures_regress_plant"
class Stuff(models.Model):
name = models.CharField(max_length=20, null=True)
owner = models.ForeignKey(User, null=True)
def __unicode__(self):
# Oracle doesn't distinguish betw... |
sveetch/PO-Projects | po_projects/crumbs.py | Python | mit | 697 | 0.004304 | from autobreadcrumbs import site
from django.utils.translation import ugett | ext_lazy
site.update({
'po_projects:project-index': ugettext_lazy('PO Projects'),
'po_projects:project-create': ugettext_lazy('Create a new project'),
'po_projects:project-details': ugettext_lazy('<small class="subhead">Project</small> {{ project.name }}'),
'po_projects:project-update': ugettext_lazy('... | po_projects:catalog-details': ugettext_lazy('<small class="subhead">Catalog</small> {{ catalog.get_locale_name }}'),
'po_projects:catalog-messages-edit': ugettext_lazy('Edit messages'),
'po_projects:catalog-messages-download': None,
}) |
UCSD-CCAL/ccal | ccal/conda_is_installed.py | Python | mit | 184 | 0.005435 | from os.path import isdir
def conda_is_installed( | conda_directory_path):
return all(
(isdir("{}/{}".format(conda_directory_path, na | me)) for name in ("bin", "lib"))
)
|
neutrinog/Comperio | comperio/accounts/forms.py | Python | bsd-3-clause | 8,980 | 0.010468 | from django import forms
from django.core import validators
from comperio.accounts.models import cUser, Settings, cGroup
from django.core.validators import email_re
import random, datetime, sha
MIN_PASSWORD_LENGTH = 6
class LoginForm(forms.Form):
"""account login form"""
username = forms.CharField(widget=form... | sting user from the form data"""
# make sure email is unique
new_data = request.POST.copy()
if u.email != new_data['email']:
try:
duplicate = cUser.objects.get(email=new_data['email'])
raise forms.ValidationEr | ror(u'email is not available')
except cUser.DoesNotExist:
u.email = new_data['email']
if u.username != new_data['username']:
try:
duplicate = cUser.objects.get(username=new_data['username'])
raise forms.ValidationError(u'userna... |
concefly/indent_system | db_test.py | Python | gpl-3.0 | 598 | 0.078595 | # -*- coding:utf-8 -*-
import datetime
import xml.etree.ElementTree as et
import pony.orm as orm
import sys
import os
pjoin = os.path.join
__dir__ = os.path.abspath(os.path.dirname(__file__))
sys.path.append(__dir__)
from server import *
dat = dict(
code = 'concefly',
last_login = datetime.datetime.n... | = True,
date_joined = datetime.datetime.now(),
balance = 10000,
point_member = | 10000,
point_xzl = 10000,
point_jhs = 10000,
point_nlb = 10000,
point_nlt = 10000
)
with orm.db_session:
User(**dat)
|
Metronus/metronus | Metronus-Project/metronus_app/model/goalEvolution.py | Python | mpl-2.0 | 791 | 0.001264 | from django.db import models
from metronus_app.model.actor import Actor
from metronus_app.model.task import Task
class GoalEvolution(models.Model):
"""
Each time the goal or the price per unit/hour from a task is changed, a new entry is created in the log
Maybe should have been named TaskLog, but...
"... | models.ForeignKey(Task)
registryDate = models.DateTimeField(auto_now=True)
actor_id = models.ForeignKey(Actor)
production_goal = models.FloatField(blank=True, null=True)
goal_description = models. | CharField(blank=True, max_length=100, default="")
price_per_unit = models.FloatField(null=True, blank=True)
price_per_hour = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.production_goal
|
misli/cmsplugin-survey | cmsplugin_survey/fields.py | Python | bsd-3-clause | 744 | 0 | from __future__ import unicode_literals
import re
from django import forms
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class ColorInput(forms.TextInput):
input_type = 'color'
class ColorField(models.CharField):
defa... | '^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$'),
_('Enter a valid hex color.'),
'invalid',
)]
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 10
super(ColorField, self). | __init__(*args, **kwargs)
def formfield(self, **kwargs):
kwargs['widget'] = ColorInput
return super(ColorField, self).formfield(**kwargs)
|
yuhangwang/MirrorAI | test/dataset/directional/label_image/test_3.py | Python | mit | 224 | 0 | from MirrorAI.dataset.directional.label_image import label_image
import numpy
def test():
d = numpy.array([1, 1, 0])
| answer = label_image(d, target=0)
solut | ion = [0, 0, 1]
assert (answer == solution).all()
|
VillageAlliance/django-cms | cms/templatetags/cms_tags.py | Python | bsd-3-clause | 14,804 | 0.003445 | # -*- coding: utf-8 -*-
from classytags.arguments import Argument, MultiValueArgument
from classytags.core import Options, Tag
from classytags.helpers import InclusionTag
from classytags.parser import Parser
from cms.models import Page, Placeholder as PlaceholderModel
from cms.plugin_rendering import render_plugins, re... | isinstance(page_lookup, Page):
page_key = str(page_lookup.pk)
else:
page_key = str(page_lookup)
page_key = _clean_key(pa | ge_key)
return name+'__page_lookup:'+page_key+'_site:'+str(site_id)+'_lang:'+str(lang)
def _get_page_by_untyped_arg(page_lookup, request, site_id):
"""
The `page_lookup` argument can be of any of the following types:
- Integer: interpreted as `pk` of the desired page
- String: interpreted as `rever... |
openstack/manila | manila/share/drivers/purestorage/flashblade.py | Python | apache-2.0 | 17,837 | 0 | # Copyright 2021 Pure Storage 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 require... | "FlashBlade storage system management VIP.",
),
cfg.HostAddres | sOpt(
"flashblade_data_vip",
help="The name (or IP address) for the Pure Storage "
"FlashBlade storage system data VIP.",
),
]
flashblade_auth_opts = [
cfg.StrOpt(
"flashblade_api",
help=("API token for an administrative user account"),
secret=True,
),
]
fla... |
hr567/seating-chart | SeatingChart/API/SeatingChart.py | Python | gpl-3.0 | 2,072 | 0 | from .RuleEditor import *
class SeatingChart:
def __init__(self, m, n):
self.M, self.N = m, n
self._pos = list(range(len(self)))
self.names = None
self.rule_editor = RuleEditor(m, n)
self.maintain()
def __len__(self) -> int:
"""Return the number of students in ... | in range(self.M):
for j in range(self.N):
s += str(self[i][j]).rjust(4)
s += '\n'
return s
def index(self, i: int) -> tuple:
"""Return the position of student i""" |
i = int(i)
_real_pos = self._pos.index(i)
return _real_pos // self.N, _real_pos % self.N
def get_name(self, i: int, j: int) -> str:
"""Return the number/name of student who seat at (i, j)"""
return self.names[self[i][j]] if self.names else str(self[i][j])
def maintain(... |
gilestrolab/pyrem | src/pyrem/univariate.py | Python | gpl-3.0 | 18,418 | 0.008579 | r"""
==================================================
Feature computation for univariate time series
==================================================
This sub-module provides routines for computing features on univariate time series.
Many functions are improved version of PyEEG [PYEEG]_ functions. Be careful,
som... | esults is different from [PYEEG]_ which appear to uses a non normalised (by the length of the signal) definition of the activity:
.. math::
\sigma_{a}^2 = \sum{\mathbf{x}[i]^2}
As opposed to
. | . math::
\sigma_{a}^2 = \frac{1}{n}\sum{\mathbf{x}[i]^2}
:param a: a one dimensional floating-point array representing a time series.
:type a: :class:`~numpy.ndarray` or :class:`~pyrem.time_series.Signal`
:return: activity, complexity and morbidity
:rtype: tuple(float, float, float)
... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorboard/version.py | Python | mit | 744 | 0 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Ver | sion 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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Co... |
kgsn1763/deep-learning-from-scratch | ch06/weight_init_compare.py | Python | mit | 1,963 | 0.00429 | #!/usr/bin/env python
# coding: utf-8
import os
import sys
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.util import smooth_curve
from common.multi_layer_net import MultiLayerNet
from common.optimizer import ... | .append(loss)
if i % 100 == 0:
print("===========" + "iteration:" + str(i) + "===========")
for key in weight_init_types.keys():
loss = networks[key].loss(x_batch, t_batch)
print(key + ":" + str(loss))
# 3.グラフの描画==========
markers = {'std=0.01': 'o', 'Xavier': 's', 'He': '... | ker=markers[key], markevery=100, label=key)
plt.xlabel("iterations")
plt.ylabel("loss")
plt.ylim(0, 2.5)
plt.legend()
plt.show()
|
MrYsLab/pymata-aio | examples/blink.py | Python | agpl-3.0 | 1,345 | 0 | #!/usr/bin/python
"""
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentatio... | n_mode(BOARD_LED, Constants.OUTPUT)
def loop():
"""
Toggle the LED by alternating the values written
to the LED pin. Wait 1 second between writes.
Also note the use of board.sleep and not
time.sleep.
:return:
"""
print("LED On | ")
board.digital_write(BOARD_LED, 1)
board.sleep(1.0)
print("LED Off")
board.digital_write(BOARD_LED, 0)
board.sleep(1.0)
if __name__ == "__main__":
setup()
while True:
loop()
|
bd-j/hmc | convergence.py | Python | gpl-2.0 | 1,867 | 0.009106 | import numpy as np
def gr_indicators(chain, alpha=0.05):
"""Calculate the Gelman Rubin indicator of convergence. Also,
calculate the interval based indicator presented in Brooks &
Gelman 1998
"""
nw, nstep, ndim = chain.shape
# mean within each chain
mean = chain.mean(axis=1)
# varian... | rated_time
nw, nstep, ndim = chain.shape
x = np.mean(chain, axis=0)
m = 0
if window is None:
for m in np.arange(10, nstep):
tau = integrated_time(x, axis=0, fast=fast,
window=m)
if np.all(tau * c < m) and np.all(tau > 0):
... | ow=window)
if m == (nstep-1) or (np.any(tau < 0)):
raise(ValueError)
return tau, window
def raftery_lewis(chain, q, tol=None, p = 0.95):
pass
def heidelberg_welch(chain, alpha):
pass
def geweke(chain):
pass
|
simon-r/SerialPhotoMerge | imgmerge/mergeProcedureVirtual.py | Python | gpl-3.0 | 2,752 | 0.00109 | # Serial Photo Merge
# Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#(at your optio... | ead_image_factory, set_read_image_factory)
def execute(self):
NotImplementedError(
" %s : is virutal and must b | e overridden." % sys._getframe().f_code.co_name)
def get_resulting_image(self):
return self._resimg
def set_resulting_image(self, resarr):
self._resimg = resarr
resulting_image = property(get_resulting_image, set_resulting_image)
|
nfredrik/pyModelStuff | samples/populations/test/test_filter.py | Python | bsd-3-clause | 247 | 0.004049 | cases = [
('pmt.py -s 1 -n 20 population | s, first without state filter',
'pmt.py -s 1 -n 20 populations'),
('pmt.py -s 2 -n 20 populations filter3, state filter limits population to 3',
'pmt.py -s 2 -n 20 popu | lations filter3')
]
|
surru/Three-Musketeers-Game | multiagent/main.py | Python | mit | 113 | 0.026549 | import view
try:
view.main()
e | xcept:
print('Invalid List F | ormat')
view.terminate()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.