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 |
|---|---|---|---|---|---|---|---|---|
lsaffre/blog | docs/blog/2011/0527.py | Python | agpl-3.0 | 806 | 0.017677 | # -*- coding: UTF-8 -*-
import logging
unicode_string = u"Татьяна"
utf8_string = "'Татьяна' is an invalid string value"
logging.warning(unicode_string)
logging.warning(utf8_string)
try:
raise Exception(utf8_string)
except Exception,e:
print "--- (Log a traceback of the exception):"
logging.exception(e... | )
from django.utils.encoding | import force_unicode
logging.warning(u"4 Deferred %s : %s",unicode_string,force_unicode(utf8_string))
|
AccelAI/accel.ai | flask-aws/lib/python2.7/site-packages/blessed/sequences.py | Python | mit | 26,038 | 0.000154 | # encoding: utf-8
" This sub-module provides 'sequence awareness' for blessed."
__author__ = 'Jeff Quast <[email protected]>'
__license__ = 'MIT | '
__all__ = ('init_sequence_patterns', 'Sequence', 'SequenceTextWrapper',)
# built-ins
import functools
import textwrap
import warnings
import math
import sys
import re
# local
from ._binterms import binary_terminals as _BINTERM_UNSUPPORTED
# 3rd-party
import wcwidth # https://github.com | /jquast/wcwidth
_BINTERM_UNSUPPORTED_MSG = (
u"Terminal kind {0!r} contains binary-packed capabilities, blessed "
u"is likely to fail to measure the length of its sequences.")
if sys.version_info[0] == 3:
text_type = str
else:
text_type = unicode # noqa
def _merge_sequences(inp):
"""Merge a lis... |
stxnext-kindergarten/presence-analyzer-agrochowski | src/presence_analyzer/__init__.py | Python | mit | 97 | 0 | # -*- coding: utf-8 -*-
from .main import app
from . im | port views
"""
Initial | ize the package
"""
|
ntt-sic/nova | nova/tests/api/openstack/compute/contrib/test_certificates.py | Python | apache-2.0 | 2,810 | 0 | # Copyright (c) 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 ... | pecific language governing permissions and limitations
# under the License.
from lxml import etree
from nova.api.openstack.compute.contrib import certificates
from nova import context
from nova.openstack.common import rpc
from nova import test
from nova.tests.api.openstack import fakes
def f | ake_get_root_cert(context, *args, **kwargs):
return 'fakeroot'
def fake_create_cert(context, *args, **kwargs):
return 'fakepk', 'fakecert'
class CertificatesTest(test.NoDBTestCase):
def setUp(self):
super(CertificatesTest, self).setUp()
self.context = context.RequestContext('fake', 'fake... |
iksws/GnomeTurboNoteExtension | turbonote-adds/notestyle.py | Python | gpl-3.0 | 10,601 | 0.016602 | from gi.repository import Gtk, Gdk,GObject,Pango
import commands
import time
import sys,os
import threading
import sqlite3
from config_note import Config
config_note = Config()
path = "/usr/share/gnome-shell/extensions/[email protected]/turbonote-adds/"
path_icon = "/usr/share/gnome-shell/extensions/turbonote@iks... | l()
sel | f.space4.set_text(" ")
self.space5 = Gtk.Label()
self.space5.set_text(" ")
self.title_body = Gtk.Label()
self.title_body.set_text("Body Components")
self.title_title = Gtk.Label()
self.title_title.set_text("Title Components")
self.noteTextLabel =... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/google/protobuf/any_pb2.py | Python | bsd-2-clause | 2,652 | 0.006787 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/any.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflecti... | rl', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containi | ng_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='google.protobuf.Any.value', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=No... |
bartscheers/tkp | tkp/accessors/aartfaaccasaimage.py | Python | bsd-2-clause | 1,347 | 0 | import logging
from tkp.accessors import CasaImage
logger = logging.getLogger(__name__)
class AartfaacCasaImage(CasaImage):
def __init__(self, url, plane=0, beam=None):
super(AartfaacCasaImage, self).__init__(url, plane=0, beam=None)
self.taustart_ts = self.parse_taustartts()
self.teles... | d some of the header information. For now we will try both
# locations.
if 'spectral1' in keywords['coords']:
keyword = 'spectral1'
|
if 'spectral2' in keywords['coords']:
keyword = 'spectral2'
freq_eff = keywords['coords'][keyword]['restfreq']
freq_bw = keywords['coords'][keyword]['wcs']['cdelt']
return freq_eff, freq_bw
|
TheWardoctor/Wardoctors-repo | plugin.video.salts/scrapers/xmovies8_scraper.py | Python | apache-2.0 | 5,391 | 0.006678 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | import VIDEO_TYPES
from salts_lib.constants import XHR
import scraper
VIDEO_URL = '/video_info/iframe'
class Scraper(scraper.Scraper):
OPTIONS = ['h | ttps://xmovies8.org', 'https://putlockerhd.co', 'https://afdah.org', 'https://watch32hd.co']
def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
self.base_url = kodi.get_setting('%s-base_url' % (self.get_name()))
@classmethod
def provides(cls):
return fr... |
mikehulluk/morphforge | src/morphforgeexamples/exset2_singlecell_simulations/singlecell_simulation010.py | Python | bsd-2-clause | 3,237 | 0.006179 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | mple, we build a single section neuron, with passive channels,
and stimulate it with a step current clamp of 200pA for 100ms starting at t=100ms.
We also create a summary pdf of the simulation.
"""
from morphforge | .stdimports import *
from morphforgecontrib.stdimports import StdChlLeak
# Create the morphology for the cell:
morphDict1 = {'root': {'length': 20, 'diam': 20, 'id':'soma'} }
m1 = MorphologyTree.fromDictionary(morphDict1)
# Create the environment:
env = NEURONEnvironment()
# Create the simulation:
sim = env.Simulat... |
andensinlimite/metaespacio | metaespacio/espacios/templatetags/espacios.py | Python | agpl-3.0 | 441 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import Library
from ..models import Espacio
register = Library()
@register.inclusion_tag('espacios/_otros_espacios.html', takes_context=True)
def otros_espacios(context):
qs = Espacio.objects.all()
if 'e | spacio' in context:
obj = context['espacio']
if obj:
qs = qs.exclude(p | k=obj.pk)
return {'otros_espacios': qs}
|
vLBrian/boxeehack-cigamit | hack/boxee/scripts/OpenSubtitles/resources/lib/gui.py | Python | mit | 11,411 | 0.063897 | import sys
import os
import xbmc
import xbmcgui
import xbmcplugin
import threading
import socket
import urllib
from Queue import Queue
import plugins
import ConfigParser
import logging
import difflib
try: current_dlg_id = xbmcgui.getCurrentWindowDialogId()
except: current_dlg_id = 0
current_win_id = xbmcgui.getCurrent... | : 'Chechen',
'ch' : 'Chamorro',
'co' : 'Corsican',
'cr' : 'Cree',
'cs' : 'Czech',
'cu' : 'Old Church Slavonic',
'cv' : 'Chuvash',
'cy' : 'Welsh',
'da' : 'Danish',
'de' : 'German',
'dv' : 'Divehi',
'dz' : 'Dzongkha',
'ee' : 'Ewe',
'el' : 'Greek',
'en' : 'English',
'eo' : 'Esperanto',
'es' : 'Spanish' | ,
'et' : 'Estonian',
'eu' : 'Basque',
'fa' : 'Persian',
'ff' : 'Fula',
'fi' : 'Finnish',
'fj' : 'Fijian',
'fo' : 'Faroese',
'fr' : 'French',
'fy' : 'Western Frisian',
'ga' : 'Irish',
'gd' : 'Scottish Gaelic',
'gl' : 'Galician',
'gn' : 'Guaraní',
'gu' : 'Gujarati',
'gv' : 'Manx',
'ha' : 'Hausa',
'he' : 'Hebrew',
'hi' : ... |
libnano/libnano | libnano/fileio/gb_reader_b.py | Python | gpl-2.0 | 12,973 | 0.004702 | # -*- coding: utf-8 -*-
"""
http://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html
http://www.insdc.org/documents/feature_table.html
All keys are native strings, as are values, except the origin which is always
a python 3 byte string (not unicode)
"""
import re
import io
import sys
from collections import OrderedDict
... | on: List[str] = [ "^VERSION", # field
" +(?P<version>[\w|.]+)", # version
" +GI:(?P<GI>[\w|.]+)" # gi field
| ".*", # match line end
NEWLINE_STR
]
RE_VERSION: bytes = _bytes("".join(re_version))
RE_DBLINK: bytes = b"^DBLINK +(?P<dblink>[\w|:| |.]+)" + NEWLINE_BYT
re_keywords: List[str] = [
"^KEYWORDS",
" +(?P<keywords>[\w|.]*)"
".*",
NEWL... |
brianhouse/wavefarm | granu/braid/core.py | Python | gpl-3.0 | 2,215 | 0.005869 | #!/usr/bin/env python3
import time, threading, queue
from .util import osc, log
class Driver(object):
""" This is a substitute for a realtime system """
def __init__(self):
self.voices = []
self.grain = 0.01 # hundredths are nailed by Granu, w/o load. ms are ignored.
self.t = 0.... | = True
self.msp_sender = osc.Sender(5280)
self.queue = queue.Queue()
self.start()
def send(self, address, *params):
self.queue.put((address, params))
def run(self):
while True:
address, params = self.queue.get()
se | lf.msp_sender.send(address, params)
synth = Synth() # player singleton
driver = Driver()
|
Sbalbp/DIRAC | FrameworkSystem/Client/SiteMapClient.py | Python | gpl-3.0 | 1,184 | 0.033784 | """ Client-side transfer class for monitoring system
"""
import time
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC import S_OK
class SiteMapClient:
###########################################################################
def __init__( self, getRPCClient = None ):
self.getRPCClient = getRPCCl... | #####
def getSitesData( self ):
""" Retrieves a single file and puts it in the output directory
"""
if self.lastDataRetrievalTime - time.time() < 300:
result = self.__getRPCClient().getSitesData()
if 'rpcStub' in result:
del( result[ 'rpcStub' ] )
if not result[ 'OK' ]:
... | time.time()
return S_OK( self.sitesData )
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
|
wakatime/komodo-wakatime | components/wakatime/offlinequeue.py | Python | bsd-3-clause | 3,427 | 0.000875 | # -*- coding: utf-8 -*-
"""
wakatime.offlinequeue
~~~~~~~~~~~~~~~~~~~~~
Queue for saving heartbeats while offline.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from time import sleep
from .compat import json
from .constants import ... | if row is not None:
id = row[0]
heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True)
c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id])
conn.commit()
| loop = False
except sqlite3.Error:
log.traceback(logging.DEBUG)
sleep(wait)
tries -= 1
try:
conn.close()
except sqlite3.Error:
log.traceback(logging.DEBUG)
return heartbeat
def push_many(self, heartbeats... |
bobbyxuy/flask_web | app/auth/views.py | Python | mit | 1,344 | 0.001488 | from flask import render_template, redirect, request, url_for, flash
from . import auth
from ..models import User
from .forms import LoginForm, RegistrationForm
from flask_login import login_user, logout_user, login_required, current_user
from .. import db
from ..email import send_email
@auth.route('/login', methods=... | login_user(user, form.remember_me.data)
r | eturn redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password')
return render_template('auth/login.html', form=form)
@auth.route('/logout')
@login_required
def logout():
logout_user()
flash('you have been logged out.')
return redirect(url_for('main.index... |
StrasWeb/picomon | picomon/__init__.py | Python | gpl-3.0 | 2,005 | 0 | import socket
from .attrtree import AttrTree
from .checks import Checks
config = AttrTree()
# the list of checks
config.install_attr('checks', Checks())
# This is the base granularity (in seconds) for polling
# Each check may then individually be configured to run every N * tick
config.install_attr('base_tick', 60)... | .install_attr('emails.report.every', 0)
# Subject template for state change email notifications
# available substitutions:
# - state ("Pro | blem" or "OK")
# - check (check's name, like "CheckDNSRec6")
# - dest (the target of the check ie. an IP or a Host's 'name'
# parameter)
config.install_attr('emails.subject_tpl',
'[DOMAIN] {state}: {check} on {dest}')
# reports email subject
config.install_attr('emails.report.subject... |
dani882/edX---Computer-Science | python/lecture 3.2.py | Python | gpl-2.0 | 336 | 0.002976 | __author__ = 'dani882'
# lecture 3.2, slide | 6
# Find the cube root of a perfect cube
x = int(raw_input('Enter an integer: '))
ans = 0
while ans**3 < abs(x):
ans = ans + 1
if ans**3 != abs(x):
print(str(x) + ' is not a perfect cube')
else:
if x < 0:
ans = -ans
print('C | ube root of ' + str(x) + ' is ' + str(ans)) |
atmb4u/marlin | marlin/__init__.py | Python | bsd-3-clause | 13 | 0.076923 | im | port marlin | |
mullikine/ranger | ranger/container/settings.py | Python | gpl-3.0 | 8,531 | 0.001524 | # Copyright (C) 2009-2013 Roman Zimbelmann <[email protected]>
# This software is distributed under the terms of the GNU GPL version 3.
from inspect import isfunction
from ranger.ext.signals import SignalDispatcher, Signal
from ranger.core.shared import FileManagerAware
from ranger.gui.colorscheme import _colors... | :
# Bad regular expression
return
self._localregexes[path] = regex
self._localsettings[path] = dict()
self._localsettings[path][name] = value
# make sure name is in _settings, so __iter__ runs through
| # local settings too.
if not name in self._settings:
type_ = self.types_of(name)[0]
value = DEFAULT_VALUES[type_]
self._settings[name] = value
elif tags:
for tag in tags:
if tag not in self._tagsettings:
... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/librarianserver/tests/test_db_outage.py | Python | agpl-3.0 | 3,628 | 0 | # Copyright 2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Test behavior of the Librarian during a database outage.
Database outages happen by accident and during fastdowntime deployments."""
__metaclass__ = type
from cStringIO impor... | ode)
self.assertTrue(len(codes) == 1, 'Mixed responses: %s' % str(codes))
return codes.pop()
def test_outage(self):
# Everything should be working fine to start with.
self.assertEqual(self.getErrorCode(), 200)
# When the outage kicks in, we start getting 503 responses
... | Code(), 503)
# When the outage is over, things are back to normal.
self.pgbouncer.start()
self.assertEqual(self.getErrorCode(), 200)
|
geonetix/simplemq | simplequeue/__init__.py | Python | mit | 71 | 0 | from simplequeue.lib.configuration import config
__all__ = ['conf | ig']
| |
iw3hxn/LibrERP | sale_order_version/models/__init__.py | Python | agpl-3.0 | 1,120 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (C) 2014 Didotech srl (<http://www.didotech.com>).
#
# All Rights Reserved
#
# This program is free software: you can redistr... | r 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME... | ls.
#
# 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 . import sale_order
from . import sale_order_line
from . import sale_shop
from . ... |
akx/shoop | _misc/ensure_license_headers.py | Python | agpl-3.0 | 4,075 | 0.001227 | #!/usr/bin/env python3
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, 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.
"""
License header updater.
"""
from __future__ import unicode_literals
impo... | tually write changes", action="store_true")
ap.add_argument("-s", "--exit-status", help="Exit with error status when missing headers", action="store_true")
ap.add_argument("-v", "--verbose", help="Log OK files too", action="store_true")
args = ap.parse_args()
adders = get_adders()
paths = find_files... | , write=args.write)
if args.exit_status and missing:
return 1
return 0
def process_files(paths, adders, verbose, write):
width = max(len(s) for s in paths)
missing = set()
for path in sorted(paths):
if os.stat(path).st_size == 0:
if verbose:
print('[+]:%... |
applecool/Practice | Python/Sorting/RadixSort.py | Python | mit | 556 | 0.082734 | #implementation of radix sort in Python.
def RadixSort(A):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
buckets = [list() for _ in range(RADIX)]
for i in A:
tmp = i / placement
buckets[tmp % RADIX].append(i)
if maxLength and tmp > 0:
maxL... | X):
buck = buckets[b]
for i i | n buck:
A[a] = i
a += 1
# move to next digit
placement *= RADIX
A = [534, 246, 933, 127, 277, 321, 454, 565, 220]
print(RadixSort(A))
|
msultan/mdtraj | mdtraj/nmr/scalar_couplings.py | Python | lgpl-2.1 | 8,005 | 0.001376 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2014 Stanford University and the Authors
#
# Authors: Kyle A. Beauch... | ents. USES RADIANS!"""
return A * np.cos(phi + phi0) ** 2. + B * np.cos(phi + phi0) + C
def compute_J3_HN_HA(traj, model="Bax2007"):
"""Calculate the scalar coupling between HN and H_alpha.
This function does not take into account periodic boundary conditions (it
will give spurious results if the th... | A for
model : string, optional, default="Bax2007"
Which scalar coupling model to use. Must be one of Bax2007, Bax1999,
or Ruterjans1999
Returns
-------
indices : np.ndarray, shape=(n_phi, 4), dtype=int
Atom indices (zero-based) of the phi dihedrals
J : np.ndarray, shape=(n_... |
HalCanary/skia-hc | tools/skp/page_sets/skia_cnn_desktop.py | Python | bsd-3-clause | 1,145 | 0.00524 | # Copyright 2019 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.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | esktop.json')
urls_list = [
# go/skia-skps-3-2019
'http://www.cnn.com',
]
for url in urls_list:
self.AddStory(SkiaDesktopPage(url, | self)) |
nghiattran/generator-python-parse | generators/endpoint/templates/model_template.py | Python | mit | 201 | 0.014925 | # | @name <%= app_name %>
# @description
# Models for UserControler.
import json
from src.models import BaseModel
class <%= endpoint %>Model(BaseModel):
_parse_class_n | ame = '<%= table %>'
pass |
KnockSoftware/whitenoise | whitenoise/__init__.py | Python | mit | 118 | 0 | from __future__ import absolute_import
from .base import WhiteNoise
__ve | rsion__ = '2.0.3'
__all | __ = ['WhiteNoise']
|
myersjustinc/django-calaccess-campaign-browser | calaccess_campaign_browser/api.py | Python | mit | 545 | 0 | from tastypie.resources import ModelResource, ALL
from .models impor | t Filer, Filing
from .utils.serializer import CIRCustomSerializer
class FilerResource(ModelResource):
class Meta:
queryset = Filer.objects.all()
serializer = CIRCustomSerializer()
filtering = {'filer_id_raw': ALL}
excludes = ['id']
class FilingResource(ModelResource):
class M... | queryset = Filing.objects.all()
serializer = CIRCustomSerializer()
filtering = {'filing_id_raw': ALL}
excludes = ['id']
|
jamesiter/jimauth | views/user_mgmt.py | Python | gpl-3.0 | 14,179 | 0.001987 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from flask import Blueprint, request
import jimit as ji
from models import UidOpenidMapping
from models import Utils, Rules, User
__author__ = 'James Iter'
__date__ = '16/6/8'
__contact__ = '[email protected]'
__copyright__ = '(c) 2016 by James Iter.'... | r.id)
if user.id == 1:
ret = dict()
ret['state'] = ji.Common.exchange_state(40301)
raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
user.delete | ()
# 删除依赖于该用户的openid
UidOpenidMapping.delete_by_filter('uid:in:' + _id)
except ji.PreviewingError, e:
return json.loads(e.message)
@Utils.dumps2response
@Utils.superuser
def r_update(_id):
user = User()
args_rules = [
Rules.UID.value
]
if 'login_name' in request.... |
rafaelribeiroo/ensinoDistancia | src/apps/courses/migrations/0002_auto_20171103_0057.py | Python | gpl-3.0 | 685 | 0.00292 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-03 00:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0001_initial'),
]
operations = [
migrations.AlterField(
... | ='name',
| field=models.CharField(max_length=100, unique=True, verbose_name='Nome'),
),
]
|
nafitzgerald/allennlp | setup.py | Python | apache-2.0 | 3,457 | 0.002025 | """
In order to create a package for pypi, you need to follow several steps.
1. Create a .pypirc in your home directory. It should look like this:
```
[distutils]
index-servers =
pypi
pypitest
[pypi]
username=allennlp
password= Get the password from LastPass.
[pypitest]
repository=https://test.pypi.org/legacy/
... | 'numpy',
'tensorboard',
'cffi==1.11.2',
'awscli>=1.11.91',
'flask==0.12.1',
'flask-cors==3.0.3',
'psycopg2',
'argparse',
'requests>=2.18',
'tqdm',
'editdistance',
'jupyter',
'h5py',
'... | learn',
'scipy',
'pytz==2017.3'
],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
include_package_data=True,
python_requires='>=3.6',
zip_safe=False)
|
fccagou/tools | python/sql/csv-to-sql.py | Python | gpl-2.0 | 537 | 0.013035 | import csv, sqlite3
con = sqlite3.connect("toto.db") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2) | ;") # use your column names here
with open('data.csv','r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['col1'], i['col2']) for i in dr]
cur.executemany("INSERT INTO t ... | ", to_db)
con.commit()
con.close()
|
itaiin/arrow | python/pyarrow/types.py | Python | apache-2.0 | 6,569 | 0 | # 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... | ""
Return True if value is an instance of a time32 type
"""
return t.id == lib.Type_TIME32
def is_time64(t):
"""
Return True if value is an instance of a time64 type
"""
return t.id == lib.Type_TIME64
def is_binary(t):
"""
Return True if value is an instance of a variable-length ... | ng
"""
return is_string(t)
def is_string(t):
"""
Return True if value is an instance of string (utf8 unicode) type
"""
return t.id == lib.Type_STRING
def is_fixed_size_binary(t):
"""
Return True if value is an instance of a fixed size binary type
"""
return t.id == lib.Type_F... |
jawilson/home-assistant | homeassistant/components/energy/__init__.py | Python | apache-2.0 | 1,029 | 0.000972 | """The Energy integration."""
from __future__ import annotations
from homeassistant.components import frontend
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery
from homeassistant.helpers.typing import ConfigType
from . import websocket_api
from .const import DOMAIN
from .data i... | et_manager(hass)
if manager.data is None:
return False
return bool(manager.data != manager.default_preferences())
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Energy."""
websocket_api.async_setup(ha | ss)
frontend.async_register_built_in_panel(hass, DOMAIN, DOMAIN, "mdi:lightning-bolt")
hass.async_create_task(
discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config)
)
hass.data[DOMAIN] = {
"cost_sensors": {},
}
return True
|
houssemFat/MeeM-Dev | teacher/apps/dashboard/views.py | Python | mit | 3,848 | 0.013514 | from django.forms.models import model_to_dict
from django.db.models import Count
from django.core.paginator import Paginator
import json
from core.apps.tools.common import render_json, dump_and_render_json,\
MeeMJSONEncoder
from core.apps.accounts.models import User
from core.apps.history.models import UserLogEnt... | model.update({'todos' : todos})
return render_json(requ | est, json.dumps(model, encoding="utf-8", cls=MeeMJSONEncoder))
else :
return dump_and_render_json(request, None)
def get_profile_progress(user) :
# privacy
# lang
# web sites
# emails
# location
return 15
|
0xkasun/zaproxy | python/api/src/zapv2/core.py | Python | apache-2.0 | 14,644 | 0.010311 | # Zed Attack Proxy (ZAP) and its related class files.
#
# ZAP is an HTTP/HTTPS proxy for assessing web application security.
#
# Copyright 2015 the ZAP development team
#
# 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... | ues())
def number_of_messages(self, baseurl=''):
"""
Gets the | number of messages, optionally filtering by URL
"""
return next(self.zap._request(self.zap.base + 'core/view/numberOfMessages/', {'baseurl' : baseurl}).itervalues())
@property
def version(self):
"""
Gets ZAP version
"""
return next(self.zap._request(self.zap.bas... |
Pertino/pertino-sdk-python | pertinosdk/tests/pertinosdk_test.py | Python | mit | 3,217 | 0.009636 | '''
Created on Jul 26, 2014
@author: lwoydziak
'''
from mockito.mocking import mock
from pertinosdk import PertinoSdk, QueryBuilder, where
from mockito.mockito import when, verify
from mockito.matchers import any, Matcher
class Contains(Matcher):
def __init__(self, sub):
self.sub = sub
def ma... | closure = mock()
pertinoSdk.listDevicesIn({"id":1}, closure.function)
verify(closure).function(json["devices"][0])
def test_CanDeleteMachine():
pertinoSdk, requests, response = setupSdk()
when(requests).delete(any(), auth=any()).thenReturn(response)
devices = [{"ipv4Address": "123.456.789.10", "ho... | ({"id":1}, devices)
verify(requests, times=1).delete('http://api.labs.pertino.com:5000/api/v0-alpha/orgs/1/devices/1234?user_key=993e79924d5b6346fe62a5cf62183bc5', auth=any())
def test_CanBuildClosureToFilterApiResponses():
isQueryBuilder = any(QueryBuilder)
assert isQueryBuilder.matches(where("any"))
... |
yephper/django | tests/template_tests/syntax_tests/test_exceptions.py | Python | bsd-3-clause | 2,158 | 0.00139 | from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import Si | mpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
|
@setup({'exception01': "{% extends 'nonexistent' %}"})
def test_exception01(self):
"""
Raise exception for invalid template name
"""
with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception01')
@setup({'exception02': '{% ex... |
jaredhoberock/gotham | api/api.py | Python | apache-2.0 | 16,127 | 0.01637 | #!/usr/env/bin python
# TODO
# 1. fix bug that if a script shares the same name as a material dll to load,
# the material may not be loaded correctly
# 2. fix multiple definitions of c++ -> python conversion for Spectrum
import sys
import os
import math
from libgotham import *
import inspect
def normalize(x):
... | modul | e.name(copyFrom)
exec "result = module." + name + "(copyFrom)"
del module
except:
pass
# stop at the first thing we were able to create
if result != None:
break;
return result
def pushMatrix(self):
return self.__subsystem.pushMatrix()
def popMatrix(self)... |
atztogo/phonondb | phonondb/phonopy/band.py | Python | bsd-3-clause | 7,188 | 0.001113 | import numpy as np
import seekpath
class Band:
def __init__(self,
phonon,
num_qpoints=101):
| self._phonon = phonon # Phonopy object
self._num_qpoints = num_qpoints
self._band = []
self._labels = None
self._connected = None
def run(self):
unitcell = self._phonon.unitcell
cell = (unitcell.get_cell(),
unitcell.get_scaled_positions(),
... | unitcell.get_atomic_numbers())
band_path = seekpath.get_path(cell)
self._set_band(band_path)
self._set_labels(band_path)
return self._run_band()
def get_band(self):
return self._phonon.get_band_structure()
def plot_band(self, plt, delta_d=0.02):
fig, ax... |
lociii/jukebox_mpg123 | jukebox_mpg123/management/commands/jukebox_mpg123.py | Python | mit | 3,441 | 0.001453 | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
daemon = None
pr... | self.proc = subprocess.Popen(
[self.mpg123, song_instance.Filename]
| )
else:
if not self.proc.poll() is None:
self.proc = None
time.sleep(0.5)
def shutdown(self, signal, action):
if not self.proc is None:
os.kill(self.proc.pid, SIGTERM)
if not self.daemon is None:
self.da... |
ohtaman/pynm | pynm/reinforce/bandit/thompson.py | Python | mit | 683 | 0.001464 | # -*- coding:utf-8 -*-
from collections import defaultdict
import numpy
class ThompsonAg | ent:
def __init__(self, seed=None):
self._succeeds = defaultdict(int)
self._fails = defaultdict(int)
self._np_random = numpy.random.RandomState(seed)
def choose(self, arms, features=None):
return max(arms, key=lambda arm: self._score(arm))
def _score(self, arm):
ret... | lf, arm, reward, arms=None, features=None):
if reward > 0:
self._succeeds[arm] += 1
else:
self._fails[arms] += 1
|
kklmn/xrt | xrt/backends/raycing/physconsts.py | Python | mit | 1,189 | 0.003364 | # -*- coding: utf-8 -*-
__author__ = "Konstantin Klementi | ev", "Roman Chernikov"
__date__ = "07 Jan 2016"
PI = 3.1415926535897932384626433832795
PI2 = 6.283185307179586476925286766559
SQRT2PI = PI2**0.5 # =2.5066282746310002
SQ3 = 1.7320508075688772935274463415059
SQ2 = 2**0.5 # =1.4142135623730951
SQPI = PI**0.5 # =1.7724538509055159
SIE0 = 1.602176565e-19
#E0 = 4.803e-... | 528e-28 # [g]
SIM0 = 9.109383701528e-31
M0C2 = 0.510998928 # MeV
HPLANCK = 6.626069573e-27 # [erg*sec]
EV2ERG = 1.602176565e-12 # Energy conversion from [eV] to [erg]
K2B = 2 * PI * M0 * C**2 * 0.001 / E0 # =10.710201593926415
# EMC = SIE0 / SIM0 / C[mm]
EMC = 0.5866791802416487
SIHPLANCK = 6.626069573e-34
#SIM0... |
ankanaan/chimera | src/chimera/gui/modules/camera.py | Python | gpl-2.0 | 11,323 | 0 | from chimera.core.callback import callback
from chimera.core.exceptions import printException
from chimera.gui.modules.canvas import FITS, FITSCanvas
from chimera.gui.module import ChimeraGUIModule
from chimera.interfaces.camera import CameraStatus
from chimera.util.image import Image
import gtk
import glib
import g... | heel = wheel
def getWheel(self):
# transfer to current thread and return (a hacky way to reuse Proxies)
self.wheel._transferThread()
return self.wh | eel
def expose(self):
camera = self.getCamera()
durationSpin = self.module.builder.get_object("durationSpin")
duration = durationSpin.get_value()
framesSpin = self.module.builder.get_object("framesSpin")
frames = framesSpin.get_value()
shutterOpen = self.module.b... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/topology_resource_py3.py | Python | mit | 1,570 | 0.005096 | # 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 ... | ociation]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'associations': {'key': 'associations', 'type': '[TopologyAssociation]'},
}
def _ | _init__(self, *, name: str=None, id: str=None, location: str=None, associations=None, **kwargs) -> None:
super(TopologyResource, self).__init__(**kwargs)
self.name = name
self.id = id
self.location = location
self.associations = associations
|
ngokevin/zamboni | apps/amo/tests/test_log.py | Python | bsd-3-clause | 976 | 0 | """Tests for the activitylog."""
from datetime import datetime
from nose.tools import eq_
import amo
import amo.tests
from mkt.webapps.models import Webapp
from mkt.users.models import UserProfile
class LogTest(amo.tests.TestCase):
def setUp(self | ):
u = UserProfile.objects.create(username='foo')
amo.set_user(u)
def test_details(self):
"""
If we get details, verify they are stored as JSON, and we get out what
we put in.
"""
a = Webapp.objects.create(name='kumar is awesome')
magic = dict(title= | 'no', body='way!')
al = amo.log(amo.LOG.DELETE_REVIEW, 1, a, details=magic)
eq_(al.details, magic)
eq_(al._details, '{"body": "way!", "title": "no"}')
def test_created(self):
"""
Verify that we preserve the create date.
"""
al = amo.log(amo.LOG.CUSTOM_TEXT, ... |
Droriel/python_training_mantis | fixture/mail.py | Python | apache-2.0 | 858 | 0.004662 | import poplib
import email
import time
class MailHelper:
def __init__(self, app | ):
self.app = app
def get_mail(self, username, password, s | ubject):
for i in range (5):
pop = poplib.POP3(self.app.config['james']['host'])
pop.user(username)
pop.pass_(password)
num = pop.stat()[0]
if num>0:
for n in range(num):
msglines = pop.retr(n+1)[1]
... |
openstack/neutron-classifier | neutron_classifier/tests/unit/cli/__test_db_classifications.py | Python | apache-2.0 | 2,667 | 0 | # Can't be run at the moment until migration with openstack-client
# Copyright (c) 2018 Intel Corporation.
#
# 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.ap... | rom neutronclient.v2_0 import client
OPENSTACK_CLI_ID = "/ccf/classifications"
ASSOCS_PATH = "/ccf/classifications"
NET_ASSOC_ID = "uuid_client_foo"
class OpenstackClientTestCase(test_extensions_base.ExtensionTestCase):
def setUp(self):
super(OpenstackClientTestCase, self).setUp()
self.client = ... | xt = mock.Mock()
self.client.show_ext = mock.Mock()
self.client.update_ext = mock.Mock()
self.client.delete_ext = mock.Mock()
print("self.client keys: ", dir(self.client))
def test_client_url_list(self):
self.client.ListIPV4Classification(OPENSTACK_CLI_ID)
self.clien... |
hzlf/openbroadcast | website/legacy/obp_legacy/models_legacy.py | Python | gpl-3.0 | 31,942 | 0.005134 | # This is an auto-generated Django model module.
# You'll have to do the follow | ing manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database... | Model):
ident = models.IntegerField(primary_key=True)
owner = models.IntegerField()
calendar = models.IntegerField()
title = models.CharField(max_length=765, blank=True)
description = models.TextField()
access = models.CharField(max_length=765, blank=True)
location = models.CharField(max_len... |
tomachalek/kontext | lib/plugins/default_token_connect/backends/treq.py | Python | gpl-2.0 | 6,004 | 0.002165 | # Copyright (c) 2018 Charles University, Faculty of Arts,
# Institute of the Czech National Corpus
# Copyright (c) 2018 Tomas Machalek <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as publis... | imary lang | uage (= corpora[0]).
"""
primary_lang = self._lang_from_corpname(corpora[0])
translations = self.AVAIL_LANG_MAPPINGS.get(primary_lang, [])
for cn in corpora[1:]:
lang = self._lang_from_corpname(cn)
if lang in translations:
return cn, lang
r... |
wonder041/MegaPipeline | Standardize.py | Python | mit | 264 | 0.015152 | import sys
from Bio import SeqIO
input_file = sys.argv[1]
output_file = sys | .argv[2]
def Ungap(seq):
seq.seq=seq.seq.ungap('-')
return seq
output_gen = (Ungap(seq) for seq in SeqIO.parse(input_file, 'fasta'))
SeqIO.write(output_gen,ou | tput_file, 'fasta')
|
fachschaft-medizin-rostock/django-fsmedhro | exoral/migrations/0005_merge_20170331_1617.py | Python | mit | 337 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-31 14:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('exoral', '0004_merge_20170327_0002'),
('exoral', '0003_auto_20170322_1453'),
]
oper... | ions = [
]
| |
palfrey/kitling | frontend/videos/migrations/0015_add_channel.py | Python | agpl-3.0 | 907 | 0.005513 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
('videos', '0014_add_enabled_and_notes'),
]
operations = [
migrations.Create... | elds=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('url', models.URLField(unique=True)),
('enabled', models.BooleanField(default=True)),
('working', models.BooleanField(default=False)),
... | ,1)))),
('notes', models.CharField(max_length=1024, null=True, blank=True)),
],
),
]
|
INCF/lib9ML | test/serialization_profile.py | Python | bsd-3-clause | 1,617 | 0.001237 | from __future__ import print_function
import shutil
import os.path
import tempfile
import cProfile
import pstats
import nineml
from nineml.utils.comprehensive_example import (
instances_of_all_types, v1_safe_docs)
from nineml.serialization import ext_to_format, format_to_serializer
format_to_ext = dict((v, k) for... | e()
url = os.path.join(
_tmp_dir, 'test{}v{}{}'.format(i, version, ext))
nineml.write(url, doc, format=format, version=version,
indent=2)
if print_serialized and format in printable:
with open(url) as f:... | hutil.rmtree(_tmp_dir)
out_file = os.path.join(os.getcwd(), 'serial_profile.out')
cProfile.run('function()', out_file)
p = pstats.Stats(out_file)
p.sort_stats('cumtime').print_stats()
|
Guts/isogeo2sig | StandAlone/modules/proxy_checker.py | Python | gpl-3.0 | 2,322 | 0.004737 | # -*- coding: UTF-8 -*-
#!/usr/bin/env python
from __future__ import unicode_literals
# ------------------------------------------------------------------------------
# Name: Proxy checker
# Purpose: Just a couple of functions to check various proxy configuration
#
# Author: Julien Moura (@geojulien)... | #################
############ Functions ############
###################################
# execfile("parameters.py")
def is_bad_proxy(pip):
"""
TO COMMENT
"""
try:
proxy_handler = urllib2.ProxyHandler({'http': pip})
opener = urllib2.build_opener(proxy_handler)
opener.addheader... | ', 'Mozilla/5.0')]
urllib2.install_opener(opener)
req=urllib2.Request('http://www.example.com') # change the URL to test here
sock=urllib2.urlopen(req)
except urllib2.HTTPError, e:
print 'Error code: ', e.code
return e.code
except Exception, detail:
print "ERROR:... |
IllegalCactus/argument-workbench | querytool/search/migrations/0004_searchquery_scope.py | Python | gpl-3.0 | 437 | 0 | # -*- coding: utf-8 -*-
f | rom __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('search', '0003_auto_20150321_1848'),
]
operations = [
migrations.AddField(
model_name='searchquery',
name='scope',
... | ]
|
dseredyn/velma_planners | scripts/tf_pub.py | Python | gpl-2.0 | 2,492 | 0.008026 | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | n the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Warsaw University of Technology nor the
# names of its contributors may | be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FI... |
lubokkanev/cloud-system | console/main/command_handler/commands/simple_command.py | Python | gpl-2.0 | 107 | 0 | from console.main.command_handler.commands.command import Command
class SimpleComm | and(Command | ):
pass
|
howiworkdaily/scofield-project | scofield/category/admin.py | Python | bsd-3-clause | 898 | 0.010022 | from models import *
from forms import CategoryImageForm
from django.contrib import admin
class CategoryImageInline(admin.TabularInline):
model = CategoryImage
form | = CategoryImageForm
class CategoryOptions(admin.ModelAdmin):
prepopulated_ | fields = {'slug': ('name',)}
list_display = ['name', 'slug', 'parent', 'sortorder', 'published']
inlines = [
CategoryImageInline,
]
fieldsets = (
(None, {
'fields': ('name', 'slug', 'parent', 'sortorder', 'published',)
}),
('Meta options', {
'... |
yaybu/touchdown | touchdown/config/integer.py | Python | apache-2.0 | 1,092 | 0 | # Copyright 2016 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the " | License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT W... | License for the specific language governing permissions and
# limitations under the License.
from touchdown.core import argument
from . import variable
class Integer(variable.Variable):
resource_name = "integer"
default = argument.Integer()
min = argument.Integer()
max = argument.Integer()
clas... |
airtimemedia/satyr | tests/python/gdb.py | Python | gpl-2.0 | 5,764 | 0.00399 | #!/usr/bin/env python
import unittest
from test_helpers import *
contents = load_input_contents('../gdb_stacktraces/rhbz-803600')
threads_expected = 2
frames_expected = 227
expected_short_text = '''Thread no. 1 (5 frames)
#0 validate_row at gtktreeview.c:5699
#1 validate_visible_area at gtktreeview.c:5898
#2 gtk_t... | ree_view_expose at gtktreeview.c:4955
#4 _gtk_marshal_BOOLEAN__BOXED at gtkmarshalers.c:84
'''
expected_short_text_955617 = '''Thread no. 1 (3 frames)
#10 xf86CursorSetCursor at xf86Cursor.c:333
#11 xf86CursorEnableDisableFBAccess at xf86Cursor.c:233
#12 ??
'''
class TestGdbStacktrace(BindingsTestCase):
def s... | correct_thread_count(self):
self.assertEqual(len(self.trace.threads), threads_expected)
def test_correct_frame_count(self):
self.assertEqual(frame_count(self.trace), frames_expected)
def test_dup(self):
dup = self.trace.dup()
self.assertNotEqual(id(dup.threads), id(self.trace.t... |
akvo/akvo-rsr | akvo/rsr/migrations/0079_auto_20160620_1418.py | Python | agpl-3.0 | 1,137 | 0.004398 | # -*- coding: utf-8 -*-
from django.db import models, migrations
def sector_validation(apps, schema_editor):
""" Remove sector from RSR validation set """
ProjectEditorValidation = apps.get_model('rsr', 'ProjectEditorVa | lidation')
sector_validators = ['rsr_sector', 'rsr_sector.se | ctor_code', 'rsr_sector.vocabulary']
for v in sector_validators:
validation = ProjectEditorValidation.objects.filter(validation_set_id=1, validation__exact=v)
if validation:
validation.delete()
def undo_sector_validation(apps, schema_editor):
""" Remove sector from RSR validation s... |
alisaifee/limits | tests/storage/test_memcached.py | Python | mit | 3,218 | 0.000622 | import time
import pymemcache.client
import pytest
from limits import RateLimitItemPerMinute, RateLimitItemPerSecond
from limits.storage import MemcachedStorage, storage_from_string
from limits.strategies import (
FixedWindowElasticExpiryRateLimiter,
FixedWindowRateLimiter,
)
from tests.utils import fixed_sta... | assert limiter.test(per_sec)
def test_clear(self):
storage = MemcachedStorage("memcached://localhost:22122")
limiter = FixedWi | ndowRateLimiter(storage)
per_min = RateLimitItemPerMinute(1)
limiter.hit(per_min)
assert not limiter.hit(per_min)
limiter.clear(per_min)
assert limiter.hit(per_min)
|
birsoyo/conan | conans/test/generators/custom_generator_test.py | Python | mit | 3,848 | 0.001819 | import unittest
from conans.test.utils.tools import TestServer, TestClient
from conans.model.ref import ConanFileReference
import os
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.paths import CONANFILE, CONANFILE_TXT
from conans.util.files import load
generator = """
from conans.model... | elf.servers, users={"default": [("lasote", "mypass")]})
files = {CONANFILE: generator_multi}
client.save(files)
client.run("export . lasote/stable")
client.run("upload %s" % str(gen_reference))
# Test local, no retrieval
files = {CONANFILE_TXT: consumer_multi}
cl... | files, clean_first=True)
client.run("install . --build")
self.assertIn("Generator MyCustomMultiGenerator is multifile. "
"Property 'filename' not used",
client.user_io.out)
for i in (1, 2):
generated = load(os.path.join(client.current_folde... |
openstack/dragonflow | dragonflow/tests/unit/test_chassis_snat_app.py | Python | apache-2.0 | 3,471 | 0 | # Copyright (c) 2017 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... | ler(ev)
self.SNAT_app.add_flow_go_to_table.assert_has_calls(
[mock.call(
constants.L3_LOOKUP_TABLE,
| constants.PRIORITY_LOW,
constants.EGRESS_NAT_TABLE,
match=mock.ANY)])
self.SNAT_app.mod_flow.assert_has_calls(
[mock.call(
inst=mock.ANY,
table_id=constants.INGRESS_CLASSIFICATION_DISPATCH_TABLE... |
dichen001/Go4Jobs | JackChen/hash/299. Bulls and Cows.py | Python | gpl-3.0 | 1,587 | 0.003781 | """
You are playing the fol | lowing Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits matc... | cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Secret number: "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
Write a function to return a hint according to the secret number and friend's guess, use A to ... |
elcr/muhblog | muhblog/utils.py | Python | mit | 3,071 | 0 | import re
import math as maths
from typing import Iterable, Dict
from base64 import b64encode
from flask import Response, render_template, make_response, current_app
from peewee import SelectQuery
from htmlmin.minify import html_minify
from .models import Entry
PAGE_GROUP_SIZE = 5
ENTRIES_PER_PAGE = 10
class Pagin... | page = 1
end_page = total_pages
else:
if start_page < 1:
difference = 1 - start_page
start_page += difference
end_page += difference
i | f end_page > total_pages:
difference = end_page - total_pages
end_page -= difference
start_page -= difference
if start_page < 1:
start_page = 1
return range(start_page, end_page + 1)
_template_cache: Dict[str, str] = {}
def... |
redreamality/thefuck | thefuck/logs.py | Python | mit | 3,065 | 0.000327 | # -*- encoding: utf-8 -*-
from contextlib import contextmanager
from datetime import datetime
import sys
from traceback import format_exception
import colorama
from .conf import settings
def color(color_):
"""Utility for ability to disabling colored output."""
if settings.no_colors:
return ''
els... | et=color(colorama.Style.RESET_ALL),
title=title,
trace=''.join(format_exception(*exc_info))))
def rule_failed(rule, exc_info):
exception('Rule {}'.format(rule.name), exc_info)
def failed(msg):
sys.stderr.write('{red}{msg}{reset}\n'.format(
msg=msg,
red=color(colorama.... |
reset=color(colorama.Style.RESET_ALL)))
def show_corrected_command(corrected_command):
sys.stderr.write('{bold}{script}{reset}{side_effect}\n'.format(
script=corrected_command.script,
side_effect=' (+side effect)' if corrected_command.side_effect else '',
bold=color(colorama.Style... |
cdawei/digbeta | dchen/music/src/PLA_pop.py | Python | gpl-3.0 | 3,102 | 0.000322 | import os
import sys
import gzip
import time
import numpy as np
import pickle as pkl
from scipy.sparse import hstack
from sklearn.metrics import roc | _auc_score
from models import MTC
if len(sys.argv) != 7:
print('Usage: python', sys. | argv[0],
'WORK_DIR DATASET C P N_SEED TRAIN_DEV(Y/N)')
sys.exit(0)
else:
work_dir = sys.argv[1]
dataset = sys.argv[2]
C = float(sys.argv[3])
p = float(sys.argv[4])
n_seed = int(sys.argv[5])
trndev = sys.argv[6]
assert trndev in ['Y', 'N']
data_dir = os.path.join(work_dir, 'd... |
rbarrois/aionotify | setup.py | Python | bsd-2-clause | 1,579 | 0 | #!/usr/bin/env python
# Copyright (c) 2016 The aionotify project
# This code is distributed under the two-clause BSD License.
import codecs
import os
import re
import sys
from setuptools import setup
root_dir = os.path.abspath(os.path.dirname(__file__))
def get_version(package_name):
version_re = re.compile(r"... | description="Asyncio-powered inotify library",
author="Raphaël Barrois",
author_email="raphael.barrois+%[email protected]" % PACKAGE,
url='https://github.com/rbarrois/%s' % PACKAGE,
keywords=['asyncio', 'inotify'],
packages=[PACKAGE],
license='BSD',
setup_requires=[
],
tests_req... | t Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development :: Libraries :: Pytho... |
allenlavoie/tensorflow | tensorflow/contrib/quantize/python/quantize_graph_test.py | Python | apache-2.0 | 11,911 | 0.009151 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | quant_delay_found = True
const_value = str(op.get_attr('value'))
self. | assertTrue(('int64_val: %i' % quant_delay) in const_value)
self.assertTrue(quant_delay_found)
def testWeightBits(self):
self._RunTestOverExperimentalRewrites(self._TestWeightBits)
def _TestWeightBits(self, rewrite_fn):
with ops.Graph().as_default() as g:
self._ConvLayer()
weight_bits = 4
... |
justacec/bokeh | examples/app/selection_histogram.py | Python | bsd-3-clause | 3,598 | 0.005281 | ''' Present a scatter plot with linked histograms on both axes.
Use the ``bokeh serve`` command to run the example by executing:
bokeh serve selection_histogram.py
at your command prompt. Then navigate to the URL
http://localhost:5006/selection_histogram
in your browser.
'''
import numpy as np
from boke... | top=vedges[1:], right=vzeros, alpha=0.1, **LINE_ARGS)
pv.min_border_top = 80
pv.min_border_left = 0
ph.min_border_top = 10
| ph.min_border_right = 10
p.min_border_right = 10
layout = vplot(hplot(p, pv), hplot(ph, Paragraph(width=200)), width=800, height=800)
curdoc().add_root(layout)
def update(attr, old, new):
inds = np.array(new['1d']['indices'])
if len(inds) == 0 or len(inds) == len(x):
hhist1, hhist2 = hzeros, hzeros
... |
swamireddy/python-cinderclient | cinderclient/tests/v2/test_volume_backups.py | Python | apache-2.0 | 2,562 | 0 | # Copyright (C) 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/LICEN... | b62')
cs.assert_called('DELETE',
'/backups/76a17945-3c6f-435c-975b-b5685db10b62')
cs.backups.delete(b)
cs.assert_called('DELETE',
'/backups/76a17945-3c6f-435c-975b-b5685db10b62')
def test_restore(self):
backup_id = '76a17945-3c6f-435... | a17945-3c6f-435c-975b-b5685db10b62'
cs.backups.export_record(backup_id)
cs.assert_called('GET',
'/backups/%s/export_record' % backup_id)
def test_record_import(self):
backup_service = 'fake-backup-service'
backup_url = 'fake-backup-url'
expected_body... |
rwl/openpowersystem | cpsm/topology/connectivity_node.py | Python | agpl-3.0 | 2,078 | 0.006256 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# 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; version 2 dated June... | e.attributes
# <<< connectivity_node.references
# @generated
# Virtual property. Terminals interconnect with zero impedance at a node. Measurements on a node apply to all of its terminals.
pass # terminals
# Container of this connectivity | node.
member_of_equipment_container = db.ReferenceProperty(ConnectivityNodeContainer,
collection_name="connectivity_nodes")
# >>> connectivity_node.references
# <<< connectivity_node.operations
# @generated
# >>> connectivity_node.operations
# EOF ----------------------------------------... |
suutari-ai/shoop | shuup/admin/module_registry.py | Python | agpl-3.0 | 1,750 | 0.000571 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import six
from shuup.apps.provides import get... | ib.contextmanager
def replace_modules(new_module_classes):
"""
Context manager to temporarily replace all modules with something else.
Test | utility, mostly.
>>> def some_test():
... with replace_modules(["foo.bar:QuuxModule"]):
... pass # do stuff
:param new_module_classes: Iterable of module classes, like you'd pass to `register`
"""
old_registry = _registry[:]
_registry[:] = []
for cls in new_module_classes:... |
chromium2014/src | chrome/common/extensions/docs/server2/document_renderer_test.py | Python | bsd-3-clause | 6,119 | 0.002125 | #!/usr/bin/env python
# Copyright 2013 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 document_renderer import DocumentRenderer
from server_instance import ServerInstance
from test_file_system import... | rtEqual(['Found unexpected title "title"'], warnings)
text, warnings = self._renderer.Render(document, path, render_title=True)
self.assertEqual('<h1>title</h1> title and <table-of-contents>', text)
self.assertEqual([], warnings)
def testRefInTitl | e(self):
document = '<h1>$(ref:baz.baz_e1 title)</h1> A $(title) was here'
expected_document_no_title = ('<h1><a href=#type-baz_e1>'
'title</a></h1> A $(title) was here')
expected_document = ('<h1><a href=#type-baz_e1>title</a></h1>'
' A title was ... |
rh-marketingops/dwm | setup.py | Python | gpl-3.0 | 1,421 | 0.001407 | """
dwm package setup
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '1.1.0'
def readme():
""" open readme for long_description """
try:
with open('README.md') as fle:
return fle.read()
except IOError:
return ''
setup(... | age_data=True,
platforms='any',
test_suite='nose.collector',
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Natural Language :: English',
'Environment :: Web Environment',
'Intended Audi | ence :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Libraries :: Application Frameworks'
],
keywords='marketing autom... |
jsubpy/jsub | jsub/operation/submit.py | Python | mit | 4,925 | 0.031675 | import os
import logging
from jsub.util import safe_mkdir
from jsub.util import safe_rmdir
class Submit(object):
def __init__(self, manager, task_id, sub_ids=None, dry_run=False, resubmit=False):
self.__manager = manager
self.__task = self.__manager.load_task(task_id)
self.__sub_ids = sub_ids
self.__dry_run ... | ootstrap_dir)
bootstrap = self.__config_mgr.bootstrap()
self.__bootstrap_mgr.create_bootstrap(bootstrap, bootstrap_dir)
def __create_launcher(self, run_root):
lau | ncher = self.__task.data['backend']['launcher']
return self.__launcher_mgr.create_launcher(launcher, run_root)
def __submit(self, launcher_param):
if self.__dry_run:
return
if self.__resubmit==False:
if self.__task.data.get('backend_job_ids') or self.__task.data.get('backend_task_id'):
self.__logger... |
rogerthat-platform/rogerthat-backend | src/rogerthat/bizz/profile.py | Python | apache-2.0 | 48,219 | 0.003152 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... | m = get_friends_map(app_user)
return user_profile, fm
user_profile, fm = db.run_in_transaction(trans)
app_user_email = app_user.email()
# delete old indexed app user if the doc_id is app_user_email (not encoded)
user_index = search.Index(name | =USER_INDEX)
try:
if user_index.get(app_user_email):
user_index.delete(app_user_email)
except search.InvalidRequest:
pass
if not user_profile:
logging.info("Tried to index a user who is deactivated")
delete_user_index_document(user_index, app_user_email)
... |
bbockelm/glideinWMS | frontend/glideinFrontendConfig.py | Python | bsd-3-clause | 19,293 | 0.020577 | import string
import os.path
import urllib
import cPickle
import copy
import sys
from glideinwms.creation.lib.matchPolicy import MatchPolicy
from glideinwms.lib import hashCrypto
#
# Project:
# glideinWMS
#
# File Version:
#
# Description:
# Frontend config related classes
#
####################################... | ##########################################################
#
# Configuration
#
############################################################
class FrontendDes | cript(ConfigFile):
def __init__(self,config_dir):
global frontendConfig
ConfigFile.__init__(self,config_dir,frontendConfig.frontend_descript_file,
repr) # convert everything in strings
class ElementDescript(GroupConfigFile):
def __init__(self,base_dir,group_... |
hemmerling/codingdojo | src/game_of_life/python_coderetreat_berlin_2014-09/python_legacycrberlin01/gol01.py | Python | apache-2.0 | 685 | 0.013139 | #---------------------------------------------- | ---------------------------------
# Name: module1
# Purpose:
#
# Author: Admi | nistrator
#
# Created: 08/10/2011
# Copyright: (c) Administrator 2011
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
class Gol01:
def __init__(self):
self.isCellAlive = False
pass
def setAl... |
botswana-harvard/edc-death-report | edc_death_report/models/cause.py | Python | gpl-2.0 | 196 | 0 | from | edc_base.model_mixins import BaseModel, ListModelMixin
class Cause (ListModelMixin, BaseModel):
class Meta:
ordering = ['display_ind | ex']
app_label = 'edc_death_report'
|
plotly/python-api | packages/python/plotly/plotly/validators/cone/_vsrc.py | Python | mit | 426 | 0 | import _plotly_utils.basevalidators
class VsrcValidator(_plotly_utils.basevali | dators.SrcValidator):
def __init__(self, plotly_name="vsrc", parent_name="cone", **kwargs):
super(VsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwargs.pop("role", "info"),
... | **kwargs
)
|
anythingrandom/eclcli | eclcli/sss/v1/api_keypair.py | Python | apache-2.0 | 878 | 0.006834 | # -*- coding: utf-8 -*-
from eclcli.common import command
from eclcli.common import exceptions
from eclcli.common import utils
from eclcli.identity import common as identity_common
from ..sssclient.common.utils import objectify
class SetAPIKeypair(command.ShowOne):
def get_parser(self, prog_name):
parser... | lp=(""),
)
return parser
def take_action(se | lf, parsed_args):
sss_client = self.app.client_manager.sss
user_id = parsed_args.user_id
keypair = sss_client.set_api_keypair(user_id)
columns = utils.get_columns(keypair)
obj = objectify(keypair)
data = utils.get_item_properties(obj, columns)
... |
michaelerule/neurotools | graphics/pygame.py | Python | gpl-3.0 | 3,004 | 0.018642 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import division
from __future__ import print_function
'''
Collected utilities for pygame
It is difficult to write pixels directly in python.
There's some way to get a framebuffer bac... | /20
wait_til = time.time() + dt
print('Animating..')
for i in neurotools.tools.progress_bar(range(100)):
t = time.time()
if t<wait_til: time.sleep(wait_til-t)
wait_til = t + dt
npg.draw_array(screen, np.random.rand(K,K,3))
pygame.quit()
'''
import sys
import numpy as np
try:
import pygame as pg
ex... | issing; it is obsolete so this is not unusual')
print('pygame graphics will not work')
pg = None
def enable_vsync():
if sys.platform != 'darwin':
return
try:
import ctypes
import ctypes.util
ogl = ctypes.cdll.LoadLibrary(ctypes.util.find_library("OpenGL"))
# set ... |
h4ck3rm1k3/gcc_py_introspector | data/body4.py | Python | gpl-2.0 | 6,023 | 0.028889 | #!/usr/bin/python
from body3 import *
function_decl(link='extern',srcp='eval.c:216',
body=bind_expr(
body=statement_list(
E0=decl_expr(
ftype=void_type(algn=' | 8',name='126')),
E1=decl_expr(
ft | ype=void_type(algn='8',name='126')),
E2=modify_expr(
OP0=var_decl(algn='32',srcp='eval.c:53',used='1',
name=identifier_node(string='need_here_doc')),
OP1=integer_cst(low='0',
ftype=integer_type(algn='32',max='7',min='6',name='1',prec='32',sign='signed',size='5'))),
E3=cal... |
spnow/grr | gui/plugins/fileview_widgets.py | Python | apache-2.0 | 7,084 | 0.005364 | #!/usr/bin/env python
# Copyr | ight 2012 Google Inc. All Rights Reserved.
"""Widgets for advanced display of files." | ""
import json
from django import http
from grr.gui import renderers
from grr.lib import utils
class HexView(renderers.TemplateRenderer):
"""Display a HexView of a file.
Internal State:
- aff4_path: The name of the aff4 object we are viewing now.
- age: The version of the AFF4 object to display.
"... |
rahulunair/nova | nova/scheduler/filters/io_ops_filter.py | Python | apache-2.0 | 2,476 | 0 | # Copyright (c) 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 ... | ware
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
|
import nova.conf
from nova.scheduler import filters
from nova.scheduler.filters import utils
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
class IoOpsFilter(filters.BaseHostFilter):
"""Filter out hosts with too many concurrent I/O operations."""
RUN_ON_REBUILD = False
def _get_max_io_ops_pe... |
Fokko/incubator-airflow | tests/contrib/operators/test_ecs_operator.py | Python | apache-2.0 | 11,678 | 0.001199 | # -*- coding: utf-8 -*-
#
# 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
#... | sk_ended()
client_mock.get_waiter.assert_called_o | nce_with('tasks_stopped')
client_mock.get_waiter.return_value.wait.assert_called_once_with(
cluster='c', tasks=['arn'])
self.assertEqual(
sys.maxsize, client_mock.get_waiter.return_value.config.max_attempts)
def test_check_success_tasks_raises(self):
client_mock = mo... |
oxpeter/small_fry | blastfaster.py | Python | gpl-2.0 | 3,115 | 0.006742 | #!/usr/bin/env python
import re
import os
import sys
import math
import argparse
def count_deflines(fastafile):
"counts number of sequences are in a fasta file"
fasta_h = open(fastafile, 'rb')
counter = 0
for line in fasta_h:
if re.search('^>', line) is not None:
counter += 1
... | ast_type", type=str, default='blastp',
help="The blast algorithm to use. (d | efault = blastp)")
parser.add_argument("-p", "--num_threads", type=int, default=1,
help="number of threads to distribute blast over")
args = parser.parse_args()
## parse files to set the working directory for saving files
# parse input file:
fullname = os.path.realpath(ar... |
rodxavier/open-pse-initiative | django_project/api/views/quotes_views.py | Python | mit | 7,113 | 0.00478 | import json
from datetime import datetime
from django.conf import settings
from django.core.paginator import Paginator
import requests
from rest_framework import generics
from rest_framework import views
from rest_framework.pagination import PaginationSerializer
from rest_framework.renderers import BrowsableAPIRender... | elif from_date == to_date:
self.csv_filename += from_date
q | uote_date = datetime.strptime(from_date, '%Y-%m-%d')
items = items.filter(quote_date=quote_date)
else:
if from_date is not None:
self.csv_filename += 'from_' + from_date
from_date = datetime.strptime(from_date, '%Y-%m-%d')
items = items.fil... |
ccwang002/biocloud-server-kai | src/users/admin.py | Python | mit | 1,557 | 0 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import EmailUser as User
from .forms import AdminUserChangeForm, UserCreationForm
@admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = (
(
... | email', 'password')}
),
(
_('Personal info'),
{
'fields': (
'name', 'auth_number',
),
},
| ),
(
_('Permissions'),
{
'fields': (
'verified', 'is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions',
),
},
),
(
_('Important dates'),
{'f... |
KenKundert/abraxas | manpage.py | Python | gpl-3.0 | 83,088 | 0.008425 | #!/usr/bin/env python
# Abraxas Collaborative Password Utility Documentation
#
# Converts a restructured text version of the manpages to nroff.
# License {{{1
# 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 Softwa... | -c, --clipboard Write output to clipboard r | ather than stdout.
-t, --autotype Mimic a keyboard to send output to the active
window rather than stdout. In this case any
command line arguments that specify what to
output are ignored and the *autotype... |
dzoep/khal | khal/settings/settings.py | Python | mit | 5,410 | 0 | # Copyright (c) 2013-2016 Christian Geier et al.
#
# 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, merge, ... | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import os
from configobj import ConfigObj, flatten_errors, get_extra_values, \
ConfigObjError
from validate import Validator
... | eConfigFileError
from khal import __productname__
from ..log import logger
from .utils import is_timezone, weeknumber_option, config_checks, \
expand_path, expand_db_path, is_color
SPECPATH = os.path.join(os.path.dirname(__file__), 'khal.spec')
def _find_configuration_file():
"""Return the configuration file... |
Clivern/PyArchiver | pyarchiver/__init__.py | Python | mit | 110 | 0.009091 | """
Python Compression and Archiving Library
@autho | r: Clivern U{[email protected] | m}
"""
__VERSION__ = "1.0.0" |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/compiler/tests/slice_ops_test.py | Python | apache-2.0 | 5,088 | 0.004324 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3D(self):
for dtype in self.numeric_types:
with self.test_session():
i = array_ops.placeholder(dtype, shape=[3, 3, 10])
with self.test_scope():
o = array_ops.strided_slice(i, [0, 2, 2], [2, 3, 6], [1, 1, 2])
params = {
i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
... | [5, 3, 1, 7, 9, 2, 4, 6, 8, 0]],
[[5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[8, 7, 6, 5, 4, 3, 2, 1, 8, 7]],
[[7, 5, 7, 5, 7, 5, 7, 5, 7, 5],
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
[9, 8, ... |
tpeek/bike_safety | imagersite/imager_profile/migrations/0005_auto_20150802_0303.py | Python | mit | 1,491 | 0.001341 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imager_profile', '0004_auto_20150802_0153'),
]
operations = [
migrations.RemoveField(
model_name='imagerprofile'... | e),
),
migrations.AlterField(
model_name='imagerprofile',
name='camera',
field=models.CharField(help_text=b'What i | s the make and model of your camera?', max_length=128, null=True, blank=True),
),
migrations.AlterField(
model_name='imagerprofile',
name='photography_type',
field=models.CharField(blank=True, max_length=64, null=True, help_text=b'What is your photography type?', choi... |
chirpradio/chirpradio-machine | chirp/stream/do_proxy_barix_status.py | Python | apache-2.0 | 4,423 | 0.000452 |
import BaseHTTPServer
import logging
import os
import sys
import threading
import time
from chirp.common.conf import (BARIX_STATUS_HOST, BARIX_STATUS_PORT,
BARIX_HOST, BARIX_PORT)
from chirp.stream import barix
_TIMEOUT_S = 2
_POLLING_FREQUENCY_S = 5
_STATUS_PAGE = """<html><head... | _level,
"right_level": b_obj.right_level,
"left_level_avg": int(left_level_avg),
"right_level_avg": int(right_level_avg),
"level_avg_window_minutes": int(level_avg_window_minutes),
"live365_connected": NOT_CONNECTED,
"archiver_con | nected": NOT_CONNECTED,
}
# TODO(trow): Check IP address.
if "12345" in b_obj.clients:
barix_info["live365_connected"] = "connected"
# TODO(trow): Check IP address.
if "12346" in b_obj.clients:
barix_info["archiver_connected"] = "connected"
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.