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 |
|---|---|---|---|---|---|---|---|---|
Pyroseza/Random | matrix_cool.py | Python | mit | 2,355 | 0.001274 | """
http://coreygoldberg.blogspot.com/2013/01/python-matrix-in-your-terminal.html
Create "The Matrix" of binary numbers scrolling vertically in your terminal.
original code adapted from juancarlospaco:
- http://ubuntuforum | s.org/showpost.php?p=10306676
Inspired by the movie: The Matrix
- Corey Goldberg (2013)
Requires:
- Linux
- Python 2.7 or 3+
"""
import fcntl
import time
import random
import struct
import sys
import termios
class message(str):
def __new__(cls, text, speed):
self = super(messa... | self.speed = speed
self.y = -1 * len(text)
self.x = random.randint(0, display().width)
self.skip = 0
return self
def move(self):
if self.speed > self.skip:
self.skip += 1
else:
self.skip = 0
self.y += 1
class ... |
aksh1/wagtail-cookiecutter-foundation | {{cookiecutter.repo_name}}/pages/templatetags/pages_tags.py | Python | mit | 58 | 0 | from dja | ngo import template
register = template.Library()
| |
dburkart/check-sieve | test/5229/variables_test.py | Python | mit | 1,796 | 0.000557 | from sys import platform
import unittest
import checksieve
class TestVariables(unittest.TestCase):
def test_set(self):
sieve = '''
require "variables";
set "honorific" "Mr";
'''
self.assertFalse(checksieve.parse_string(sieve, False))
def test_mod_length(self):
... | set :length "b" "${a}";
'''
self.assertFalse(checksieve.parse_string(sieve, False))
def test_wrong_tag(self):
sieve = '''
require "variables";
set :mime "b" "c";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
def test_set_wrong_arg(self):
... | checksieve.parse_string(sieve, True))
def test_too_many_args(self):
sieve = '''
require "variables";
set "a" "b" "c" "d";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
def test_test_string(self):
sieve = '''
require "variables";
set "... |
meerkat-code/meerkat_nest | meerkat_nest/resources/download_data.py | Python | mit | 862 | 0.008121 | """
Data resource for downloading data
"""
from flask_restful import Resource
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import json
import os
from pprint import pprint
from meerkat_nest import model
from meerkat_nest import config
db_url = os.environ['MEERKAT_NEST_DB_URL']
engine =... | esource):
def get(self):
"""
Not implemented. Initiates the download of the whole data set from Meerkat Nest
Returns:\n
HTTP return code\n
"""
Session = sessionmaker(bind=engine)
session = Session()
ret = {}
for table in config.... | all())
return ret
|
idea4bsd/idea4bsd | python/testData/copyPaste/AmbiguousParentBlockLargestIndent.after.py | Python | apache-2.0 | 113 | 0.00885 | d | ef f():
if True:
try:
pass
finally:
pass
| x = 42
pass |
rc500/ardrone_archive_aarons_laptop | multi_uav/network_config.py | Python | apache-2.0 | 1,371 | 0.043034 | """
Contains the network configuration for each drone.
Elements to update for each flight:
'host' - This is the IP which should be set on the drone - this will only update when changing drone network information
'bind_host' - This is the IP which is used by the network card/USB dongle to connect to the drone - this w... | "192.168.2.1", # NB - this is the IP which should be set on the drone
'control_host' : "127.0.0.1",
'at_port' : 5556,
'nav_port' : 5554,
'vid_port' : 5555,
'config_port' : 5659,
'control_port' : 5660,
'control_data_port' : 5661,
'video_data_port' : ... | '192.168.2.3',
};
|
clld/tsammalex | tsammalex/__init__.py | Python | apache-2.0 | 2,206 | 0.002267 | from zope.interface import classImplements
from pyramid.config import Configurator
from clld.interfaces import ILanguage, IMapMarker, IValueSet, IValue
from clld.web.app import MapMarker
from clld.db.models.common import Parameter_files
# we must mak | e sure custom models are known at database initialization!
from tsammalex import models
from tsammalex.interfaces import IEcoregion, IImage
# associate Parameter_files with the IImage interface to make the model work as resource.
classImplements(Parameter_files, IImage)
_ = lambda s: s
_('Parameter')
_('Parameters')... | ker(MapMarker):
def get_color(self, ctx, req):
lineage = None
if ctx and isinstance(ctx, (tuple, list)):
ctx = ctx[0]
if ILanguage.providedBy(ctx):
lineage = ctx.lineage
elif IValueSet.providedBy(ctx):
lineage = ctx.language.lineage
elif I... |
himanshusahay/resume-drop | mysite/resumedrop/migrations/0001_initial.py | Python | gpl-3.0 | 2,237 | 0.004917 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-11 22:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... | ext', models.CharField(default='Class Year', editable=False, max_length=10)),
],
),
migrations.CreateModel(
name='Name',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize= | False, verbose_name='ID')),
('name_text', models.CharField(default='Name', editable=False, max_length=4)),
],
),
migrations.CreateModel(
name='Resume',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fals... |
SergeySatskiy/codimension | codimension/ui/floatingrendererwindow.py | Python | gpl-3.0 | 12,510 | 0.000639 | # -*- coding: utf-8 -*-
#
# codimension - graphics python two-way code editor and analyzer
# Copyright (C) 2010-2019 Sergey Satskiy <sergey.satskiy@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 Softw... | availGeom = GlobalData().application.desktop().availableGeometry()
if self.width() + abs(self.settings['xdelta']) > availGeom.width() or \
self.height() + abs(self.settings['ydelta']) > availGeom.height():
return True
return F | alse
def restoreWindowPosition(self):
"""Makes sure that the window frame delta is proper"""
screenSize = GlobalData().application.desktop().screenGeometry()
if screenSize.width() != self.settings['screenwidth'] or \
screenSize.height() != self.settings['screenheight']:
... |
braysia/covertrace | covertrace/utils/kinase_estimation_inh.py | Python | mit | 4,757 | 0.003363 | from __future__ import division
import numpy as np
# import matplotlib.pyplot as plt
from scipy.integrate import odeint
# from scipy.interpolate import interp1d
from scipy.optimize import minimize
from ktr_shuttle_ode import main_ode, ParamHolder
# Parameters
'''r_total: Ths can be inferred experimentally or from the ... | centration and parameters,
calculate cytoplasmic-to-nuclear ratio at the pseudo-steady state.
"""
x = calc_rep_profile_at_steady_state(kin, pset)
return (x[0] + x[2])/(x[1] + x[3])
def inhibitor_ode(x, time, rcn_init, pset):
pset.k_dn, pset.k_d | c = x[0], x[0]
pset.Kmd = x[1]
rcn_final = x[2]
pset.time_points = [0, 1]
# Calculate kinase concentration at steady state such that it matches with rcn
kin0 = calc_active_kinase_at_steady_state(rcn=rcn_init, pset=pset)
# At given kinase concentration, calculate reporter profile.
y0 = calc_... |
guillaume-florent/aoc-utils | aocutils/brep/solid_make.py | Python | lgpl-3.0 | 2,302 | 0.000434 | # coding: utf-8
r"""Methods to make a solid"""
import functools
import OCC
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeSolid
from OCC.Core.BRepOffsetAPI import BRepOffsetAPI_MakePipe
# import OCC.TopoDS
from aocutils.common import AssertIsDone
from aocutils.brep.wire_make import polygon
from aocutils.bre... | port line
from aocutils.brep.face_make import face
from aocutils.operations.transform import translate
from aocutils.operations.sew import sew_shapes
@functools.wraps(BRepBuilderAPI_MakeSolid)
def solid(*args):
r"""Make a TopoDS_Solid
Parameters
----------
args
Returns
-------
TopoDS_Sol... | uilderAPI_MakeSolid (const TopoDS_CompSolid &S)
BRepBuilderAPI_MakeSolid (const TopoDS_Shell &S)
BRepBuilderAPI_MakeSolid (const TopoDS_Shell &S1, const TopoDS_Shell &S2)
BRepBuilderAPI_MakeSolid (const TopoDS_Shell &S1,
const TopoDS_Shell &S2,
con... |
arseneyr/essentia | test/src/unittest/synthesis/test_overlapadd_streaming.py | Python | agpl-3.0 | 5,943 | 0.017668 | #!/usr/bin/env python
# Copyright (C) 2006-2015 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... | return [ frame for frame in framegen ]
def analysisSynthesis(params, signal):
outsigna | l = array(0)
signal = numpy.append(signal, zeros(params['frameSize']/2))
frames = cutFrames(params, signal)
w = std.Windowing(type = "hann");
overl = std.OverlapAdd (frameSize = params['frameSize'], hopSize = params['hopSize']);
counter = 0
for f in frames:
of = w(f)
... |
bruecksen/isimip | isi_mip/climatemodels/migrations/0012_auto_20160411_1630.py | Python | mit | 775 | 0.0013 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-11 14:30
from __future__ import unicode_literals
from django.db impor | t migrations
import isi_mip.choiceorotherfield.models
class Migration(migrations.Migration):
dependencies = [
('climatemodels', '0011_auto_20160407_1050'),
]
operations = [
| migrations.AlterField(
model_name='impactmodel',
name='resolution',
field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')], help_text='The spatial resolution at which the ISIMIP simulations were run, if on a regular grid. Data was ... |
azumimuo/family-xbmc-addon | script.mrknow.urlresolver/lib/urlresolver9/plugins/lib/rijndael.py | Python | gpl-2.0 | 10,498 | 0.002477 | """
A pure python (slow) implementation of rijndael with a decent interface
To include -
from rijndael import rijndael
To do a key setup -
r = rijndael(key, block_size = 16)
key must be a string of length 16, 24, or 32
blocksize must be 16, 24, or 32. Default is 16
To use -
ciphertext = r.encrypt(plaintext)
plai... | hifts[SC][1][0]
s2 = shifts[SC][2][0]
s3 = shifts[SC][3][0]
a = [0] * BC
# temporary work array
t = []
# plaintext to ints + key
for i in range(BC):
t.append((ord(plaintext[i * 4]) << 24 |
ord(plaintext[i * 4 + 1]) << 16 |
... | ord(plaintext[i * 4 + 2]) << 8 |
ord(plaintext[i * 4 + 3])) ^ Ke[0][i])
# apply round transforms
for r in range(1, ROUNDS):
for i in range(BC):
a[i] = (T1[(t[i] >> 24) & 0xFF] ^
T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^
... |
pandas-dev/pandas | pandas/tests/reshape/test_pivot.py | Python | bsd-3-clause | 79,003 | 0.001354 | from datetime import (
date,
datetime,
timedelta,
)
from itertools import product
import numpy as np
import pytest
from pandas.errors import PerformanceWarning
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Grouper,
Index,
MultiIndex,
Series,
concat,
date... | "shiny",
"shiny",
],
"D": np.random.randn(11),
"E": np.random.randn(11),
"F": np.random.randn(11),
}
)
def test_pivot_table(self, observed):
index = ["A", "B"]
columns = "C"
table = pi... | olumns=columns, observed=observed
)
table2 = self.data.pivot_table(
values="D", index=index, columns=columns, observed=observed
)
tm.assert_frame_equal(table, table2)
# this works
pivot_table(self.data, values="D", index=index, observed=observed)
if... |
CLVsol/odoo_cl_addons | cl_todo/category/cl_todo_category.py | Python | agpl-3.0 | 4,706 | 0.004675 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | res = []
for record in reads:
name = record['name']
if record['parent_id']:
name = record['parent_id'][1] + ' / ' + name
res.append((record['id'], name))
return res
@api.model
def name_search(self, name, args=None, operator='ilike', limit... | + args
categories = self.search(args, limit=limit)
return categories.name_get()
@api.one
def _name_get_fnc(self):
self.refresh_complete_name = 0
complete_name = self.name_get()
if complete_name:
self.complete_name = complete_name[0][1]
else:
... |
samukasmk/smkcpanel | smkcpanel_django/smkcpanel/local_settings.py | Python | apache-2.0 | 882 | 0.005669 | import os
PROJECT_ROOT = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))
ROOT_URLCONF = 'smkcpanel.urls'
LOGIN_REDIRECT_URL = '/server'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don'... | LATE_DIRS += [os.path.join(PROJECT_ROOT, 'smkcpanel', 'templates')]
# TEMPLATE_DIRS += [os.path.join(PROJECT_ROOT, 'smkcpanel', 'dashboard', 'templates')]
# SESSION_ENGINE = 'django.contrib.sessions.backends.file'
# SESSION_FILE_PATH = os.path.join(PROJECT_ROOT, '../var/sessio | ns'), |
ESOedX/edx-platform | lms/djangoapps/instructor/settings/production.py | Python | agpl-3.0 | 888 | 0.002252 | """AWS environment variables unique to the instructor plugin."""
from __future__ import absolute_im | port
import warnings
def plugin_settings(settings):
"""Settings for the instructor plugin."""
# Analytics Dashboard
settings.ANALYTICS_DASHBOARD_URL = settings.ENV_TOKENS.get(
"ANALYTICS_DASHBOARD_URL", settings.ANALYTICS_DASHBOARD_URL
)
settings.ANALYTICS_DASHBOARD_NAME = settings.ENV_TO... | s.FEATURES:
warnings.warn(
"'ENABLE_S3_GRADE_DOWNLOADS' is deprecated. Please use 'ENABLE_GRADE_DOWNLOADS' instead",
DeprecationWarning,
)
settings.FEATURES['ENABLE_GRADE_DOWNLOADS'] = settings.FEATURES['ENABLE_S3_GRADE_DOWNLOADS']
|
youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py | Python | bsd-3-clause | 3,381 | 0.000887 | """
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import datetime
import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class PrintObjectArrayTestCase(TestBase):
mydir = TestBase.compu... | '[1] =',
'Hello',
'World',
'[2] =',
'Two =',
'1 ='])
self.expect(
'parray 3 objects',
substrs=[
'[0] = 0x',
'[1] = 0x',
'[2] = 0x'])
| self.expect(
'expr --element-count 3 -d run -- objects',
substrs=[
'3 elements',
'2 elements',
'2 key/value pairs'])
self.expect(
'expr --element-count 3 -d run --ptr-depth=1 -- objects',
substrs=[
... |
bezhermoso/home | setup.py | Python | gpl-3.0 | 1,396 | 0.005731 | #!/usr/bin/env python
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup
# find library modules
from ansible.constants import DEFAULT_MODULE_PATH
dirs=os.listdir("./librar | y/")
data_files = []
for i in dirs:
data_files.append((os.path.join(DEFAULT_MODULE_PATH, i), glob('./library/' + i + '/*')))
setup(name='a | nsible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='michael@ansibleworks.com',
url='http://ansibleworks.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML"],
package_dir={ 'ansible': 'lib/ansibl... |
hovo1990/deviser | generator/code_files/CppFiles.py | Python | lgpl-2.1 | 4,388 | 0.000684 | #!/usr/bin/env python
#
# @file CppFiles.py
# @brief class for generating cpp files
# @author Frank Bergmann
# @author Sarah Keating
#
# <!--------------------------------------------------------------------------
#
# Copyright (c) 2013-2015 by the California Institute of Technology
# (California, USA), the Euro... | sid_refs'] = \
query.get_sid_refs(class_object['attribs'])
self.class_object['unit_sid_refs'] = \
query.get_sid_refs(class_object['attribs'], unit=True)
self.verbose = verbose
def write_files(self):
se | lf.write_header(self.class_object)
self.write_code(self.class_object)
if self.class_object['hasListOf']:
lo_working_class = self.create_list_of_description()
self.write_header(lo_working_class)
self.write_code(lo_working_class)
def write_header(self, class_desc):... |
amdouglas/OpenPNM | test/unit/Network/GenericNetworkTest.py | Python | mit | 8,477 | 0 | import OpenPNM
import scipy as sp
class GenericNetworkTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[10, 10, 10])
def teardown_class(self):
ctrl = OpenPNM.Base.Controller()
ctrl.clear()
def test_find_connected_pores_numeric_not_flattend(self):
a = se... | n_flattend(self):
Tind = sp.zeros((self.net.Nt,), dtype=bool)
Tind[[0, 1]] = True
| a = self.net.find_connected_pores(throats=Tind, flatten=True)
assert sp.all(a == [0, 1, 2])
def test_find_connected_pores_empty_flattend(self):
a = self.net.find_connected_pores(throats=[], flatten=True)
assert sp.shape(a) == (0, 2)
def test_find_neighbor_pores_numeric(self):
... |
mehdy/py-trello | trello/util.py | Python | bsd-3-clause | 4,017 | 0.00224 | # -*- coding: utf-8 -*-
from __future__ import with_statement, print_function, absolute_import
import os
from requests_oauthlib import OAuth1Session
def create_oauth_token(expiration=None, scope=None, key=None, secret=None, name=None, output=True):
"""
Script to obtain an OAuth token from Trello.
Must ha... | in your
environment settings (eg. 'never'), otherwise it will default to 30 days.
More info on token scope here:
https://trello.com/docs/gettingstarted/#getting-a-token-from-a-us | er
"""
request_token_url = 'https://trello.com/1/OAuthGetRequestToken'
authorize_url = 'https://trello.com/1/OAuthAuthorizeToken'
access_token_url = 'https://trello.com/1/OAuthGetAccessToken'
expiration = expiration or os.environ.get('TRELLO_EXPIRATION', "30days")
scope = scope or os.environ.ge... |
Kmayankkr/robocomp | tools/robocompdsl/templates/templatePython/plugins/base/functions/src/main_py.py | Python | gpl-3.0 | 454 | 0.006608 | import datetime
import sys
from string import Temp | late
from dsl_parsers.parsing_utils import communication_is_ice, get_name_number, IDSLPool
from templates.common.templatedict import TemplateDict
class src_main_py(TemplateDict):
def __init__(self, component):
super(src_main_py, self).__init__()
self.component = component
self['year'] | = str(datetime.date.today().year)
self['component_name'] = self.component.name
|
adybbroe/atrain_match | atrain_match/reshaped_files_scr/plot_kuipers_on_area.py | Python | gpl-3.0 | 19,755 | 0.014022 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Read all matched data and make some plotting
"""
import os
from glob import glob
import numpy as np
from matchobject_io import (readTruthImagerMatchObj,
CalipsoImagerTrackObject)
from plot_kuipers_on_area_util import (PerformancePlottingObjec... | iles = files +glob(ROOT_DIR + "Reshaped_Files_merged_calipso_cbase/eos2/1km/2010/08/*.h5")
| files = files +glob(ROOT_DIR + "Reshaped_Files_merged_calipso_cbase/eos2/1km/2010/10/*.h5")
#files = files +glob(ROOT |
numixproject/circle-core | tests/ordered_db.py | Python | gpl-3.0 | 1,931 | 0 | #!/usr/bin/env python3
"""
# Copyright (C) 2016
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 3+) as
# publi | shed by the Free Software Foundation. You should have received
# a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
"""
from os import path
import json
from collections import OrderedDict
from utils import sort | , error
ABS_PATH = path.dirname(path.abspath(__file__))
DB_FILE = path.realpath(path.join(ABS_PATH, "../data.json"))
with open(DB_FILE, 'r') as db_obj:
data = json.load(db_obj, object_pairs_hook=OrderedDict)
keys = list(data.keys())
ordreded_keys = sort(keys)
has_errors = False
for i in range(len(keys)):
... |
aljoscha/flink | flink-python/pyflink/datastream/connectors.py | Python | apache-2.0 | 28,847 | 0.004715 | ################################################################################
# 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... | avepoint. When the consumer is restored from a checkpoint or
savepoint, only the offsets in the restored state will be used.
"""
self._j_function = self._j_function.setStartFromGroupOffsets()
return self
def disable_filter_restored_partitions_with_subscribed_topics(self) -> 'FlinkKa... | current specified topics or topic
pattern to subscribe to.
This method does not affect where partitions are read from when the consumer is restored
from a checkpoint or savepoint. When the consumer is restored from a checkpoint or
savepoint, only the offsets in the restored state will ... |
AccelerateNetworks/FusionPBX-Contact-Importer | cidlookup.py | Python | gpl-3.0 | 773 | 0.002587 | #!/usr/bin/env python
import urllib2
import json
| import freeswitch
CNAM_PHP = "http://localhost/app/contact-importer/cnam.php"
def handler(session, args):
"""Do the CID lookup (against our php service...)."""
response = urllib2.urlopen("%s?call=%s&format=json" % (CNAM_PHP, session.getVariable("uuid")))
| data = json.load(response)
if "error" in data:
freeswitch.consoleLog("error", str(data['error']))
else:
for key, value in data.iteritems():
freeswitch.consoleLog("info", str("%s=%s" % (key, value)))
session.execute("set", str("%s=%s" % (key, value)))
if "effec... |
liucode/tempest-master | tempest/api/compute/images/test_list_image_filters.py | Python | apache-2.0 | 12,355 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | or i in images
if i['id'] == self.snapshot1_id]),
"Failed to find image %s in images. Got images %s" %
(self. | image1_id, images))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot2_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.snapshot3_id]))
@test.idempotent_id('05a377b8-28cf-4734-a1e6-2ab5c38bf606')
@testto... |
djs55/ffs | volume/org.xen.xapi.storage.rawnfs/sr.py | Python | lgpl-2.1 | 1,847 | 0.001083 | #!/usr/bin/env python
from common import mountpoint_root
import errno
import urlparse
import os
import os.path
import subprocess
import sys
import xapi
import xapi.storage.api.volume
from xapi.storage import log
class Implementation(xapi.storage.api.volume.SR_skeleton):
def probe(self, dbg, uri):
raise ... | u = urlparse.urlparse(uri)
mountpoint = mountpoint_root + "/" + u.netloc + "/" + u.path
try:
os.ma | kedirs(mountpoint)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(mountpoint):
pass
else:
raise
if not os.path.ismount(mountpoint):
cmd = ["mount", "-t", "nfs",
"-o", "acdirmin=0,acdirmax=0",
... |
darkpixel/statuspage | status/api.py | Python | bsd-3-clause | 1,878 | 0.003727 | from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS
from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py
from .models import Inciden... | ame'
queryset = Status.objects.all()
allowed_methods = ['get']
resource_name = 'st | atus'
authentication = ApiKeyAuthentication()
authorization = Authorization()
class IncidentResource(ReadOnlyFieldNamespacedModelResource):
status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True)
#TODO: We need to include the related user object at some point
... |
PepperPD/edx-pepper-platform | lms/djangoapps/courseware/features/youtube_setup.py | Python | agpl-3.0 | 1,256 | 0.002389 | #pylint: disable=C0111
#pylint: disable=W0621
from courseware.mock_youtube_server.mock_youtube_server import MockYoutubeServer
from lettu | ce import before, after, world
from django.conf import settings
import threading
from logging import getLogger
logger = getLogger(__name__)
@before.all
def setup_mock_youtube_server():
# import ipdb; ipdb.set_trace()
server_host = '127.0.0.1'
server_port = settings.VIDEO_PORT
address = | (server_host, server_port)
# Create the mock server instance
server = MockYoutubeServer(address)
logger.debug("Youtube server started at {} port".format(str(server_port)))
server.time_to_response = 1 # seconds
# Start the server running in a separate daemon thread
# Because the thread is a d... |
tbarchyn/STAB_1.0 | operations/execute_.py | Python | gpl-3.0 | 4,077 | 0.014471 | # STAB: subglacial till advection and bedforms
# Thomas E. Barchyn - University of Calgary, Calgary, AB, Canada
# Copyright 2014-2016 Thomas E. Barchyn
# Contact: Thomas E. Barchyn [tbarchyn@gmail.com]
# This project was developed with input from Thomas P.F. Dowling,
# Chris R. Stokes, and Chris H. Hugenholtz. We wou... | xecute the model in verbose mode
"""
if os.name == 'nt':
stab_corename = 'stab.exe' # windows corename
elif os.name == 'posix':
stab_corename = 'stab'
else:
print ('platform is undefined! platform = ' + os.name)
sys.exit()
# first thing we need to... | ile_in) # get the base
sim_name = simfile_base.replace ('.simfile', '') # strip .simfile
exec_dir = os.path.join (processing_dir_in, sim_name) # set the execution directory
# make the exec_dir, but allow it to previously exist (if re-running simulations)
if not os.path.isdi... |
Furzoom/learnpython | usefull_scripts/write_to_file.py | Python | mit | 187 | 0.005348 | #!/usr/bin/env pyth | on
#-*- coding: utf-8 -*-
f = open('data.txt', 'w')
size = f.write('Hello\n')
f.write('World\n')
f.close()
f = open('data. | txt')
text = f.read()
print(text)
f.close()
|
arviz-devs/arviz | setup.py | Python | apache-2.0 | 2,583 | 0.000774 | import codecs
import os
import re
import setuptools
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt")
RE... | "Framework :: Matplotlib",
"Intended Audience :: Science/Research",
"Intended Audience :: Education",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3... | /Engineering :: Visualization",
"Topic :: Scientific/Engineering :: Mathematics",
],
)
|
mornelon/QtCreator_compliments | tests/system/shared/hook_utils.py | Python | lgpl-2.1 | 19,422 | 0.00623 | import re
# flag that caches the information whether Windows firewall is running or not
fireWallState = None
# this function modifies all necessary run settings to make it possible to hook into
# the application compiled by Creator
def modifyRunSettingsForHookInto(projectName, port):
prepareBuildSettings(1, 0)
... | "Qt version: %s, mkspec: %s, Qt LibPath: %s, qmake: '%s'"
% (qtVersion, mkspec, qtLibPath, qmake))
return None
squishPath = getSquishPath(mkspec, qtVersion)
if squishPath == None:
test.warning("Could not determine the Squish path for %s/%s" % (qtVersion, mkspec)... | qtVersion, mkspec, squishPath))
if platform.system() == "Darwin":
qmlViewer = os.path.abspath(os.path.dirname(qmake) + "/QMLViewer.app")
else:
qmlViewer = os.path.abspath(os.path.dirname(qmake) + "/qmlviewer")
if platform.system() in ('Microsoft', 'Windows'):
qmlViewer = qmlViewer + ... |
ghackebeil/PyORAM | examples/path_oram_file.py | Python | mit | 2,687 | 0.001861 | #
# This example measures the performance of Path ORAM
# when storage is accessed through a local file.
#
import os
import ra | ndom
import time
import pyoram
from pyoram.util.misc import MemorySize
from pyoram.oblivious_storage.tree.path_oram import \
PathORAM
import tqdm
pyoram.config.SHOW_PROGRESS_BAR = True
# Set the storage location and size
storage_name = "h | eap.bin"
# 4KB block size
block_size = 4000
# one block per bucket in the
# storage heap of height 8
block_count = 2**(8+1)-1
def main():
print("Storage Name: %s" % (storage_name))
print("Block Count: %s" % (block_count))
print("Block Size: %s" % (MemorySize(block_size)))
print("Total Memory: %s"
... |
gdamjan/convertor | setup.py | Python | agpl-3.0 | 1,692 | 0.021277 | #!/usr/bin/env python
# "convertor" - converts ODF files from a YUSCII font-encoding to proper UTF-8.
# Copyright (C) 2009 Damjan Georgievski
#
# 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 S... | onvertor'],
package_data | = {},
keywords = "ODF",
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 3.6'
],
test_suite = '',
zip_safe = False,
entry_points = {
'console_scripts':
['convertor=convertor.__main__:main']
... |
Bysmyyr/chromium-crosswalk | tools/telemetry/telemetry/web_perf/metrics/smoothness_unittest.py | Python | bsd-3-clause | 13,635 | 0.00308 | # Copyright 2014 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.
import unittest
from telemetry.internal.results import page_test_results
from telemetry.page import page as page_module
from telemetry.web_perf.metrics impo... | _event_latency', stats.input_event_latency)
self.assertEquals | (30, mean_value.value)
self.assertEquals(60, discrepancy_value.value)
def testComputeLatencyMetricWithMissingData(self):
stats = _MockRenderingStats(frame_timestamps=self.good_timestamps,
input_event_latency=[[], []])
value = self.metric._ComputeLatencyMetric(
self.... |
lonvia/Nominatim | nominatim/db/utils.py | Python | gpl-2.0 | 3,126 | 0.002559 | """
Helper functions for handling DB accesses.
"""
import subprocess
import logging
import gzip
import io
from nominatim.db.connection import get_pg_env
from nominatim.errors import UsageError
LOG = logging.getLogger()
def _pipe_to_proc(proc, fdesc):
chunk = fdesc.read(2048)
while chunk and proc.poll() is No... | olumn).translate(_SQL_TRANSLATION))
self.buffer.write('\n')
def copy_out(self, cur, table, columns=None):
"" | " Copy all collected data into the given table.
"""
if self.buffer.tell() > 0:
self.buffer.seek(0)
cur.copy_from(self.buffer, table, columns=columns)
|
spadgenske/TYOS | apps/camera/app.py | Python | mit | 8,419 | 0.007008 | #Camera App
#copyright (c) 2015 Tyler Spadgenske
# MIT License
import sys
import pygame
import picamera
import io
import yuv2rgb
import os
import time
from subprocess import Popen
class Stream():
def __init__(self):
self.mode = 'capture'
self.deleted = False
self.uploading = False
... | images/left.png')
self.home = pygame.image.load('/home/pi/tyos/apps/camera/images/home.png')
self.upload = pygame.image.load('/home/pi/tyos/apps/camera/images/upload.png')
self.delete = pygame.image.load('/home/pi/tyos/apps/camera/images/trash.png')
self.deleted_image = pygame.image.load... | es_image = pygame.image.load('/home/pi/tyos/apps/camera/images/nofiles.png')
def display(self):
while True:
if self.mode == 'gallery':
self.screen.blit(self.image_in_view, (0,0))
self.screen.blit(self.left, (20, 410))
... |
swfiua/django_eulasees | django_eulasees/migrations/0002_auto_20141206_1419.py | Python | bsd-3-clause | 670 | 0.001493 | # -*- coding: utf-8 | -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('django_eulasees', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='snippettag',
name='snippet',
... | s.ForeignKey(default=0, to='django_eulasees.EulaSnippet'),
preserve_default=False,
),
migrations.AlterField(
model_name='snippettag',
name='tag',
field=models.ForeignKey(to='django_eulasees.Tag'),
preserve_default=True,
),
]
|
gregbaker/dynmodel | dynmodel/model.py | Python | gpl-2.0 | 18,776 | 0.009214 | import sys
import random
from variables import Variable, StateVariables
try:
from criticalx import interpn, index
except ImportError:
sys.stderr.write("Can't import Cython implementation. Falling back to slower pure-Python.\n")
from critical import interpn, index
if __debug__:
import types
import ... | return self.__qual[self.index(t, state)]
def decision(self, t, *state):
"""
Return the decision value at the given time and state.
"""
return self.__dec[self.index(t, state)]
def decision0(self, t, state):
"""
Return the decision value at the given time and sta... | nternal use, but could be used outside
as well.
"""
return self.__dec[self.index(t, state)]
#################################################################
# Linear Interpolation
def interp(self, t, *state):
"""
Interpolate to (possibly) fractional values of t... |
CAMI-challenge/AMBER | src/plots.py | Python | apache-2.0 | 26,475 | 0.004193 | # Copyright 2020 Department of Computational Biology for Infection Research - Helmholtz Centre for Infection Research
#
# 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 Li... | og(pd_bins_precision['genome_id'].map(coverages_pd['COVERAGE'].to_dict()))
plot_by_genome_coverage(pd_bins_precision, 'precision_bp', available_tools, output_dir)
def plot_heatmap(df_confusion, sample_id, output_dir, label, separate_bar=False, log_scale=False):
if log_scale:
df_confusion = df_confusio... | 0)
fig, axs = plt.subplots(figsize=(10, 8))
fontsize = 20
# replace columns and rows labels by numbers
d = {value: key for (key, value) in enumerate(df_confusion.columns.tolist(), 1)}
df_confusion = df_confusion.rename(index=str, columns=d)
df_confusion.index = range(1, len(df_confusion) + 1)
... |
mitlib-tdm/foist | tests/test_app.py | Python | apache-2.0 | 9,664 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import requests
import xml.etree.ElementTree as ET
from foist import (create_container, parse_text_encoding_errors, Thesis,
transaction, upload_file, update_metadata)
from foist.namespaces import BIBO, DCTYPE, PCDM
def ... | 'Institute of Technology, Computation for '
'Design and Opti | mization Program, 2006.')
assert t.department == ['Department One', 'Department Two']
assert t.encoded_text is True
assert t.handle == 'http://hdl.handle.net/1721.1/39208'
assert t.handle_part == '39208'
assert t.issue_date == '2006'
assert t.ligatures is None
assert t.no_full_text is True
... |
wesm/impyla | impala/dbapi.py | Python | apache-2.0 | 6,149 | 0.000163 | # Copyright 2013 Cloudera 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 applicable law or agreed to in writing... | d.
.. deprecated:: 0.11.0
ldap_password : str, optional
Use `password` parameter instead.
.. deprecated:: 0.11.0
use_kerberos : bool, optional
Specify `auth_mechanism='GSSAPI'` inst | ead.
.. deprecated:: 0.11.0
protocol : str, optional
Do not use. HiveServer2 is the only protocol currently supported.
.. deprecated:: 0.11.0
Returns
-------
HiveServer2Connection
A `Connection` object (DB API 2.0-compliant).
"""
# pylint: disable=too-many-lo... |
z25/pyZOCP | docs/conf.py | Python | lgpl-3.0 | 8,197 | 0.006222 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ZOCP documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 5 17:56:43 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | pend as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, | do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
autodoc_member_or |
yeti-platform/yeti | plugins/analytics/public/hash_file.py | Python | apache-2.0 | 1,405 | 0 | import hashlib
from core.analytics import InlineAnalytics
from core.observables import Hash
HASH_TYPES_DICT = {
"md5": hashlib.md5,
"sha1": hashlib.sha1,
"sha256": hashlib.sha256,
"sha512": hashlib.sha512,
}
class HashFile(InlineAnalytics):
default_values = {
"name": "HashFile",
... | hash_object = Hash.get_or_create(value=h.hexdigest())
hash_object.add_source("analytics")
hash_object.save()
f.active_link_to(
hash_object,
"{} hash".format(hash_type.upper()),
"HashFile",
... | |
Zlash65/erpnext | erpnext/assets/doctype/location/location.py | Python | gpl-3.0 | 6,182 | 0.024102 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import json
import math
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import flt
fro... | 'point_type') == 'circle':
layer_area += math.pi * math.pow(feature.get('properties').get('radius'), 2)
return layer_area
def _polygon_area(coords):
if not coords:
return 0
area = abs(_ring_area(coords[0]))
for i in range(1, len(coords)):
area -= abs(_ring_area(coords[i]))
return area
def _ring_area... | in range(coords_length):
if i == coords_length - 2: # i = N-2
lower_index = coords_length - 2
middle_index = coords_length - 1
upper_index = 0
elif i == coords_length - 1: # i = N-1
lower_index = coords_length - 1
middle_index = 0
upper_index = 1
else: # i = 0 to N-3
lower_index... |
ijmarshall/robotreviewer3 | robotreviewer/ml/ner_config.py | Python | gpl-3.0 | 2,854 | 0.012263 | import os
import robotreviewer
from robotreviewer.ml.ner_data_utils import get_trimmed_glove_vectors, load_vocab, \
get_processing_word
class Config():
def __init__(self, load=True):
"""Initialize hyperparameters and load vocabs
Args:
load_embeddings: (bool) if True, load embedd... | ilename_chars = os.path.join(robotreviewer.DATA_ROOT, "pico_spans/chars.txt")
# training
train_embeddings = False
nepochs = 15
dropout = 0.5
batch_ | size = 20
lr_method = "adam"
lr = 0.001
lr_decay = 0.9
clip = -1 # if negative, no clipping
nepoch_no_imprv = 3
# model hyperparameters
hidden_size_char = 100 # lstm on chars
hidden_size_lstm = 200 # lstm on word embeddings
# NOTE: if... |
cmbiwer/pycbc | pycbc/pool.py | Python | gpl-3.0 | 4,235 | 0.002361 | """ Tools for creating pools of worker processes
"""
from __future__ import absolute_import
import multiprocessing.pool
import functools
from multiprocessing import TimeoutError
import types
import signal
import atexit
def is_main_process():
""" Check if this is the main control process and may handle one time tas... | esses=None, initializer=None, initargs=(), **kwds):
global _process_lock
global _numdone
_process_lock = multiprocessing.Lock()
_numdone = multiprocessing.Value('i', 0)
noint = functools.partial(_noint, initializer)
super(BroadcastPool, self).__init__(processes, noint, in... | """ Do a function call on every worker.
Parameters
----------
fcn: funtion
Function to call.
args: tuple
The arguments for Pool.map
"""
results = self.map(_lockstep_fcn, [(len(self), fcn, args)] * len(self))
_numdone.value = 0
retu... |
desk467/pyxel | src/pxl_sprite.py | Python | mit | 150 | 0.013333 | from | pxl_object import PxlObject
from pxl_vector import PxlVector
class PxlSprite(PxlObject):
def __init__(self, size, position):
| pass
|
tmcdonnell87/bananas | bananas/apps/message/migrations/0002_add_send_events.py | Python | mit | 1,300 | 0.002308 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-09-11 01:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('message', '0001_initial'),
]
operations = [
migrations.RemoveField(
... | to send this message.', null=True),
),
migrations.AddField(
model_name='messagetemplate',
name='send_event',
field=models.CharField(choices=[('c', 'Appointment Created'), ('u', 'Appointment Updated'), ('d', 'Appointment Deleted'), ('a', 'Appointment Attended')], defau... |
),
migrations.AlterField(
model_name='messagetemplate',
name='send_time',
field=models.TimeField(help_text='The clock time to send a message', null=True),
),
]
|
jrg365/gpytorch | gpytorch/priors/smoothed_box_prior.py | Python | mit | 2,544 | 0.001965 | #!/usr/bin/env python3
import math
from numbers import Number
import torch
from torch.distributions import constraints
from torch.distributions.utils import broadcast_all
from torch.nn import Module as TModule
from .prior import Prior
from .torch_priors import NormalPrior
class SmoothedBoxPrior(Prior):
r"""A s... | igma
self.register_buffer("a", _a)
self.register_buffer("b", _b)
self.register_buffer("sigma", _sigma.clone())
self.tails = NormalPrior(torch.zeros_like(_a), _sigma, validate_args=validate_args)
self._transform = transform
@property
def _c(self):
return (self.a +... | def _r(self):
return (self.b - self.a) / 2
@property
def _M(self):
# normalization factor to make this a probability distribution
return torch.log(1 + (self.b - self.a) / (math.sqrt(2 * math.pi) * self.sigma))
def log_prob(self, x):
return self._log_prob(self.transform(x)... |
beernarrd/gramps | gramps/gui/editors/displaytabs/srcattrembedlist.py | Python | gpl-2.0 | 5,553 | 0.004682 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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 you... | et_data()
data.append(name)
se | lf.changed = True
self.rebuild()
GLib.idle_add(self.tree.scroll_to_cell, len(data)-1)
def edit_button_clicked(self, obj):
attr = self.get_selected()
if attr:
pname = ''
try:
self.get_editor()(
self.dbstate, self.uistate, se... |
djsilenceboy/LearnTest | Python_Test/PyDataMiningSample/com/djs/learn/test/ura/TestPreprocessTransactionData2.py | Python | apache-2.0 | 518 | 0 | '''
Preprocess URA merged data.
Update log: (date / versio | n / author : comments)
2020-06-06 / 1.0.0 / Du Jiang | : Creation
'''
from com.djs.learn.ura import PreprocessData
__data_type = 0
__base_file_name = "URA_CondoEcTrans_M"
__input_file_path = "../../../../../Temp/{0}.csv".format(__base_file_name)
argv = ["-d", __data_type, "-i", __input_file_path]
PreprocessData.main(argv)
'''
Or run:
python PreprocessData.py -d 0 -i ... |
lukefrasera/fatigueBSN | scripts/include/test_h7PolarRead.py | Python | gpl-3.0 | 363 | 0.008264 |
import time
import bluetooth
from h7PolarDataPoints import h7PolarDataPoint
from h7PolarDataPointReader import h7PolarDataPoi | ntReader
if __name__ == '__main__':
h7PolarDataPointReader = h7PolarDataPointReader()
h7PolarDataPointReader.start()
while(True):
dataPoint = h7PolarDataPointReader.readNextDataPoint()
p | rint (dataPoint) |
caedesvvv/metanomon | metanomon/nomon.py | Python | gpl-3.0 | 13,700 | 0.003942 | #!/usr/bin/env python
import gtk
import pango
from kiwi.ui.gadgets import quit_if_last
from kiwi.ui.delegates import GladeDelegate
from kiwi.ui.objectlist import ObjectList, Column, ObjectTree
from xmlrpclib import ServerProxy
from urllib import urlencode
import gtkmozembed
import gtksourceview
#import gtksource... | )
#self.document.write_stream(text)
#self.document.close_stream()
def put_page(self, text, summary, minor):
pars = {}
if summary:
pars['sum'] = summary
if minor:
pars['minor'] = minor
self._rpc.wiki.putPage(self.current, text, pars)
if... | def add_page(self, page):
name = page["id"]
path = name.split(":")
prev = None
for i,pathm in enumerate(path):
if i == len(path)-1: # a page
new = DictWrapper(page, pathm)
self._sections[name] = new
self.objectlist.append(prev... |
Lehoang89/Python-plot | Histogram/export_3d.py | Python | cc0-1.0 | 1,437 | 0.016006 | import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm as CM
from matplotlib import mlab as ML
import numpy as NP
import matplotlib.pyplot as PLT
import re
import math
x = []
y = []
z= []
u = []
v = []
w = []
| count = 0
f = open("10mm_true.txt")
for line in iter(f):
xa = line.split( )
x.append(float(xa[0]))
y.append(float(xa[1]))
# | z.append(float(xa[2]))
if (float(xa[0]) * float(xa[0]) + float(xa[1]) * float(xa[1]) < 10*10):
v.append(1)
u.append(math.sqrt(float(xa[4]) * float(xa[4]) + float(xa[3]) * float(xa[3])))
else:
v.append(0)
u.append(0)
#v.append(float(xa[4]))
... |
shupelneker/gae_new_structure | config/__init__.py | Python | lgpl-3.0 | 745 | 0.002685 | """
This configuration file loads environment's specific config settings for the application.
It takes precedence over the config located in the boilerplate package | .
"""
import os
if os.environ['HTTP_HOST'] == "appengine.beecoss.com":
# Load Boilerplate config only in http://appengine.beecoss.com
# this code is here just for testing purposes
from config.boilerplate import config
elif "SERVER_SOFTWARE" in os.environ:
if os.environ['SERVER_SOFTWARE'].startswith('D... | oduction import config
else:
raise ValueError("Environment undetected")
else:
from config.testing import config |
protwis/protwis | construct/functions.py | Python | apache-2.0 | 79,499 | 0.011688 | from django.conf import settings
from django.utils.text import slugify
from django.db import IntegrityError, connection
from protein.models import Protein, ProteinConformation
from residue.models import Residue
from structure.models import Structure
from construct.models import *
from ligand.models import Ligand, Liga... | ta_dir, pdbname + '.pdb'])
if not os.path.isfile(pdb_path):
url = 'https://www.rcsb.org/pdb/files/%s.pdb' % pdbname
pdbdata_raw = urlopen(url).read().decode('utf-8')
with open(pdb_path, 'w') as f:
| f.write(pdbdata_raw)
else:
with open(pdb_path, 'r') as pdb_file:
pdbdata_raw = pdb_file.read()
if new_xtal==False:
try:
structure = Structure.objects.filter(pdb_code__index=d['construct_crystal']['pdb'].upper()).get()
if 1==1: #update ... |
jmalacho/ansible-examples | filter_plugins/users.py | Python | apache-2.0 | 344 | 0.037791 | # Jinja2 filters | for user creation help
# Needed for chage
def daysSinceEpoc( _unused=0 ):
import datetime
return (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).days
# Boilerplate code to add filter to Jinja2
class FilterModule(object):
def filters(self):
return { 'daysSinceEpoc': daysSinceEpoc,
| }
|
Compjeff/PokemonGo-Bot | pokemongo_bot/cell_workers/complete_tutorial.py | Python | mit | 4,839 | 0.002893 | import random
from pokemongo_bot import logger
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot.human_behaviour import sleep
class CompleteTutorial(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.api = self.bo... | else:
self.logger.error('Error trying to set nickname')
return False
# FIRST_TIME_EXPERIENCE_COMPLETE = 7
| if not 7 in tutorial_state:
if self._set_tutorial_state(7):
self.logger.info('Completed first time experience')
else:
return False
return True
def _encounter_tutorial(self):
# You just need to call the API with the pokemon you choose
... |
DIRACGrid/DIRAC | src/DIRAC/Core/Utilities/Version.py | Python | gpl-3.0 | 822 | 0.002433 | import importlib
from importlib.metadata import version as get_version
from DIRAC import S_OK
from DIRAC.Core.Utilities.Extensions import extensionsByPriority
def getCurrentVersion():
"""Get a string corresponding to the current version of the DIRAC package and all the installed
extension packages
"""
... | try:
return S_OK(importlib.import_module(ext).version)
except (ImportError, AttributeError):
pass
def getVersion():
"""Get a dictionary corresponding to the current version of the DIRAC package and all the installed
extension packages
"""
vDict = {"Extensions": {}... | n = get_version(ext)
vDict["Extensions"][ext] = version
return S_OK(vDict)
|
taedori81/shoop | shoop/front/views/category.py | Python | agpl-3.0 | 2,056 | 0.001459 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop 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 tree.
from __future__ import with_statement
from django import forms
from django.... | manufacturers = form.cleaned_data.get("manufacturers")
if manufacturers:
filters["manufacturer__in"] = manufacturers
products = Product.objects.list_visi | ble(
customer=self.request.customer,
shop=self.request.shop
).filter(**filters).distinct()
products = cache_product_things(self.request, products)
products = sort_products(self.request, products, self.request.GET.get("sort"))
context["products"] = products
... |
desarrollogt-frm-utn/reservas | app_reservas/admin/tipoLaboratorio.py | Python | mit | 341 | 0.002959 | # coding=utf-8
from django.contrib import admin
from ..models import TipoLaboratorio
@admin.register(TipoLaboratorio)
class TipoLaboratorioAdmin(admin.ModelAdmin):
"""
Especificación de la representación de TipoLaboratorio | en la i | nterfaz de administración.
"""
list_display = (
'nombre',
'slug',
)
|
tillahoffmann/util | tests/test_util.py | Python | mit | 757 | 0.001321 | import util
import numpy as np
import pytest
import tensorflow as tf
def test_acorr():
x = np.random.normal(0, 1, 1000)
y = util.acorr(x)
assert x.size - 1 == y.size, "unexpected autocorrelation size"
@pytest.mark.parametrize('value, desired', [
('Hello World!', False),
([1, 2, 3], True),
((... | ble(value, desired):
assert util.iterable(value) == desired, "incorrect result for `it | erable`"
@pytest.mark.parametrize('value, reference, desired', [
("a", "bdaef", 2),
("ab", "bdaef", [2, 0])
])
def test_list_index(value, reference, desired):
assert util.list_index(reference, *value) == desired, "incorrect result for `list_index`"
|
couchbaselabs/litmus | webapp/settings.py | Python | apache-2.0 | 2,790 | 0 | # Django settings for cbmonitor project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'cbmonitor.db'
}
}
# Local time zone for this installation.
TIME_ZONE = 'America/Los_Angeles'
# Language code for this installatio... | iles.
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static').replace('\\', | '/'),
)
# 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.staticfiles.finders.DefaultStorageFinder',
)
# Make this u... |
fxfitz/ansible | lib/ansible/modules/network/junos/junos_config.py | Python | gpl-3.0 | 13,712 | 0.001677 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | unos import commit_configuration, discard_changes, locked_config
from ansible.module_utils.network.junos.junos import junos_argument_spec, load_configuration, tostring
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native, to_text
try:
from lxml.etree import Element, fr... | string
try:
from lxml.etree import ParseError
except ImportError:
try:
from xml.etree.ElementTree import ParseError
except ImportError:
# for Python < 2.7
from xml.parsers.expat import ExpatError
ParseError = ExpatError
USE_PERSISTENT_CONNECTION = True
DEFAULT_COMMENT = 'co... |
podiobooks/podiobooks | podiobooks/management/commands/clear_cache.py | Python | gpl-3.0 | 345 | 0 | """Clears the Cache"" | "
from django.core.cache import cache
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Clears the Cache
"""
help = "Clears the Cache"
def handle(self, **options):
"""Clears the Cache"""
cache.clear()
self.stdout.write('Cleared cac | he\n')
|
ArchiveTeam/tinyarchive | twitter_spritzer_import.py | Python | gpl-3.0 | 7,952 | 0.006288 | #!/usr/bin/env python
# TinyArchive - A tiny web archive
# Copyright (C) 2012 David Triendl
#
# 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 opti... | to"]: # URLs are not stable, probably not a shortener(?)
continue
elif ps.hostname == "su.pr":
service = "supr"
elif ps.hostname == "soc.li": # URLs are not stable, appears to be spam(?)
contin | ue
elif ps.hostname == "plurk.com": # Only redirects to www.plurk.com/CODE
continue
elif ps.hostname == "htn.to":
service = "htnto"
elif ps.hostname == "kvs.co": # Only redirects to kanvaso.com/show/CODE
continue
elif ps.hostname == "mypict.me": # TODO
continue
elif p... |
rosswhitfield/javelin | javelin/_version.py | Python | mit | 18,463 | 0 | # flake8: noqa
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that j... |
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is no... | ich we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].s... |
stormi/tsunami | src/secondaires/jeux/plateaux/oie/pion.py | Python | bsd-3-clause | 1,992 | 0.003521 | # -*-coding:Utf-8 -*
# Copyright (c) 2012 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# l... | UT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier définissant la classe Pion, détaillée plus bas."""
from abstraits.obase import BaseObj
class Pio | n(BaseObj):
"""Classe représentant un pion."""
def __init__(self, couleur, numero):
"""Constructeur du pion."""
BaseObj.__init__(self)
self.couleur = couleur
self.numero = numero
self._construire()
def __getnewargs__(self):
return ("", 0)
|
zctea/biocode | gff/report_basic_gff_model_agreement.py | Python | gpl-3.0 | 3,802 | 0.012625 | #!/usr/bin/env python3
"""
This script will take two generic gff3 files that contain gene structure
annotation and compare them. When a model from file A has identical coordinates
to a model contained in file B, this is considered an identity match.
Every part of the gene model is compared. For each gene, the follow... | genes = list()
for feat_id in features:
feat = feature | s[feat_id]
if feat.__class__.__name__ == 'Gene':
genes.append(feat)
return genes
if __name__ == '__main__':
main()
|
hakatashi/youtube-dl | youtube_dl/extractor/nrk.py | Python | unlicense | 24,502 | 0.000899 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse_unquote,
)
from ..utils import (
ExtractorError,
int_or_none,
JSON_LD_RE,
NO_DEFAULT,
parse_age_limit,
parse_duration,
try_get,... | nd_time,
'title': point.get('title'),
})
if chapters and len(entries) == 1:
entries[0]['chapters'] = chapters
return self.playlist_result(entries, video_id, title, description)
class NRKIE(NRKBaseIE):
_VALID_URL = r'''(?x)
... | (?:www\.)?nrk\.no/video/PS\*|
v8[-.]psapi\.nrk\.no/mediaelement/
)
)
(?P<id>[^?#&]+)
'''
_API_HOSTS = ('psapi.nrk.no', 'v8-psapi.nrk.no')
... |
zimmerman-zimmerman/OIPA | OIPA/iati_synchroniser/migrations/0027_merge_20210914_1033.py | Python | agpl-3.0 | 306 | 0 | # Generated by Django 2.0.13 on 2021-09-14 10:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('iati_synchroniser', '0026_dataset_old_date_marker | '),
('iati_synchroniser', '0026_int | erruptincrementalparse'),
]
operations = [
]
|
openpolis/op-verify | project/verify/management/commands/generi_in_istituzioni.py | Python | bsd-3-clause | 3,219 | 0.004663 | # -*- coding: utf-8 -*-
from collections import OrderedDict
import locale
from optparse import make_option
from verify.management.commands import VerifyBaseCommand
from verify.models import *
from verify.politici_models import *
from django.db.models import Q, Count
__author__ = 'guglielmo'
class Command(VerifyBase... | filter(id__in=charge_types_ids)
for charge_type in charge_types:
self.logger.info(
"Counting {0} in {1}".format(
| charge_type.name, institution.name
)
)
qs = OpInstitutionCharge.objects.using('politici').\
filter(date_end__isnull=True,
content__deleted_at__isnull=True).\
filter(institution=institution,
... |
BurtBiel/azure-cli | src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/tests/test_validators.py | Python | mit | 1,205 | 0.006639 | #---------------------------------- | -----------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Lic | ensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------------------------------
import unittest
from six import StringIO
from azure.cli.command_modules.resource._validators import (validate_parent, validate_resour... |
fyookball/electrum | lib/__init__.py | Python | mit | 644 | 0.001553 | from .version import PACKAGE_VERSION
from .util import format_satoshis, print_msg, print_error, set_verbosity
from .wallet import Synchronizer, Wallet
from .storage import WalletStorage
from .network import Network, pick_random_server
from .interface import Connection, Interface
from .simple_config import SimpleConfig,... | mmands import Commands, known_command | s
from . import address
from . import cashacct # has a side-effect: registers itself with ScriptOut protocol system
|
JNero/shiyanlou | wenbenjiexiqi/rules.py | Python | gpl-3.0 | 1,355 | 0.077226 | class Rule:
'''
规则父类
'''
def action(self,block,handler):
'''
加标记
'''
handler.start(self.type)
handler.feed(block)
handler.end(self.type)
return True
class HeadingRule(Rule):
'''
一号标题规则
'''
type='heading'
def condition(self,block):
'''
判断文本块是否符合规则
'''
return not '\n' in block and len(bloc... | ndler.start(self.type)
handler.feed(block[1:].strip())
handler.end(self.type)
return True
class ListRule(ListItemRule):
'''
列表规则
'''
type ='list'
inside=False
def condition(self,block):
return True
def action(self,block,handler):
if not self.inside and ListItemRule.condition(self,block):
handler.s... | f.inside and not ListItemRule.condition(self,block):
handler.end(self,type)
self.inside=False
return False
class ParagraphRule(Rule):
'''
段落规则
'''
type='paragraph'
def condition(self,block):
return True |
ernestyalumni/Propulsion | ccdroplet/ccdroplet/__init__.py | Python | gpl-2.0 | 69 | 0 | import CCDrop | let
import CC_params
import CC_out
import LiquidVaporEq | |
qinq-net/sandbox | Solution3/MyLibThread/MyLibThread.py | Python | gpl-3.0 | 355 | 0.03662 | #!/usr/bin/env python3
import threading
cl | ass thread(threading.Thread):
a,b=True,False
def __init__(self):
threading.Thread.__init__(self,target=self.targ | et,daemon=True)
def target(self):
# do something here
while True:
if self.a: self.b = False
else: self.b = True
import sys
sys.stderr.write() |
weidel-p/nest-simulator | pynest/nest/lib/hl_api_exceptions.py | Python | gpl-2.0 | 9,411 | 0.002975 | # -*- coding: utf-8 -*-
#
# hl_api_exceptions.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 Licen... | f {}.
""".format(errorname, parent.__name__)
try:
__init__.__doc__ = docstring
except AttributeError:
__init__.__func__.__doc__ = docstring
return __init__
# source: the dynamically created exceptions come from SLI
# default_parent: the dynamically ... | ception descended from SLIException
# these should be updated when new exceptions in sli are created that aren't directly descended
# from SLIException (but nothing bad will happen, it's just that otherwise they'll be directly
# descended from SLIException instead of an intermedia... |
supermari0/ironic | ironic/api/controllers/v1/node.py | Python | apache-2.0 | 45,509 | 0.000308 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | ethod
def sample(cls):
console = {'type': 'shellinabox', 'url': 'http://<hostname>:4201'}
return cls(console_enabled=True, console_info=console)
class NodeConsoleController(rest.RestController):
@expose.expose(ConsoleInfo, types.uuid_or_name)
def get(self, node_ident):
"""Get conn... | ical name of a node.
"""
rpc_node = api_utils.get_rpc_node(node_ident)
|
apache/incubator-airflow | airflow/contrib/operators/imap_attachment_to_s3_operator.py | Python | apache-2.0 | 1,197 | 0.000835 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF | licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 Licen... |
openattic/openattic | backend/ceph_radosgw/tests.py | Python | gpl-2.0 | 3,934 | 0.001779 | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package is distributed in the hope that it wi | ll 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.
"""
from ceph_radosgw.rgw_ | client import RGWClient
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from rest_framework import status
from sysutils.database_utils import make_default_admin
import json
import mock
class RGWClientTestCase(TestCase):
@staticmethod
def _mock_settings(S... |
sergeyf/scikit-learn | examples/decomposition/plot_pca_3d.py | Python | bsd-3-clause | 2,259 | 0.000885 | # -*- coding: utf-8 -*-
"""
=========================================================
Principal components analysis (PCA)
=========================================================
These figures aid in illustrating how a point cloud
can be very flat in one direction--which is where PCA
comes in to choose a direction th... | om.normal(scale=0.5, size=(30000))
z = np.random.normal(scale=0.1, size=len(x))
density = pdf(x) * pdf(y)
pdf_z = pdf(5 * z)
density *= pdf_z
a = x + y
b = 2 * y
c = a - b + z
norm = np.sqrt(a.var() + b.var())
a /= norm
b /= norm
# ## | ###########################################################################
# Plot the figures
def plot_figs(fig_num, elev, azim):
fig = plt.figure(fig_num, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=elev, azim=azim)
ax.scatter(a[::10], b[::10], c[::10], c=density[::10], mark... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_chart_chartarea02.py | Python | bsd-2-clause | 1,604 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
chart.axis_ids = [82933248, 82952960]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10], |
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_ser... |
cpennington/edx-platform | openedx/core/djangoapps/embargo/tests/test_api.py | Python | agpl-3.0 | 13,897 | 0.002087 | """
Tests for EmbargoMiddleware
"""
from contextlib import contextmanager
import geoip2.database
import maxminddb
import ddt
import mock
from mock import patch, MagicMock
from django.conf import settings
from django.test.utils import override_settings
from django.core.cache import cache
from django.db import connec... | elf.course = CourseFactory.create()
self.user = UserFactory.create()
self.restricted_course = RestrictedCourse.objects.create(course_key=self.course.id)
Country.objects.create(country='US')
Country.objects.create(country='IR')
Country.objects.create(country='CU')
# Clear... | t, whitelist, allow_access
('US', None, [], [], True),
('IR', None, ['IR', 'CU'], [], False),
('US', 'IR', ['IR', 'CU'], [], False),
('IR', 'IR', ['IR', 'CU'], [], False),
('US', None, [], ['US'], True),
('IR', None, [], ['US'], False),
('US', 'IR', [], ['US'], Fa... |
SCPR/firetracker | calfire_tracker/templatetags/tracker_tags.py | Python | gpl-2.0 | 5,772 | 0.003638 | from django.template import Library, Context
from django.conf import settings
from django.utils.timezone import utc
from django.db.models import Q, Avg, Max, Min, Sum, Count
from calfire_tracker.models import CalWildfire, WildfireDisplayContent
from dateutil import parser
from datetime import datetime, date, time... | pprint(columns(range(i), 3), width=20)
7x3:
[[0, 3, 6],
[1, 4],
[2, 5]]
8x3:
[[0, 3, 6],
[1, 4, 7],
[2, 5]]
9x3:
[[0, 3, 6],
[1, 4, 7],
[2, 5, 8]]
10x3:
[[0, 4, 8],
[1, 5, 9],
... | be
# present:
>>> pprint(columns(range(4), 3), width=10)
[[0, 2],
[1, 3]]
"""
try:
n = int(n)
thelist = list(thelist)
except (ValueError, TypeError):
return [thelist]
list_len = len(thelist)
split = list_len // n
if list_len ... |
AustralianAntarcticDataCentre/metadata_xml_convert | print_xsl.py | Python | mit | 376 | 0.013298 | import logging
import os
from settings import CONVERSIONS, LOGGING_KWARGS, XSL_PATH
logger = logging.getLogger(__name__)
def print_xsl_files( | ):
for index, parts in enumerate(CONVERSIONS):
file_path = os.path.join(XSL_PATH, parts[0])
pr | int('{}: {}'.format(index + 1, file_path))
if '__main__' == __name__:
logging.basicConfig(**LOGGING_KWARGS)
print_xsl_files()
|
Digitalminion/api-django-inbound | inbound/urls.py | Python | mit | 351 | 0.002849 | from django.conf.urls import patterns, include, url
from inbound.views import *
urlpatterns = patterns('',
url(r'capture/lead/', AddVisitorToCRM.as_view()),
url(r'capture/session/', LogSession.as_view()),
url(r'c | apture/alignment/', LogAlignment.a | s_view()),
) |
LCAS/spqrel_tools | ros_ws/src/naoqi_bridge/naoqi_driver_py/setup.py | Python | mit | 311 | 0.006431 | ## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup |
from catkin_pk | g.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['naoqi_driver'],
package_dir={'': 'src'})
setup(**setup_args)
|
burnpanck/traits | traits/tests/test_range.py | Python | bsd-3-clause | 2,646 | 0 | # Copyright (c) 2007, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http:// | www.enthought.com/licenses/BSD.txt
from __future__ import absolute_import
from traits.testing.unittest_tools import unittest
from ..api import HasTraits, Int, Range, Str, TraitError
class WithFloatRange(HasTraits):
r = Range(0.0, 100.0)
r_copied_on_change = Str
_changed_handler_calls = Int
def _r... | (self.r % 10) > 0:
self.r += 10 - (self.r % 10)
class WithLargeIntRange(HasTraits):
r = Range(0, 1000)
r_copied_on_change = Str
_changed_handler_calls = Int
def _r_changed(self, old, new):
self._changed_handler_calls += 1
self.r_copied_on_change = str(self.r)
if ... |
edx-solutions/edx-platform | common/djangoapps/third_party_auth/tests/utils.py | Python | agpl-3.0 | 4,741 | 0.001266 | """Common utility for testing third party oauth2 features."""
import json
from base64 import b64encode
import httpretty
from onelogin.saml2.utils import OneLogin_Saml2_Utils
from oauth2_provider.models import Application
from social_core.backends.facebook import API_VERSION as FACEBOOK_API_VERSION
from social_core.b... | th_client = self._create_client()
if self.BACKEND == 'google-oauth2':
self.configure_google_provider(enabled=True, visible=True | )
elif self.BACKEND == 'facebook':
self.configure_facebook_provider(enabled=True, visible=True)
def tearDown(self):
super(ThirdPartyOAuthTestMixin, self).tearDown()
Partial.objects.all().delete()
def _create_client(self):
"""
Create an OAuth2 client applicat... |
mccolgst/www.gittip.com | tests/py/test_for_community_json.py | Python | cc0-1.0 | 1,994 | 0 | import json
from gratipay.models.community import slugize
from gratipay.testing import Harness
class TestForCommunityJson(Harness):
def setUp(self):
Harness.setUp(self)
self.add_participant('alice')
self.add_participant('bob')
carl = self.add_participant('carl')
carl.inse... | assert len(result['membe | rs']) == 2
assert result['name'] == 'test'
def test_post_not_supported(self):
response = self.client.PxST('/for/test/index.json')
assert response.code == 405
def test_limit(self):
response = self.client.GET('/for/test/index.json?limit=1')
result = json.loads(response.bo... |
bxlab/HiFive_Paper | Scripts/Support/compile_mapping_stats.py | Python | bsd-3-clause | 1,882 | 0.007439 | #!/usr/bin/env python
#(c) 2014 Emory University. All Rights Reserved
# Code written by: Michael Sauria (mgehrin@emory.edu)
import sys
import glob
def main():
stats_prefix, out_fname = sys.argv[1:3]
stats_fnames = glob.glob("%s*" % stats_prefix)
ordered_fnames = {}
for fname in stats_fnames:
... | nt' or n | ame == '-m':
stats[name] += int(line.split(':')[1].split('(')[0].strip(' '))
print >> output, "Overall Stats"
print >> output, "# reads processed: %i" % (stats['processed'])
print >> output, "# reads with at least one reported alignment: %i (%0.2f%%)" % (stats['alignment'],
... |
OCA/partner-contact | base_partner_sequence/models/partner.py | Python | agpl-3.0 | 2,422 | 0 | # Copyright 2004-2009 Tiny SPRL (<https://tiny.be>).
# Copyright 2013 initOS GmbH & Co. KG (<https://www.initos.com>).
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2016 Camptocamp - Akim Juillerat (<https://www.camptocamp.com>).
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo... |
@api.model
def create(self, vals):
if not vals.get("ref") and self._needs_ref(vals=vals):
vals["ref"] = self._get_next_ref(vals=vals)
return super(ResPartner, self).create(vals)
def copy(self, | default=None):
default = default or {}
if self._needs_ref():
default["ref"] = self._get_next_ref()
return super(ResPartner, self).copy(default=default)
def write(self, vals):
for partner in self:
partner_vals = vals.copy()
if (
not... |
MrLokans/MoonReader_tools | moonreader_tools/parsers/__init__.py | Python | mit | 178 | 0 | fro | m .fb2_parser import FB2NoteParser
fr | om .pdf_parser import PDFNoteParser
from .stat_parser import StatsAccessor
__all__ = ("FB2NoteParser", "PDFNoteParser", "StatsAccessor")
|
skosukhin/spack | var/spack/repos/builtin/packages/r-dbi/package.py | Python | lgpl-2.1 | 1,758 | 0.000569 | ##############################################################################
# Copyright (c) 2013-2017, 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... | #############################
from spack import *
class RDbi(RPackage):
"""A database interface definition for communication between R and
relational database management systems. All classes in this package are
virtual and need to be extended by the various R/DBMS implementations."""
homepage = "http... | ersion('0.4-1', 'c7ee8f1c5037c2284e99c62698d0f087')
version('0.7', '66065dd687d758b72d638adb6a8cab2e')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.