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 |
|---|---|---|---|---|---|---|---|---|
veloutin/papas | etc/papas/settings.py | Python | agpl-3.0 | 4,958 | 0.004639 | # Django settings for apmanager project.
import os
from django.utils.translation import ugettext_lazy as _
DEBUG = True
USE_DAEMON = True
if os.environ.get("USE_DEV_PATHS", None):
DEV_PATHS = True
else:
DEV_PATHS = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGE... | # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = "/media/"
# Make this unique, and don't share it with anybody.
SECRET_KEY = ')@1wt()$4x&&e9c#n&viv-g#k20(p!_ga)s$+4i!*hbdcid$)s'
# List of callables tha... | stem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.... |
kamyu104/LeetCode | Python/accounts-merge.py | Python | mit | 3,714 | 0 | # Time: O(nlogn), n is the number of total emails,
# and the max length ofemail is 320, p.s. {64}@{255}
# Space: O(n)
# Given a list accounts, each element accounts[i] is a list of strings,
# where the first element accounts[i][0] is a name,
# and the rest of the elements are emails representing emai... | ind_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root != y_root:
self.set[min(x_root, y_root)] = max(x_root, y_r... | """
union_find = UnionFind()
email_to_name = {}
email_to_id = {}
for account in accounts:
name = account[0]
for i in xrange(1, len(account)):
if account[i] not in email_to_id:
email_to_name[account[i]] = name
... |
lechat/jenkinsflow | test/cause_test.py | Python | bsd-3-clause | 966 | 0.006211 | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from jenkinsflow.flow import serial
from .framework import api_select
# TODO: Actually test that cause is set
def test_cause_no_build_number(api_type, env_job_name):
with api_s... | _number):
with api_select.api(__fi | le__, api_type) as api:
api.flow_job()
api.job('j1', exec_time=0.01, max_fails=0, expect_invocations=1, expect_order=1)
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=1) as ctrl1:
ctrl1.invoke('j1')
|
dspinellis/effective-debugging | logging/Python/eventlog.py | Python | apache-2.0 | 220 | 0.004545 | import logging;
logger = logging.getLogger('myapp')
# Send | log messa | ges to myapp.log
fh = logging.FileHandler('myapp.log')
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)
logger.debug('In main module')
|
danbradham/hotline | hotline/widgets.py | Python | mit | 14,920 | 0.000268 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from collections import deque
from contextlib import contextmanager
from hotline.utils import event_loop
from hotline.anim import *
from hotline.vendor.Qt import QtWidgets, QtCore, QtGui
class ActiveScreen(object):
@staticmethod
def active():
... | False
self.setWindowTitle('Hotline')
| self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.FramelessWindowHint
)
self.setMinimumSize(1, 1)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.mode_button = QtWidgets.QPushButton(self)
self.mode_button.setMinimumWidth(self._height)
s... |
atul-bhouraskar/django | tests/admin_views/admin.py | Python | bsd-3-clause | 36,442 | 0.000494 | import datetime
from io import StringIO
from wsgiref.util import FileWrapper
from django import forms
from django.contrib import admin
from django.contrib.admin import BooleanFieldListFilter
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.c... | a_var': 'Hello!'})
class ThingAdmin(admin.ModelAdmin):
list_filter = ('color', 'color__warm', 'color__value', 'pub_date')
class InquisitionAdmin(admin.ModelAdmin):
list_display = ('leader', 'country', 'expected', 'sketch')
@admin.display
def sketch(self, obj):
# A method with the same name ... | ay-sketch'
class SketchAdmin(admin.ModelAdmin):
raw_id_fields = ('inquisition', 'defendant0', 'defendant1')
class FabricAdmin(admin.ModelAdmin):
list_display = ('surface',)
list_filter = ('surface',)
class BasePersonModelFormSet(BaseModelFormSet):
def clean(self):
for person_dict in self.c... |
Kaniabi/ben10 | source/python/ben10/foundation/print_detailed_traceback.py | Python | lgpl-2.1 | 6,374 | 0.006119 | from __future__ import unicode_literals
import locale
import sys
#===================================================================================================
# _StreamWrapper
#===================================================================================================
class _StreamWrapper(object):
... | name=frame.f_code.co_name.decode(encoding),
filename=frame.f_code.co_filename.decode(encoding),
lineno=frame.f_lineno,
)
_WriteToStream(' File "%(filename)s", line %(lineno)d, in %(name)s\n' % params)
try:
lines = io.open(frame.f_code.co_filename).r... | pass # don't show the line source
else:
_WriteToStream(' %s\n' % line.strip())
if not omit_locals:
# string used to truncate string representations of objects that exceed the maximum
# line size
trunc_str = '...'
for key, value in ... |
cpsaltis/pythogram-core | src/gramcore/filters/morphology.py | Python | mit | 3,722 | 0 | """Morphological filters.
The following work on 2D arrays. They wrap the relevant scipy functions. The
ones provided by skimage are not well documented for now.
"""
from scipy.ndimage import morphology
def closing(parameters):
"""Calculates morphological closing of a greyscale image.
This is equal to perfo... | to (3, 3) a.k.a. numpy.ones((3, 3))
:type parameters['size']: list
:return: numpy.array
"""
data = parameters['data'][0]
size = tuple(parameters['size'])
return morphology.grey_erosion(data, size=size)
def dilation(parameters):
"""Dilates a greyscale image.
For th... | ver a sliding window.
It wraps `scipy.ndimage.morphology.grey_dilation`. The `footprint`,
`structure`, `output`, `mode`, `cval` and `origin` options are not
supported.
Keep in mind that `mode` and `cval` influence the results. In this case
the default mode is used, `reflect`.
:param parameter... |
srange/SU2 | SU2_PY/change_version_number.py | Python | lgpl-2.1 | 3,458 | 0.010411 | #!/usr/bin/env python
## \file change_version_number.py
# \brief Python script for updating the version number of the SU2 suite.
# \author A. Aranake
# \version 6.2.0 "Falcon"
#
# The current SU2 release has been coordinated by the
# SU2 International Developers Society <www.su2devsociety.org>
# with selected cont... | ill be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public Li | cense for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with SU2. If not, see <http://www.gnu.org/licenses/>.
# make print(*args) function available in PY2.6+, does'nt work on PY < 2.6
from __future__ import print_function
# Run the script from the base directory (... |
belokop/indico_bare | migrations/versions/201511251405_33a1d6f25951_add_timetable_related_tables.py | Python | gpl-3.0 | 4,295 | 0.004889 | """Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# rev... | NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
... | int(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstrain... |
hongaar/meterkast | components/timedReader.py | Python | mit | 1,120 | 0 | from helpers.timer import TaskThread
class TimedReader(TaskThread):
DEFAULT_INTERVAL = 1 * 60
HIBERNATION_INTERVAL = 5 * 60
DEBUG_INTERVAL = 5
probing_callback = None
probed_callback = None
def | __init__(self, p1, debug=False):
TaskThread.__init__(self)
self | .debug = debug
self.p1 = p1
self.set_interval(self.DEFAULT_INTERVAL)
def set_interval(self, interval):
if self.debug:
TaskThread.set_interval(self, self.DEBUG_INTERVAL)
else:
TaskThread.set_interval(self, interval)
def wakeup(self):
self.set_inte... |
sinanm89/barista | build/barista-site/barista/settings.py | Python | gpl-2.0 | 6,858 | 0.002333 | # Django settings for barista project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Sinan Midillili', 'sinan@rahatol.com'),
)
DEFAULT_FROM_EMAIL = 'sinan@rahatol.com',
SERVER_EMAIL = 'sinan@rahatol.com'
MANAGERS = ADMINS
# Hosts/domain names that are valid for this site; required if DEBUG is Fals... | tic/markitup/", os.path.join(os.path. | realpath(os.path.dirname(__file__)), 'media/markitup/')),
# )
# List of finder classes that know how to find static files in
# various locations.
# STATICFILES_FINDERS = (
# 'django.contrib.staticfiles.finders.FileSystemFinder',
# 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.... |
Lightshadow244/OwnMusicWeb | ownmusicweb/manage.py | Python | apache-2.0 | 809 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ownmusicweb.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that ... | ly that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variab... | |
ianmiell/shutit-test | test/docker_tests/16/test16.py | Python | mit | 395 | 0.043038 | from shu | tit_module import ShutItModule
class test16(ShutItModule):
def build(self, shutit):
shutit.login()
shutit.login(command='bash')
shutit.send('ls',note='We are l | isting files')
shutit.logout()
shutit.logout()
return True
def module():
return test16(
'shutit.test16.test16.test16', 210790650.002938762,
description='',
maintainer='',
depends=['shutit.tk.setup']
)
|
capitalone/cloud-custodian | tools/c7n_gcp/c7n_gcp/resources/pubsub.py | Python | apache-2.0 | 3,103 | 0.000967 | # Copyright 2018 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.utils import type_schema
from c7n_gcp.actions import MethodAction
from c7n_gcp.provider import resources
from c7n_gcp.query import QueryResourceManager, TypeInfo
"""
todo, needs detail_sp... | rsion = 'v1'
component = 'projects.subscriptions'
enum_spec = ('list', 'subscriptions[]', None)
scope_template = 'projects/{}'
name = id = 'name'
default_report_fields = [
"name", "topic", "ackDeadlineSeconds",
"retainAckedMessages", "messageRetentionDurat... | source_info):
return client.execute_command(
'get', {'subscription': resource_info['subscription_id']})
@PubSubSubscription.action_registry.register('delete')
class DeletePubSubSubscription(MethodAction):
schema = type_schema('delete')
method_spec = {'op': 'delete'}
def get_r... |
jonzobrist/Percona-Server-5.1 | kewpie/lib/util/mysqlBaseTestCase.py | Python | bsd-3-clause | 12,988 | 0.018017 | #! /usr/bin/env python
# -*- mode: python; indent-tabs-mode: nil; -*-
# vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
#
# Copyright (C) 2011 Patrick Crews
#
#
# 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 Softwar... | given
server, storing the output to dump_path
"""
if not dump_path:
dump_path = os.path.join(server.vardir, 'dumpfile.dat')
if cmd_root:
dum | p_cmd = cmd_root
else:
dump_cmd = "%s --no-defaults --user=root --port=%d --host=127.0.0.1 --protocol=tcp --result-file=%s" % ( server.mysqldump
, server.master_port
... |
t-mertz/slurmCompanion | django-web/webcmd/cmdtext.py | Python | mit | 4,609 | 0.006943 | import sys
MAX_NUM_STORED_LINES = 200
MAX_NUM_LINES = 10
LINEWIDTH = 80
class CmdText(object):
"""
Represents a command line text device. Text is split into lines
corresponding to the linewidth of the device.
"""
def __init__(self):
"""
Construct empty object.
"""
s... | lf.insert(string)
if (rind is not None):
self.response = rind
class Response(CmdText):
def __init__(self, string, cind=None):
CmdText.__init__(self)
self.insert(string)
if (cind is not None):
self.command = cind
class TestCase(object):
"""
Ba... | ""
#print(cls)
max_len = max([len(a) for a in cls.__dict__])
for key in cls.__dict__:
if key.startswith("test"):
fill = max_len - len(key)
sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill))
try:
cls.__dict__... |
pydoit/doit-cmd | test_doitcmd.py | Python | mit | 2,946 | 0.004752 |
from doit.tools import Interactive
import doitcmd
from doitcmd import BaseCommand
class TestBaseCommand_OptStr(object):
def test_no_value(self):
assert '' == BaseCommand.opt_str()
def test_single_value(self):
assert '--name test' == BaseCommand.opt_str({'name':'test'})
assert '-n te... | 'bar'} == cmd.options
class TestBaseCommand_Action(object):
class MyCmd(BaseCommand):
cmd_template = 'foo {options} {target}'
def __call__(self, target):
action = self.action(self.cmd_template.format(
| target=target,
options=self.opt_str(self.options),
))
return {
'name': target,
'actions': [action],
}
def test_normal(self):
cmd = self.MyCmd(options={'bar': 'baz'})
assert 'foo --bar ... |
jedie/djangocms-find_and_replace | find_and_replace/tests/test_doctest.py | Python | gpl-3.0 | 2,605 | 0.001919 | # coding: utf-8
"""
django find&replace
~~~~~~~~~~~~~~~
:copyleft: 2015 by find&replace team, see AUTHORS for more details.
:created: 2015 by JensDiemer.de
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import os
import doc | test
import sys
import find_and_replace
BASE_DIR = find_and_replace.__file__
SKIP_DIRS = (".settings", ".git", "dist", ".egg-info")
SKIP_FILES = ("setup.py", "test.py")
def get_all_doctests(base_path, verbose=False):
modules = []
for root, dirs, filelist in os.walk(base_path, followlinks=True):
for... | SKIP_DIRS:
if skip_dir in dirs:
dirs.remove(skip_dir) # don't visit this directories
for filename in filelist:
if not filename.endswith(".py"):
continue
if filename in SKIP_FILES:
continue
sys.path.insert(0, root)... |
gigglearrows/anniesbot | pajbot/models/emotecomboparser.py | Python | mit | 1,638 | 0.001221 | import re
import logging
log = logging.getLogger('pajbot')
class EmoteComboParser:
def __init__(self, bot):
self.bot = bot
self.emote_count = 0
self.current_emote = None
def inc_emote_count(self):
self.emote_count += 1
if self.emote_count >= 5:
self.bot.we... | (self):
self.emote_count = 0
self.current_emote = None
def parse_line(self, msg, source, emotes):
if len(emotes) == 0:
# Ignore messages without any emotes
return False
prev_code = None
for emote in emotes:
if prev_code is | not None:
if prev_code != emote['code']:
# The message contained more than 1 unique emote, reset.
self.reset()
return False
else:
prev_code = emote['code']
emote = emotes[0]
if self.current_emote is... |
jumpstarter-io/keystone | keystone/common/ldap/core.py | Python | apache-2.0 | 76,368 | 0.000013 | # Copyright 2012 OpenStack Foundation
#
# 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... | : %(options)s') % {
'scope': scope,
'options': ', '.join(LDAP_SCOPES.keys())})
def prep_case_insensitive(value):
"""Prepare a string for case-insensitive comparison.
Th | is is defined in RFC4518. For simplicity, all this function does is
lowercase all the characters, strip leading and trailing whitespace,
and compress sequences of spaces to a single space.
"""
value = re.sub(r'\s+', ' ', value.strip().lower())
return value
def is_ava_value_equal(attribute_type, va... |
lukovkin/ufcnn-keras | models/UFCNN1_REPO_V16_TESTMODE.py | Python | mit | 51,403 | 0.013054 | from __future__ import absolute_import
from __future__ import print_function
import sys
import glob
import time
import numpy as np
import pandas as pd
import os.path
import time
import datetime
import re
from keras.preprocessing import sequence
from keras.optimizers import SGD, RMSprop, Adagrad
from keras.utils impor... | , filter_length=filter_length, border_mode='same', init=init), name='conv3', input='relu2')
#model.add_node(Activation(activation), name='relu3', input='conv3')
conv3 = (Convolution1D(nb_filter=nb_filter, filter_length=filter_length, border_mode='same', init=init))(relu2)
relu3 = (Activation(activation))(... | nv3)
#########################################################
#model.add_node(Convolution1D(nb_filter=nb_filter, filter_length=filter_length, border_mode='same', init=init), name='conv4', input='relu3')
#model.add_node(Activation(activation), name='relu4', input='conv4')
conv4 = (Convolution1D(nb_fil... |
qedsoftware/commcare-hq | corehq/apps/toggle_ui/urls.py | Python | bsd-3-clause | 291 | 0.003436 | from django.conf.urls import | url
from corehq.apps.toggle_ui.views import ToggleListView, ToggleEditView
urlpatterns = [
url(r'^$', ToggleListView.as_view(), name=ToggleListView.urlname),
url(r'^edit/(?P<toggle>[\w_-]+)/$', ToggleEditView.as_view(), name=T | oggleEditView.urlname),
]
|
samhoo/askbot-realworld | askbot/management/commands/askbot_add_test_content.py | Python | gpl-3.0 | 10,587 | 0.007368 | from django.core.management.base import NoArgsCommand
from askbot.models import User
from optparse import make_option
from askbot.utils.console import choice_dialog
NUM_USERS = 40
# KEEP NEXT 3 SETTINGS LESS THAN OR EQUAL TO NUM_USERS!
NUM_QUESTIONS = 40
NUM_ANSWERS = 20
NUM_COMMENTS = 20
# To ensure that all the ac... | self.print_if_verbose("%s upvoted an answer"%(
user.username
))
last_vote = ~last_vote
active_answer = user.post_answer(
ques | tion = active_question,
body_text = ANSWER_TEMPLATE,
follow = True
)
self.print_if_verbose("%s posted an answer to the active question"%(
user.username
... |
youtube/cobalt | third_party/devtools/scripts/build/dependency_preprocessor.py | Python | bsd-3-clause | 3,349 | 0.00209 | # Copyright 2016 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.
"""
This ensures that each front-end module does not accidentally rely on a module
that isn't listed as a transitive dependency in the module.json.
How this ... | ors = descriptors.modules
self.modules = set(self.descriptors.sorted_modules())
shutil.copytree(devtools_frontend_path, self.temp_frontend_path)
self._special_case_namespaces = special_case_namespaces.special_case_namespaces
def enforce_dependencies(self):
arg_list = []
for ... | ptors.sorted_dependencies_closure(module))
excluded_modules = self.modules - {module} - dependencies
excluded_namespaces = [self._map_module_to_namespace(m) for m in excluded_modules]
file_paths = [
path.join(self.temp_frontend_path, module, file_name)
... |
bmcfee/mir_eval | evaluators/melody_eval.py | Python | mit | 2,538 | 0 | #!/usr/bin/env python
'''
CREATED:2014-03-18 by Justin Salamon <justin.salamon@nyu.edu>
Compute melody extraction evaluation measures
Usage:
./melody_eval.py TRUTH.TXT PREDICTION.TXT
(CSV files also accepted)
For a detailed explanation of the measures please refer to:
J. Salamon, E. Gomez, D. P. W. Ellis and G. Ri... | )
# Compute all the scores
scores = mir_eval.melody.evaluate(ref_time, ref_freq, est_time, est_freq,
hop=parameters['hop'])
print("{} vs | . {}".format(os.path.basename(parameters['reference_file']),
os.path.basename(parameters['estimated_file'])))
eval_utilities.print_evaluation(scores)
if parameters['output_file']:
print('Saving results to: ', parameters['output_file'])
eval_utilities.save_results(sc... |
xtacocorex/chip-python-aREST | examples/chip-arest-cloud.py | Python | mit | 734 | 0.013624 | #!/usr/bin/env python
# Copyright (c) 2017 Robert Wolterman
# Basic example using the CHIP aREST API
# Module Imports
import CHIP_aREST.aREST as aREST
# Setup the Device Info
aREST.set_id(aREST.make_id(6))
# or
#aREST.set_id("Xy56E1")
aREST.set_name("MY_CLOUDED_CHIP")
# In the future, this would be used to | different | iate a CHIP and CHIP Pro
aREST.set_hardware("chip")
# Variable Examples
temperature = 21.2
humidity = 95.2
aREST.variable("temperature",temperature)
aREST.variable("humidity",humidity)
# Function Example
def myfunction():
return "hello from myfunction cloud!"
aREST.function("functiontest",myfunction)
# Connect ... |
D4wN/brickv | src/build_data/windows/OpenGL/GL/NV/half_float.py | Python | gpl-2.0 | 1,383 | 0.016631 | '''OpenGL extension NV.half_float
This module customises the behaviour of the
OpenGL.raw.GL.NV.half_float to provide a more
Python-friendly API
Overview (from the spec)
This extension introduces a new storage format and data type for
half-precision (16-bit) floating-point quantities. The floating-point
format... | s, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.NV.half_float import *
### END AUTOGENERATED SECTION | |
douwevandermeij/cmsplugin-filer | cmsplugin_filer_folder/cms_plugins.py | Python | bsd-3-clause | 2,258 | 0.000886 | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template import loader
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.models.imagemodels import Image
cla... | els.FilerFolder
name = _("Folder")
TEMPLATE_NAME = 'cmsplugin_filer_folder/plugins/folder/%s.html'
render_template = TEMPLATE_NAME % 'default'
text_enabled = False
admin_preview = False
fieldsets = (
(None, {'fields': ['title', 'folder']}),
)
if settings.CMSPLUGIN_FILER_FOL | DER_STYLE_CHOICES:
fieldsets[0][1]['fields'].append('style')
def get_folder_files(self, folder, user):
qs_files = folder.files.filter(image__isnull=True)
if user.is_staff:
return qs_files
else:
return qs_files.filter(is_public=True)
def get_folder_images... |
martadesimone/Protoplanetarydisks | linmix/linmix/__init__.py | Python | gpl-2.0 | 117 | 0.008547 | """ A hierarchical Bayesian approach to linea | r regression with | error in both X and Y.
"""
from linmix import LinMix
|
flp9001/vila-paraiso | vilaparaiso/vilaparaiso/settings.py | Python | gpl-3.0 | 5,294 | 0.003967 | """
Django settings for vilaparaiso project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
impor... | TH_USER_MODEL = 'users.User'
#CITIES_LIGHT
#http://download.geonames.org/export/dump/iso-languagecodes.txt
CITIES_LIGHT_APP_NAME = 'cities'
CITIES_LIGHT_TRANSLATION_LA | NGUAGES = ['en', 'es', 'pt', 'abbr']
#CITIES_LIGHT_INCLUDE_COUNTRIES = ['BR']
JET_THEMES = [
{
'theme': 'default', # theme folder name
'color': '#47bac1', # color of the theme's button in user menu
'title': 'Default' # theme title
},
{
'theme': 'green',
'color': '#4... |
suutari/shoop | shuup_tests/utils/basketish_order_source.py | Python | agpl-3.0 | 355 | 0 | # -*- coding: utf-8 -*-
# This file is par | t of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tr | ee.
from shuup.core.order_creator import OrderSource
class BasketishOrderSource(OrderSource):
pass
|
venicegeo/eventkit-cloud | scripts/thematic_test.py | Python | bsd-3-clause | 5,667 | 0.004764 | """
Harness for running thematic transformations against a spatialite db.
From the project directory run:
./manage.py runscript thematic_test --settings=hot_exports.settings -v2
Depends on django-extensions.
"""
import logging
import os
import shutil
from string import Template
import sqlite3
from e... | planet_osm_point_GEOMETRY')
cur.execute('DROP TABLE idx_planet_osm_line_GEOMETRY')
cur.execute('DROP TABLE idx_planet_osm_polygon_GEOMETRY')
conn.commit()
# drop default schema tables
cur.execute('DROP TABLE planet_osm_point')
cur.execute('DROP TABLE planet_osm_line')
| cur.execute('DROP TABLE planet_osm_polygon')
conn.commit()
cur.close()
|
kupiakos/LapisMirror | plugins/e621.py | Python | mit | 4,898 | 0.000612 | # The MIT License (MIT)
# Copyright (c) 2016 HeyItsShuga
# 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, modify,... | self.log.error('Could not import e621 URL %s (%s)',
submission.url, tr | aceback.format_exc())
return None
__plugin__ = E621Plugin
# END OF LINE.
|
xbmc/atv2 | xbmc/lib/libPython/Python/Mac/scripts/buildpkg.py | Python | gpl-2.0 | 15,904 | 0.001572 | #!/usr/bin/env python
"""buildpkg.py -- Build OS X packages for Apple's Installer.app.
This is an experimental command-line tool for building packages to be
installed with the Mac OS X Installer.app application.
It is much inspired by Apple's GUI tool called PackageMaker.app, that
seems to be part of the OS X develo... | les set later
self.packageRootFolder = None
self.packageResourceFolder = None
self.sourceFolder = None
self.resourceFolder = None
def build(self, root, resources=Non | e, **options):
"""Create a package for some given root folder.
With no 'resources' argument set it is assumed to be the same
as the root directory. Option items replace the default ones
in the package info.
"""
# set folder attributes
self.sourceFolder = root
... |
GeosoftInc/gxpy | geosoft/gxapi/GXDBWRITE.py | Python | bsd-2-clause | 11,130 | 0.007907 | ### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
from .GXDB import GXDB
from .GXVA import GXVA
from .GXVV import GXVV
### endblock ClassImports
### block Header
# NOTIC... | db)
return GXDBWRITE(ret_val)
@classmethod
def create_xy(cls, db):
"""
Create a `GXDBWRITE <geosoft.gxapi.GXDBWRITE>` object for a XY-located data. Add channels using the
`add_channel <geosoft.gxapi.GXDBWRITE.add_channel>` method.
:param db: Database input
... | `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
"""
ret_val = gxapi_cy.WrapDBWRITE._create_xy(GXContext._get_tls_geo(), db)
return GXDBWRITE(ret_val)
@classmethod
def create_xyz(cls, db):
"""
Create a ... |
szha/mxnet | python/mxnet/gluon/model_zoo/model_store.py | Python | apache-2.0 | 6,036 | 0.00116 | # 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... | th to the requested pretrained model file.
"""
| file_name = '{name}-{short_hash}'.format(name=name,
short_hash=short_hash(name))
root = os.path.expanduser(root)
file_path = os.path.join(root, file_name+'.params')
sha1_hash = _model_sha1[name]
if os.path.exists(file_path):
if check_sha1(file_path... |
prasanna08/oppia | extensions/answer_summarizers/models.py | Python | apache-2.0 | 14,017 | 0.000285 | # coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | ded state answers.
NOTE TO DEVELOPERS: To specify calculations desired for an interaction named
<INTERACTION_NAME>, edit
extensions.interactions.<INTERACTION_NAME>.answer_visualizations
This is a list of visualizations, each of which is specified by a dict with keys
'id', 'options' and 'calculation_id'. An examp... |
answer_visualizations = [{
'id': 'SortedTiles',
'options': {
'use_percentages': True,
'header': 'Pretty Tiles!',
},
'calculation_id': 'AnswerFrequencies',
}]
"""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future_... |
kashifpk/TA | fetchmail.py | Python | gpl-2.0 | 3,120 | 0.006731 | #!/usr/bin/python
import email
from email.parser import HeaderParser
import imaplib
import mimetypes
import getpass
import sys
import os
from config import email_id, assignments_folder
class Mailbox(object):
def __init__(self, email_id, password, server='imap.gmail.com'):
self.mbox = imaplib.IMAP4_SS... | (part.get_payload(decode=True))
else:
fp = open(os.path.join(folder, filename), 'wb')
fp.write(part.get_payload(decode=True).strip())
fp.close()
open(os.path.join(folder, '_email.txt'), 'wb').write(email_text)
if '__main__' == __na | me__:
if len(sys.argv) != 2:
print("Usage:\n\n\t %s email_save_folder" % sys.argv[0])
sys.exit()
password = getpass.getpass("Enter password for %s: " % email_id)
M = Mailbox(email_id, password)
M.select(assignments_folder)
M.fetch_messages(folder=sys.argv[1])
|
binoculars/osf.io | addons/base/tests/models.py | Python | apache-2.0 | 24,742 | 0.001213 | import abc
import mock
import pytest
from addons.base.tests.utils import MockFolder
from django.utils import timezone
from framework.auth import Auth
from framework.exceptions import HTTPError
from nose.tools import (assert_equal, assert_false, assert_in, assert_is,
assert_is_none, assert_not_i... | y()
self.user = self.node.creator
self.external_account = self.ExternalAccountFactory()
self.user.external_accounts.add(self.external_account)
self.user.save()
self.user_settings | = self.user.get_or_add_addon(self.short_name)
def test_mergability(self):
assert self.user_settings.can_be_merged
def test_merge_user_settings(self):
other_node = ProjectFactory()
other_user = other_node.creator
other_account = self.ExternalAccountFactory()
other_user.... |
oseledets/ttpy | examples/test_eigb.py | Python | mit | 544 | 0.020221 | from __future__ import | print_function, absolute_import, division
import sys
sys.path.append('../')
import numpy as np
import tt
from tt.eigb import *
import time
""" This code computes many eigenvalus of the Laplacian operator """
d = 8
f = 8
A = tt.qlaplace_dd([d]*f)
#A = (-1)*A
#A = tt.eye(2,d)
n = [2] *(d * f)
r = [8] *(d * f + 1)
r[0] ... | )
print('Time is:', t1-t)
|
OpenWinCon/OpenWinNet | web-gui/myvenv/lib/python3.4/site-packages/pip/commands/freeze.py | Python | apache-2.0 | 4,647 | 0.002798 | import re
im | port sys
import pip
from pip.req import InstallRequirement
from pip.log import logger
from pip.basecommand import Command
from pip.util import get_installed_distributions
import pkg_resources
| class FreezeCommand(Command):
"""Output installed packages in requirements format."""
name = 'freeze'
usage = """
%prog [options]"""
summary = 'Output installed packages in requirements format.'
def __init__(self, *args, **kw):
super(FreezeCommand, self).__init__(*args, **kw)
... |
chaos95/fluxxbot | pyGBot/Plugins/probability/Roll.py | Python | gpl-3.0 | 5,676 | 0.008633 | ##
## Roll - a plugin for pyGBot
## Copyright (C) 2008 Morgan Lokhorst-Blight, Alex Soborov
##
## 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 Lic... | ", "^")
self.bot.pubout(channel, "Rolled %s for a subtotal of %d. With modifiers of %s, the total is %d" % (rolls, subtotal, mod, modtotal))
else:
self.bot.pubout(channel, "Rolled " + rolls + " for a total of %i." % modtotal)
elif st | atus == 1:
self.bot.pubout(channel, "That's too many dice! I won't roll more than 75 at once.")
elif status == 2:
self.bot.pubout(channel, "Why would you ever need dice with that many sides? I'm not rolling this.")
def msg_action(self, channel, user, message):
... |
wjlei1990/shakemovie_pyproc | src/source.py | Python | gpl-2.0 | 11,628 | 0.003354 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Source and Receiver classes of Instaseis.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014
Martin van Driel (Martin@vanDriel.de), 2014
:license:
GNU Lesser General Public License, Version 3
(http://www.gnu.org/copyleft/lgpl.html)
"""... | elif mag.magnitude_type == "MS":
ms = mag.mag
region_tag = event.event_descriptions[0].text
for descrip in event.event_descriptions:
if descrip.type == "earthquake name":
eventname = descrip.text
| eventname = self.adjust_eventname(eventname)
cmt_time = cmtsolution.time
focal_mechanism = event.focal_mechanisms[0]
half_duration = focal_mechanism.moment_tensor.source_time_function.duration/2.0
latitude = cmtsolution.latitude
longitude = cmtsolution.longitude
depth_... |
lmazuel/azure-sdk-for-python | azure-mgmt-storage/azure/mgmt/storage/v2016_01_01/models/storage_account_regenerate_key_parameters.py | Python | mit | 957 | 0 | # 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 ... | nerateKeyParameters(Model):
"""StorageAccountRegenerateKeyParameters.
:param key_name:
:type key_name: str
"""
_validation = {
'key_name': {'required': True},
}
_attribute_map = {
'key_name': {'key': 'keyName', 'type': 'str'},
}
def __init__(self, key_name):
... | init__()
self.key_name = key_name
|
sbsdev/daisyproducer | daisyproducer/documents/templatetags/verbose_name.py | Python | agpl-3.0 | 214 | 0.014019 | from django import template
from django.utils.text import capfirst
register = | template.Library()
@register.filter
def verbose_name(obj, arg):
return capfirst | (obj._meta.get_field(arg).verbose_name)
|
hpk42/pluggy | docs/conf.py | Python | mit | 2,375 | 0 | import sys
if sys.version_info >= (3, 8):
from importlib import metadata
else:
import importlib_metadata | as metadata
extensions = [
"sphinx.ex | t.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# General in... |
anthraxx/diffoscope | diffoscope/presenters/html/templates.py | Python | gpl-3.0 | 5,651 | 0.001062 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope 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,... | k;
color: white
}
.diffoscope .diffunmodified td {
background: #D0D0E0
}
.diffoscope .diffhunk td {
background: #A0A0A0
}
.diffoscope .diffadded td {
background: #CCFFCC
}
.diffoscope .diffdeleted td {
background: #FFCCCC
}
.diffoscope .diffchanged t... | oscope .comment {
font-style: italic;
}
.diffoscope .source {
font-weight: bold;
}
.diffoscope .error {
border: solid black 1px;
background: red;
color: white;
padding: 0.2em;
}
.diffoscope .anchor {
margin-left: 0.5em;
font-size: 80%%;
color... |
ptesarik/crash-python | crash/cache/syscache.py | Python | gpl-2.0 | 6,029 | 0.003981 | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.... | adavg_values()
self.loadavg = self.format_loadavg(metrics)
return self.loadavg
except DelayedAttributeError:
return "Unknown"
@classmethod
def setup | _jiffies(cls, symbol):
if cls.jiffies_ready:
return
jiffies_sym = gdb.lookup_global_symbol('jiffies_64')
if jiffies_sym:
try:
jiffies = long(jiffies_sym.value())
except gdb.MemoryError:
return False
cls.adjust_jiff... |
wackerly/faucet | faucet/valve_acl.py | Python | apache-2.0 | 6,809 | 0.000587 | """Compose ACLs on ports."""
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2018 The Contributors
#
# Licensed under the Apache Lic... | this, maybe this can be rewritten easily
# possibly replace with a class for ACLs
def build_acl_entry(rule_conf, meters,
acl_allow_inst, acl_force_port_vlan_inst,
port_num=None, vlan_vid=None):
acl_inst = []
acl_act = []
acl_match_dict = {}
acl_ofmsgs = []
acl... | nf.items()):
if attrib == 'in_port':
continue
if attrib == 'cookie':
acl_cookie = attrib_value
continue
if attrib == 'description':
continue
if attrib == 'actions':
allow = False
allow_specified = False
i... |
redhataccess/redhat-support-tool | src/redhat_support_tool/plugins/list_cases.py | Python | apache-2.0 | 17,874 | 0.001231 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | default='DESC')]
def _check_case_group(self):
if self._options['casegroup']:
valid_groups = []
given_groupAry = str(self._options['casegroup']).split(',')
real_gro | upAry = common.get_groups()
for i in given_groupAry:
match = False
for j in real_groupAry:
if i.lower() == j.get_name().lower() or \
i == str(j.get_number()):
valid_groups.append(j.get_number())
... |
ActiveState/code | recipes/Python/173071_ReseekFile/recipe-173071.py | Python | mit | 5,077 | 0.003151 | # Written in 2003 by Andrew Dalke, Dalke Scientific Software, LLC.
# This software has been released to the public domain. No
# copyright is asserted.
from cStringIO import StringIO
class ReseekFile:
"""wrap a file handle to allow seeks back to the beginning
Takes a file handle in the constructor.
... | g to
# the original input file.
if self._use_buffer == 0 and self.buffer_file.tell() == \
len(self.buffer_file.getvalue()):
# I'm doing this for the slightly better performance
self.seek = get | attr(self.file, "seek", None)
self.tell = getattr(self.file, "tell", None)
self.read = self.file.read
self.readline = self.file.readline
self.readlines = self.file.readlines
del self.buffer_file
def nobuffer(self):
"""tell the ReseekFile to stop u... |
joergdietrich/astropy | astropy/visualization/wcsaxes/tests/datasets.py | Python | bsd-3-clause | 1,655 | 0.000604 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Downloads the FITS files that are used in image testing and for building documentation.
"""
import time
from ....utils.data import download_file
from ....io import fits
__all__ = ['fetch_msx_hdu',
'fetch_rosat_hdu',
'fetch_twoMA... | (TIME_BETWEEN_RETRIES)
else:
break
else:
raise Exception("Failed to download file {0}".format(filename))
return fits.open(path)[0]
def fetch_msx_hdu(cache=True):
"""Fetch the MSX example dataset HDU.
Returns
-------
hdu : `~astropy.io.fits.ImageHDU`
Image H... | ch_hdu('galactic_center/gc_msx_e.fits', cache=cache)
def fetch_rosat_hdu(cache=True):
return fetch_hdu('allsky/allsky_rosat.fits', cache=cache)
def fetch_twoMASS_k_hdu(cache=True):
return fetch_hdu('galactic_center/gc_2mass_k.fits', cache=cache)
def fetch_l1448_co_hdu(cache=True):
return fetch_hdu('l1... |
funkring/fdoo | addons-funkring/subscription_invoice/__init__.py | Python | agpl-3.0 | 36 | 0.027778 | import wizar | d
import | account_invoice |
cytec/SickRage | lib/validators/__init__.py | Python | gpl-3.0 | 551 | 0 | from .between import between # noqa
from .domain import d | omain # noqa
from .email import email # noqa
from .extremes import Max, Min # noqa
from | .i18n import fi_business_id, fi_ssn # noqa
from .iban import iban # noqa
from .ip_address import ipv4, ipv6 # noqa
from .length import length # noqa
from .mac_address import mac_address # noqa
from .slug import slug # noqa
from .truthy import truthy # noqa
from .url import url # noqa
from .utils import Validati... |
Elico-Corp/odoo-addons | website_recaptcha/models/__init__.py | Python | agpl-3.0 | 1,075 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2014 Elico Co | rp. All Rights Reserved.
# Augustin Cisterne-Kaas <augustin.cisterne-kaas@elico-corp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licens... | 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with th... |
westfeld/fritz-speed | create-rra.py | Python | mit | 1,072 | 0.009328 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
create-rra.py
creates RRD file with 60 seconds primary step length
four datasources which are | counters
three RRA for one day, one week and one mont
"""
import fritzconnection
import r | rdtool
import os
from common import read_configuration
def get_link_speed():
fc = fritzconnection.FritzConnection()
status = fc.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')
downstream = status['NewLayer1DownstreamMaxBitRate'] / 8.
upstream = status['NewLayer1UpstreamMaxBitRate'] ... |
mopsalarm/pr0gramm-meta | update/main.py | Python | apache-2.0 | 13,461 | 0.001634 | #!/usr/bin/env python3
import argparse
import itertools
import queue
import re
import subprocess
import sys
import threading
import time
from collections import deque
from collections import namedtuple
from io import BytesIO
import datadog
import logbook
import pcc
import requests
from PIL import Image
from attrdict ... | erate_posts(start=None):
base_url = "http://pr0gramm.com/api/items/get?flags=7"
while True:
url = base_url + "&older=%d" % s | tart if start else base_url
# :type: requests.Response
with stats.timer(metric_name("request.feed")):
response = requests.get(url)
response.raise_for_status()
json = response.json()
for item in json["items"]:
item = Item(**item)
start... |
centrumholdings/buildbot | buildbot/status/web/authz.py | Python | gpl-2.0 | 2,513 | 0.003979 | from buildbot.status.web.auth import IAuth
class Authz(object):
"""Decide who can do what."""
knownActions = [
# If you add a new action here, be sure to also update the documentation
# at docs/cfg-statustargets.texinfo
'gracefulShutdown',
'forceBuild',
'forceAllBui... | get("username", ["<unknown>"])[0]
passwd = request.args.get("passwd", ["<no-password>"])[0]
if user == "<unknown>" or passwd == "<no-password>":
return False
if self.auth.authenticate(user, passwd):
if callable(cfg) and not cfg(user... | lse:
return True # anyone can do this..
|
sigopt/sigopt-python | test/orchestrate/services/aws_provider_bag_test.py | Python | mit | 1,060 | 0.00283 | import pytest
from mock import Mock
from sigopt.orchestrate.services.aws_provider_bag import AwsProviderServiceBag
class TestOrchestrateServiceBag(object):
@pytest.fixture
def orchestrate_services(self):
return Mock()
def test_orchestrate_service_bag(self, orchestrate_services):
services = AwsPr | oviderServiceBag(orchestrate_services)
assert services.cloudformation_service is not None
assert services.c | loudformation_service.client is not None
assert services.cloudformation_service.cloudformation is not None
assert services.ec2_service is not None
assert services.ec2_service.ec2 is not None
assert services.ecr_service is not None
assert services.ecr_service.client is not None
assert services.ek... |
nis-sdn/odenos | src/main/python/org/o3project/odenos/core/component/conversion_table.py | Python | apache-2.0 | 7,233 | 0.000138 | # -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | for port_id in del_port_list:
self.__del_entry_object(s | elf.__port_conversion_table,
port_id)
key = network_id + "::" + node_id
self.__del_entry_object(self.__node_conversion_table, key)
def del_entry_port(self, network_id, node_id, port_id):
key = network_id + "::" + node_id + "::" + port_id
self.__d... |
pstreck/django-videokit | videokit/fields.py | Python | mit | 9,739 | 0.006366 | from django.conf import settings
from django.core.files import File
from django.db.models.fields.files import FieldFile
from django.db.models.fields.files import FileDescriptor
from datetime import datetime
import os.path
import subprocess
from videokit.apps import VideokitConfig
from videokit.tasks import generate_v... | ame)
if os.path.isfile(path):
try:
process = subprocess.Popen(
['mediainfo', '--Inform=Video;%Width%', path],
stdout = subprocess.PIPE, stderr = subproce | ss.PIPE)
stdout, stderr = process.communicate()
if process.wait() == 0:
width = int(stdout.decode('utf8').strip(' \t\n\r'))
else:
return (0,0)
process = subprocess.Popen(
['mediainfo', '--Inform=Video;%Height%', path],
... |
KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/core/files/uploadhandler.py | Python | gpl-3.0 | 6,876 | 0.001454 | """
Base file upload handler classes, and the built-in concrete subclasses
"""
from __future__ import unicode_literals
from io import BytesIO
from django.conf import settings
from django.core.files.uploadedfile import (
InMemoryUploadedFile, TemporaryUploadedFile,
)
from django.utils.encoding import python_2_uni... | show a "connection reset" error.
"""
self.connection_reset = connection_reset
def __str__(self):
if self.connection_reset:
return 'StopUpload: Halt current upload.'
else:
return 'StopUpload: Consume request | data, then halt.'
class SkipFile(UploadFileException):
"""
This exception is raised by an upload handler that wants to skip a given file.
"""
pass
class StopFutureHandlers(UploadFileException):
"""
Upload handers that have handled a file and do not want future handlers to
run should rais... |
Diti24/python-ivi | ivi/agilent/agilent34410A.py | Python | mit | 4,335 | 0.008535 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 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... | he Software, and to permit persons | to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED... |
ojotoxy/iTerm2 | api/examples/python/remote_control.py | Python | gpl-2.0 | 3,599 | 0.012781 | #!/usr/bin/python
# This is python 2.7 on macOS 10.12.
from __future__ import print_function
import api_pb2
import sys
import thread
import time
import websocket
callbacks = []
DEBUG=0
def SendRPC(ws, message, callback):
if DEBUG > 0:
print(">>> " + str(message))
ws.send(message.SerializeToString(), o... | request.list_sessions_request.SetInParent()
SendRPC(ws, request, callback)
subscribe_to_new_sessions(ws)
list_sessions( | ws)
#websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:1912/",
on_message = on_message,
on_error = on_error,
on_close = on_close,
subprotocols = [ 'api.iterm2.com' ])
... |
MultimediaSemantics/entity2vec | scripts/old/page_links_to_edge_list_wiki.py | Python | apache-2.0 | 3,039 | 0.015466 | import optparse
import pickle
#converts urls to wiki_id
parser = optparse.OptionParser()
parser.add_option('-i','--input', dest = 'input_file', help = 'input_file')
parser.add_option('-o','--output', dest = 'output_file', help = 'output_file')
(options, args) = parser.parse_args()
if options.input_file is None:
... | .output_file is None:
options.output_file = raw_input('En | ter output file:')
input_file = options.input_file
output_file = options.output_file
#define the dictionary url:wiki_id
wiki_from_url_dict = {}
with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f:
for line in f:
line = line.split(' ')
if line[0] == '#':
continue
... |
InterestingLab/elasticmanager | elasticmanager/settings.py | Python | mit | 4,127 | 0.000727 | """
Django settings for elasticmanager project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... | long running tasks
# see http://docs.celeryproject.org/en/latest/userguide/optimizing.html#prefetch-limits
CELERYD_PREFETCH_MULTIPLIER = 1
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
# --- End of Celery Config --- |
# django-celery config
import djcelery
djcelery.setup_loader()
# --- End of django-celery Config ---
|
azafred/skeletor | tests/test_advanced.py | Python | bsd-2-clause | 267 | 0 | # -*- co | ding: utf-8 -*-
from .context import sample
import unittest
class AdvancedTestSuite(unittest.TestCase):
"""Advanced test cases."" | "
def test_thoughts(self):
self.assertIsNone(sample.main())
if __name__ == '__main__':
unittest.main()
|
jkozerski/meteo | meteo_lcd/update_meteo.py | Python | apache-2.0 | 20,586 | 0.018313 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Author:
# Janusz Kozerski (https://github.com/jkozerski)
# install:
# pip install python-dateutil
#
# for diagrams install:
# sudo python -m pip --no-cache-dir install -U matplotlib
#
# for database install:
# sqlite3 (apt-get install sqlite3)
#
#
# or for other diag... | uid/gid
| os.setgid(grp.getgrnam(default_user).gr_gid)
os.setuid(pwd.getpwnam(default_user).pw_uid)
except Exception as e:
print("Error while changing user." + str(e))
print "User changed from '" + user + "' to '" + default_user + "'."
###################################################... |
TallonRain/horsefaxbot | horsefax/telegram/events/threaded.py | Python | mit | 2,365 | 0.000846 | import threading
import queue
from . import BaseEventHandler, BaseEventQueue
class ThreadedEventHandler(BaseEventHandler):
"""
A threaded implementation of :class:`.BaseEventHandler`.
"""
def __init__(self):
self._handlers = {}
self._handle_map = {}
self._counter = 0
s... |
def __init__( | self, events, event):
self.queue = queue.Queue()
self.event_handler = events
self.handle = self.event_handler.register_handler(event, self._handle_event)
def _handle_event(self, arg):
self.queue.put(arg)
def close(self):
self.event_handler.unregister_handler(self.handle... |
wilhelm-murdoch/blink | setup.py | Python | mit | 479 | 0 | #!/usr/bin/env python
# -*- coding: utf | -8 -*-
from setuptools import setup, find_packages
from version import __version__
setup(
name='blink',
version=__version__,
description='Create jQuery-like eve | nts for your Python app.',
author='Wilhelm Murdoch',
author_email='wilhelm.murdoch@gmail.com',
url='http://www.thedrunkenepic.com/',
packages=find_packages(exclude=['tests']),
setup_requires=[
'nose==1.3.0',
'yanc==0.2.3'
]
)
|
HamutalCohen3/anyway | clusters_calculator.py | Python | bsd-3-clause | 1,569 | 0.003824 | from models import Marker
from static.pymapcluster import calculate_clusters
import time
import logging
import concurrent.futures
import multiprocessing
def retrieve_clusters(**kwargs):
marker_boxes = divide_to_boxes(kwargs['ne_lat'], kwargs['ne_lng'], kwargs['sw_lat'], kwargs['sw_lng'])
result_futures = []
... | = (ne_lat - sw_lat) / cpu_count
# lng_box_size = (sw_lng - ne_lng) / cpu_count
boxes = []
for i in xrange(cpu_count):
# TODO: the below calculation is using sw_lat as first param instead of ne_lat. Plz verify my fix for that:
# boxes.append((sw_lat + (i + 1) * lat_box_size, ne_lng, sw_lat +... | boxes.append({'ne_lat': ne_lat + (i + 1) * lat_box_size, 'ne_lng': ne_lng,
'sw_lat': sw_lat + i * lat_box_size, 'sw_lng': sw_lng})
return boxes
|
huangenyan/Lattish | project/mahjong/ai/base.py | Python | mit | 187 | 0 | # -*- coding: utf-8 -*-
class BaseAI(object):
player = None
table = None
| def __init__(self, player):
self.player = | player
def discard_tile(self):
pass
|
lsst-sims/sims_phosim_pythoncontrol | fullFocalplane.py | Python | gpl-3.0 | 11,426 | 0.009102 | #!/usr/bin/python
"""Perform preprocessing and generate raytrace exec scripts for one focal plane.
For documentation using the python_control for ImSim/PhoSim version <= v.3.0.x,
see README.v3.0.x.txt.
For documentation using the python_control for ImSim/PhoSim version == v.3.2.x,
see README.txt.
The behavior of th... | preprocessor.focalplane.observationID
files_to_stage = preprocessor.ArchiveRaytraceInputByExt(exec_archive_name=exec_manifest_fn)
if not files_to_stage:
logger.critical('Output archive step failed.')
return 1
with PhosimUtil.WithTimer() as t:
preprocessor.StageOutput(files_to_stage)
t.LogWall('Stage... | onfig_file, trimfile,
extra_commands)
missing_files = verifier.VerifySharedOutput()
if missing_files:
logger.critical('Verification failed with the following files missing:')
for fn in missing_files:
logger.critical(' %s', fn)
sys.stderr.write('Verific... |
pneerincx/easybuild-framework | easybuild/toolchains/linalg/__init__.py | Python | gpl-2.0 | 1,340 | 0.002239 | ##
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | /in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have receive... |
Jumpers/MysoftAutoTest | Step1-PythonBasic/Practices/wangr/31-35/ex31.py | Python | apache-2.0 | 1,033 | 0.019361 | #-*-coding:utf-8-*-
#coding=utf-8
print "you enter a dark room with two doors. Do you go through door #1 or door #2"
door = raw_input(">>>")
if door == "1":
print "there's a glant bear here eating a cheese cake. What do you do?"
print "1,Take the cake"
print "2,Scream at the bear"
bear = raw_in... | eats your legs off. Good job!"
else:
print "Well,doing %s is probably better.Bear runs away." % bear
elif door =="2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1, Blueberries"
print "2, Yellow jacket clothspins"
print "3, Understanding revolvers yelling me | lodies."
if insanity == "1" or insanity == "2":
print "you body survives powered by a mind of jello, Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
else:
print "you stumble around and fail on a knife and die. Good job!"
|
TalhaAsmal/Taming-Big-Data-Pyspark-Udemy | ratings-counter.py | Python | mit | 437 | 0 | from pyspark import SparkConf | , SparkContext
import collections
conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf=conf)
lines = sc.textFile("file:///SparkCourse/ml-100k/u.data")
ratings = lines.map(la | mbda x: x.split()[2])
result = ratings.countByValue()
sortedResults = collections.OrderedDict(sorted(result.items()))
for key, value in sortedResults.items():
print("%s %i" % (key, value))
|
BrythonServer/ggame | examples/assetcolor.py | Python | mit | 90 | 0 | "" | "
Example of using Color cl | ass.
"""
from ggame import Color
RED = Color(0xFF0000, 1.0)
|
claymation/pystogram | pystogram/histogram.py | Python | bsd-2-clause | 3,484 | 0.004879 | import datetime
from pystogram.tree import PrefixTree
SECOND = 1
MINUTE = SECOND * 60
HOUR = MINUTE * 60
DAY = HOUR * 24
MONTH = DAY * 30
YEAR = DAY * 365
# The multiplier applied when testing timestamp interval to guess a resolution.
# A value of 2.0 means the timestamp interval must be greater than 24 mon... | while timestamp <= last_sample:
node = self.tree.insert(prefix(timestamp, resolution))
bucket = Bucket(timestamp, node)
yield bucket
timestamp += bu | cket_interval
class Bucket(object):
"""
Histogram bucket for a given time interval.
"""
def __init__(self, start, node):
self.start = start
self.node = node
self.count = node.sum()
|
Razi91/BiblioTeKa | manage/management/commands/randoms.py | Python | gpl-2.0 | 5,194 | 0.024713 | __author__ = 'jkonieczny'
from books.models import *
import random
import datetime
from django.core.management.base import BaseCommand, CommandError
_names1 = [
"JAKUB",
"KACPER",
"SZYMON",
"MATEUSZ",
"FILIP",
"MICHAŁ",
"BARTOSZ",
"WIKTOR",
"PIOTR",
"DAWID",
"ADAM",
"M... |
entity = BookEntity()
| entity.title = title
entity.book = edition
entity.uuid = uuid.uuid4()
entity.quality = max(10, min(0, random.normalvariate(7, 5)))
entity.save()
|
sparkslabs/kamaelia_ | Sketches/RJL/Packages/Kamaelia/Community/RJL/Kamaelia/Util/ChunkNamer.py | Python | apache-2.0 | 3,315 | 0.006938 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | cense.
# -------------------------------------------------------------------------
# Licensed to the BBC under a Contributor Agreement: RJL
"""\
=========================
Chunk Namer
=========================
A component that labels each message with a unique filename for that message.
e.g. "A" ... "B" ... --> ["chun... |
-------------
Save each line entered to the console to a separate file:
pipeline(
ConsoleReader(),
ChunkNamer("test", ".txt"),
WholeFileWriter()
).run()
"""
from Axon.Component import component
from Axon.Ipc import producerFinished, shutdown
class ChunkNamer(component):
"""\
ChunkNamer() -> new ... |
krafczyk/spack | var/spack/repos/builtin/packages/mpir/package.py | Python | lgpl-2.1 | 2,446 | 0.000818 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | e 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 in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; with... | ore details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack impo... |
pmuller/versions | versions/compat.py | Python | mit | 273 | 0.007326 | import sys
MAJOR = sys.version_info[0]
if MAJOR == 3:
| cmp = lambda a, b: (a > b) - (a < b) # pragma: no cover
basestring = str # pragma: no cover
else: # hopefully MAJOR == 2
cmp = cmp # pragma: no cover
basestring = basestring # pragma: no | cover
|
csyhhu/L-OBS | PyTorch/ImageNet/validate-AlexNet.py | Python | mit | 2,746 | 0.011289 | """
This code validates the performance of AlexNet after L-OBS prunning
"""
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from models.alexnet import AlexNet
from utils import validate, adjust_mean_var
import numpy as np
from d... |
adjust_mean_var(net, train_loader, None)
print ('[% | s] Adjust finish. Now saving parameters' %(datetime.now()))
'''
# Load validation dataset
valdir = '/home/shangyu/imagenet-val'
print('==> Preparing data..')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, t... |
romanvm/django-tinymce4-lite | test_tinymce/views.py | Python | mit | 363 | 0 | from django.views.generic import CreateView, DetailView
from .models import TestModel
class TestCreateView(CreateView):
template_name = 'test_tinymce/create.html'
fields = ('content',)
model = TestModel
clas | s TestDisplayView(DetailView):
template_name = 'test_tin | ymce/display.html'
context_object_name = 'test_model'
model = TestModel
|
cjparsons74/Kupfer-cjparsons74 | kupfer/plugin/virtualbox/constants.py | Python | gpl-3.0 | 417 | 0.002404 | # -*- coding: UTF-8 -*-
'''
virtualbox_co | nst_support.py
Constants for VirtualBox.
'''
__author__ = "Karol Będkowski <karol.bedkowski@gmail.com>"
__version__ = '0.3'
# virtual machine states
VM_STATE_POWEROFF = 0
VM_STATE_POWERON = 1
VM_STATE_PAUSED = 2
# virtual machine actions
VM_START_NORMAL = 1
VM_START_HEADLESS = 2
VM_PAUSE = 3
VM_POWEROFF = 4
VM_ACPI_... | _SAVE = 8
|
lmzintgraf/MultiMAuS | authenticators/abstract_authenticator.py | Python | mit | 596 | 0.003356 | from abc import ABCMeta, abstractmethod
class AbstractAuthenticator(metaclass=ABCMeta):
def __init__(self):
"""
Every authenticator has to have a name
:param name:
"""
super().__ini | t__()
@abstractmethod
def authorise_transaction(self, customer):
"""
Decide whether to authorise transaction.
Note that all relevant information can be obtained from the customer.
:param customer: the customer making a transactio | n
:return: boolean, whether or not to authorise the transaction
"""
|
EBIvariation/eva-cttv-pipeline | tests/eva_cttv_pipeline/trait_mapping/test_main.py | Python | apache-2.0 | 2,363 | 0.003386 | #!/usr/bin/env python3
"""Tests for the trait mapping pipeline. Test resources are compressed XML files which contain one or a few records
manually extracted from the main ClinVar XML to check specific cases."""
import os
import tempfile
from eva_cttv_pipeline.trait_mapping.main import main
def get_test_resource(re... | ory where it is contained.
module_directory = os.path.dirname(this_module)
# Full path to the requested resource.
return os.path.join(module_directory, 'resources', resource_name)
def run_pipeline(resource_name):
"""Runs the pipeline on a given test resource and returns the output traits, automated m... | ."""
input_filename = get_test_resource(resource_name)
traits_file, mappings_file, curation_file = [tempfile.NamedTemporaryFile(delete=False) for _ in range(3)]
filters = {
'ontologies': 'efo,ordo,hp,mondo',
'required': 'cttv,eva-clinvar,clinvar-xrefs,gwas',
'preferred': 'eva-clinvar... |
chfoo/warcat | warcat/__init__.py | Python | gpl-3.0 | 130 | 0 | '''WARCAT: Web ARChive (WARC) Arch | iving Tool
Tool | and library for handling Web ARChive (WARC) files.
'''
from .version import *
|
plieningerweb/cumulocity-python-device-client | test/test_app.py | Python | mit | 698 | 0.005731 | import unittest
import app
try:
| from unittest import mock
except ImportError:
import mock
from Cumulocity import Cumulocity
class TestApp(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@mock.patch('Cumulocity.Cumulocity', spec=Cumulocity)
def testMeasurement(self, mock_cumulocity):
... | tance = mock_cumulocity.return_value
app.measure(c_instance)
expected_data = []
#check if we got exactly two calls
expected_calls = [
mock.ANY,
mock.ANY]
self.assertEqual(c_instance.addMeasurement.mock_calls, expected_calls)
|
bqbn/addons-server | src/olympia/translations/utils.py | Python | bsd-3-clause | 3,578 | 0.000559 | from django.template import engines
from django.utils.encoding import force_str
import html5lib
import jinja2
def truncate_text(text, limit, killwords=False, end='...'):
"""Return as many characters as possible without going over the limit.
Return the truncated text and the characters left before the limit,... | 'en-br': 'y'}
"""
in | itial = [
(k, v.localized_string)
for k, v in iter(initial.items())
if '%s_' % field in k and v is not None
]
data = [
('%s_%s' % (field, k), v) for k, v in iter(data[field].items()) if k != 'init'
]
return set(initial) != set(data)
|
ptitjes/quodlibet | quodlibet/library/libraries.py | Python | gpl-2.0 | 28,163 | 0 | # Copyright 2006 Joe Wreschnig
# 2013 Nick Boultbee
# 2013,2014 Christoph Reiter
#
# 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 y... | ed method and Librarians.
if not items:
return
print_d("Changing %d items." % len(items), self)
self.dirty = True
self.emit('changed', items)
def __iter__(self):
"""Iterate over the ite | ms in the library."""
return iter(self._contents.values())
def iteritems(self):
return iter(self._contents.items())
def iterkeys(self):
return iter(self._contents.keys())
def itervalues(self):
return iter(self._contents.values())
def __len__(self):
"""The numb... |
sestrella/ansible | test/units/modules/network/ios/test_ios_ping.py | Python | gpl-3.0 | 2,838 | 0.001409 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | dules.utils import set_module_args
from .ios_module import TestIosModule, load_fixture
class TestIosPingModule(TestIosModule):
''' Class used | for Unit Tests agains ios_ping module '''
module = ios_ping
def setUp(self):
super(TestIosPingModule, self).setUp()
self.mock_run_commands = patch('ansible.modules.network.ios.ios_ping.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
su... |
zgreatone/python-veralite | veralite/__init__.py | Python | lgpl-3.0 | 652 | 0 | # -*- coding:utf-8 -*-
from .veralite import Veralite
from .scene import Scene
from .device import Device
from | .device import DimmingLight
from .device import Switch
from .device import MotionSensor
from .exceptions import VeraliteException
from .exceptions import VeraliteConnectionError
from .exceptions import InvalidDeviceError
from .exceptions import InvalidSceneError
__all__ = ['Veralite',
'Scene',
'... |
'InvalidDeviceError',
'InvalidSceneError']
|
fraricci/pymatgen | pymatgen/analysis/diffraction/core.py | Python | mit | 7,522 | 0.000266 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import collections
import abc
import numpy as np
from pymatgen.core.spectrum import Spectrum
from pymatgen.util.plotting import add_fig_kwargs
"""
This module implements core classes for calculation of diff... | matplotlib.pyplot as plt
nrows = len(structures)
fig, axes = plt.subplots(nrows=nrows, ncols=1, sharex=True,
squeeze=False)
for i, (ax, structure) in enumerate(zip(axes.ravel(), structures)):
self.get_plot(structure,
fontsi... | bels=i == nrows - 1,
**kwargs)
spg_symbol, spg_number = structure.get_space_group_info()
ax.set_title("{} {} ({}) ".format(structure.formula, spg_symbol,
spg_number))
return fig
def get_unique_families(hkls):
... |
microhh/microhh | kernel_tuner/statistics.py | Python | gpl-3.0 | 1,185 | 0.008439 | import matplotlib.pyplot as pl
import numpy as np
import json
import glob
pl.close('all')
pl.ion()
def get_timings(kernel_name, gridsizes):
dt = np.zeros_like(gridsizes, dtype=float)
for i,gridsize in enumerate(gridsizes):
with open( '{0}_{1:03d}.json'.format(kernel_name, gridsize) ) as f:
... | return dt
if __name__ == '__main__':
gridsize = np.arange(32, 513, 32)
normal = get_timings('diff_c_g', gridsize)
smem = get_timings('diff_c_g_smem', gridsize)
fac = gridsize**3
pl.figure(figsize=(8,4))
pl.subplot(121)
pl.plot(gridsize, norm | al/fac, 'k-x', label='non smem')
pl.plot(gridsize, smem /fac, 'r-x', label='smem')
pl.ylim(0, 2e-7)
pl.ylabel('time/gridpoint (s)')
pl.xlabel('gridpoints (-)')
pl.legend()
pl.grid()
pl.subplot(122)
pl.plot(gridsize, normal/smem, 'k-x')
pl.ylabel('non_smem/smem (-)')
pl.xlabel('... |
sparkslabs/kamaelia_ | Sketches/AM/KPIPackage/Kamaelia/Community/AM/Kamaelia/KPIFramework/KPI/Server/DataTx.py | Python | apache-2.0 | 2,606 | 0.004221 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apach... | s under the License.
# -------------------------------------------------------------------------
#
"""
====================
DataTx
====================
The DataTx packetises the data. It adds p | acket header to the
How it works?
---------------------
The DataTx adds a header to the data received on its inboxes "keyin" and
"inbox". The packet header contains packet type and packet length.
It is necessary to distinguish between encrypted data to be sent and
encrypted session keys because the client nee... |
atvcaptain/enigma2 | lib/python/Screens/PowerLost.py | Python | gpl-2.0 | 1,103 | 0.023572 | from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.config import config
import Screens.Standby
from boxbranding import getMachineBrand, getMachineName
class PowerLost(Screen):
def __init__(self, session):
Screen.__init__(self, session)
... | ):
if ret:
if config.usage.shutdownNOK_action.valu | e == 'deepstandby' and not config.usage.shutdownOK.value:
self.session.open(Screens.Standby.TryQuitMainloop, 1)
elif not Screens.Standby.inStandby:
self.session.open(Screens.Standby.Standby)
self.close()
|
reclosedev/pyautocad | examples/lights.py | Python | bsd-2-clause | 1,272 | 0.005516 | #/usr/bin/env python
#-*- coding: utf-8 -*-
import re
import sys
from collections import namedtuple, defaultdict
from pyautocad import Autocad
from pyautocad import utils
LampEntry = namedtuple('LampEntry', 'number, mark, numxpower')
# \A1;2ARCTIC SMC/SAN 254 \S2х54/2,5;\P300 лк
def iter_lamps(acad, ob... | tion:
continue
text = utils.unformat_mtext(text)
m = re.search(ur'(?P<num>\d+)(?P<mark>.*?)\\S(?P<num_power>.*?)/.*?;', text)
if not m:
continue
print m.group('num'), m.group('mark'), m.group('num_power')
yield LampEntry(m.group('num'), m.group('mar... | selection('Select objects')
lamps = defaultdict(int)
for lamp in iter_lamps(acad, objects):
lamps[lamp.mark] += int(lamp.number)
print '-' * 79
for mark, number in sorted(lamps.iteritems()):
print '%-20s | %s' % (mark, number)
if __name__ == "__main__":
with utils.timing():... |
i3thuan5/gi2_liau7_khoo3 | 語言模型/apps.py | Python | mit | 99 | 0 | from django.apps import AppConfig
|
class 語言模型Config(AppConfig):
name = ' | 語言模型'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.