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 |
|---|---|---|---|---|---|---|---|---|
mdworks2016/work_development | Python/20_Third_Certification/venv/lib/python3.7/site-packages/pip/_internal/commands/list.py | Python | apache-2.0 | 10,511 | 0 | # The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
from __future__ import absolute_import
import json
import logging
from multiprocessing.dummy import Pool
from pip._vendor import six
from pip._vendor.requests.adapters import DEFAULT_POOLSIZE
from pip._interna... | ditable',
action='store_false',
dest='include_editable',
help='Exclude editable package from output.',
)
cmd_opts.add_option(
'--include-editable',
action='store_true',
dest='include_editable',
help='Inclu | de editable package from output.',
default=True,
)
index_opts = cmdoptions.make_option_group(
cmdoptions.index_group, self.parser
)
self.parser.insert_option_group(0, index_opts)
self.parser.insert_option_group(0, cmd_opts)
def _build_package_finder(... |
shady831213/myBlog | myBlog/articles/urls.py | Python | mit | 156 | 0.00641 | from .views import *
from rest_framework.routers import | Defaul | tRouter
router = DefaultRouter()
router.register(r'', ArticleView)
urlpatterns = router.urls |
cvegaj/ElectriCERT | venv3/lib/python3.6/site-packages/tox/hookspecs.py | Python | gpl-3.0 | 3,276 | 0.000916 | """ Hook specifications for tox.
"""
from pluggy import HookspecMarker, HookimplMarker
hookspec = HookspecMarker("tox")
hookimpl = HookimplMarker("tox")
@hookspec
def tox_addoption(parser):
""" add command line options to the argparse-style parser object."""
@hookspec
def tox_configure(config):
""" calle... | :class:`tox.venv.VirtualEnv`.
.. note:: This hook uses ``firstresult=True`` (see pluggy_) -- hooks
implementing this will be run until one returns non-``None``.
.. _pluggy: http://pluggy.readthedocs.io/en/latest/#first-result-only
"""
@hookspec(firstresult=True)
def tox_testenv_install_deps(ven... | for this venv.
Some example usage:
- To *add* behavior but still use tox's implementation to install
dependencies, implement this hook but do not return a value (or
explicitly return ``None``). One use-case may be to install (or ensure)
non-python dependencies such as debian packages.
-... |
pipermerriam/flex | flex/loading/common/max_length.py | Python | mit | 1,274 | 0.000785 | from flex.error_messages import MESSAGES
from flex.exceptions import ValidationError
from flex.constants import (
EMPTY,
INTEGER,
STRING,
)
from flex.utils import pluralize
from flex.validation.common import (
generate_object_validator,
)
from flex.decorators import (
pull_keys_from_obj,
suffix_... | EMPTY or maxLength is EMPTY:
return
if not maxLength >= minLength:
raise ValidationError(
MESSAGES['max_length']['must_be_greater_than_min_length']
)
@pull_keys_from_obj('type', 'maxLength')
@suffix_reserved_words
@skip_if_any_kwargs_empty('type_', 'maxLength')
def validate_ty... | STRING,)):
raise ValidationError(
MESSAGES['type']['invalid_type_for_max_length'],
)
max_length_schema = {
'type': INTEGER,
'minimum': 1,
}
max_length_validator = generate_object_validator(
schema=max_length_schema,
)
|
showa-yojyo/notebook | source/_sample/ptt/users-suggestions-slug.py | Python | mit | 406 | 0 | #!/usr/ | bin/env python
# Demonstration GET users/suggestions/:slug
# See https://dev.twitter.com/rest/reference/get/users/suggestions/%3Aslug
from secret import twitter_instance
from json import dump
from urllib.parse import quote
import sys
tw = twitter_instance()
# [1]
response = tw.users.suggestions._id(_id=quote('政府'))... | rue)
|
endlessm/chromium-browser | third_party/chromite/api/gen/chromiumos/metrics_pb2.py | Python | bsd-3-clause | 3,384 | 0.005615 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: chromiumos/metrics.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 reflectio... | _ranges=[],
oneofs=[
],
serialized_start=40,
serialized_end=145,
)
DESCRIPTOR.message_types_by_name['MetricEvent'] = _METRICEVENT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
MetricEvent = _reflection.GeneratedProtocolMessageType('MetricEvent', (_message.Message,), dict(
DESCRIPTOR = _METRICEVENT,
__module_... | ope:chromiumos.MetricEvent)
))
_sym_db.RegisterMessage(MetricEvent)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
|
SmartElect/SmartElect | rollgen/tests/test_generate_pdf.py | Python | apache-2.0 | 11,178 | 0.002773 | # 3rd party imports
from bidi.algorithm import get_display as apply_bidi
# Django imports
from django.conf import settings
# Project imports
from .base import TestGeneratePdfBase
from .factories import create_voters
from .utils_for_tests import extract_pdf_page, extract_textlines, clean_textlines, unwrap_lines
from .... | er_roll = []
def test_blank_page_content_male(self):
"""tests that the "blank" page explains why it is blank (no voters)"""
generate_pdf(self.filename, self.center, self.voter_roll, MALE)
# Build a list of the lines I expect to see.
expected_lines = []
expected_lines.append... | S['center_list_header'])
expected_lines.append(self.STRINGS['no_male_registrants'])
expected_lines.append("1 / 1")
# Now see what was actually in the PDF and compare to expected.
xml = extract_pdf_page(self.filename, 1)
textlines = extract_textlines(xml)
actual_lines = c... |
mattupstate/flabric | flabric/ubuntu/nginx_uwsgi_supervisor.py | Python | mit | 7,722 | 0.007123 | from __future__ import with_statement
from cuisine import *
from fabric.api import env
from fabric.colors import *
from fabric.utils import puts
from fabric.context_managers import cd, settings, prefix
from flabric import ApplicationContext as AppContext
from flabric.ubu | ntu import UbuntuServer
import os, flabric
class Server(UbuntuServer):
"""nginx, uWSGI and supervisor server"""
def setup(self):
with mode_sudo():
group_ensure('admin')
for u in [('ubuntu', '/home/ | ubuntu')]:
puts(green('Ensuring user: ' + u[0]))
user_ensure(u[0], home=u[1])
group_user_ensure('admin', 'ubuntu')
puts(green("Updating /etc/sudoers"))
file_update(
'/etc/sudoers',
lambda _: text_ensure_line(_,
... |
City-of-Helsinki/django-helusers | helusers/providers/helsinki_oidc/provider.py | Python | bsd-2-clause | 1,192 | 0 | from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
from helusers.user_utils import oidc_to_user_data
from helusers.utils import uuid_to_username
class HelsinkiOIDCAccount(ProviderAccou... | name = 'City of Helsinki employees (OIDC)'
package = 'helusers.providers.helsinki_oidc'
account_class = HelsinkiOIDCAccount
def extract_uid(self, data):
return str(data['sub'])
def extract_common_fields(self, data): |
ret = oidc_to_user_data(data)
ret['username'] = uuid_to_username(data['sub'])
return ret
def get_default_scope(self):
return ['openid profile email']
providers.registry.register(HelsinkiOIDCProvider)
|
smarsland/AviaNZ | CompareCalls.py | Python | gpl-3.0 | 41,275 | 0.003828 | # Self-standing executable for tall comparison mode
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QFileDialog, QPushButton, QPlainTextEdit, QWidget, QGridLayout, QDoubleSpinBox, QGroupBox, QSizePolicy, QSpacerItem, QLayout, QProgressDialog, QMessageBox, QVBoxLayout, QHBoxLayout, QStyle, QComboBox, QDi... | self.w_browse.setSizePolicy(QSizePolicy(1,1))
self.w_browse.clicked.connect(self.browse)
| # area showing the selected folder
self.w_dir = QPlainTextEdit()
self.w_dir.setReadOnly(True)
self.w_dir.setFixedHeight(40)
self.w_dir.setPlainText('')
self.w_dir.setSizePolicy(QSizePolicy(3,1))
# feedback label
self.labelDatasIcon = QLabel()
self.label... |
acq4/acq4 | acq4/util/Canvas/items/MarkersCanvasItem.py | Python | mit | 6,603 | 0.003938 | # -*- coding: utf-8 -*-
from __future__ import print_function
import weakref
from acq4.util import Qt
from .CanvasItem import CanvasItem
import pyqtgraph as pg
import pyqtgraph.graphicsItems.TargetItem
from .itemtypes import registerItemType
class MarkersCanvasItem(CanvasItem):
"""
Canvas item used for markin... | ParameterItem):
def | __init__(self, param, depth):
pg.parametertree.ParameterItem.__init__(self, param, depth)
self.valueChanged(self.param, self.param.value())
def valueChanged(self, param, val):
strs = tuple([pg.siFormat(x, suffix='m') for x in val])
self.setText(1, '[%s, %s, %s]' % strs)
class Poin... |
bcornwellmott/frappe | frappe/test_runner.py | Python | mit | 9,730 | 0.026824 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
import frappe
import unittest, json, sys
import xmlrunner
import importlib
from frappe.modules import load_doctype_module, get_module_name
from frappe.utils impor... | rappe.flags.tests_verbose = verbose
out = unittest_runner(verbosity=1+(verbose and 1 or 0)).run(test_suite)
if profile:
pr.disable()
s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stat | s()
print(s.getvalue())
return out
def _add_test(app, path, filename, verbose, test_suite=None, ui_tests=False):
import os
if os.path.sep.join(["doctype", "doctype", "boilerplate"]) in path:
# in /doctype/doctype/boilerplate/
return
app_path = frappe.get_pymodule_path(app)
relative_path = os.path.relpat... |
wehkamp/ansible | lib/ansible/plugins/__init__.py | Python | gpl-3.0 | 12,794 | 0.005237 | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foun... |
The first match is used.
'''
def __init__(self, class_name, package, config, sub | dir, aliases={}, required_base_class=None):
self.class_name = class_name
self.base_class = required_base_class
self.package = package
self.config = config
self.subdir = subdir
self.aliases = aliases
i... |
edublancas/sklearn-evaluation | docs/source/nbs/train.py | Python | mit | 2,218 | 0 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.8.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import importlib
from sklearn.datasets import load... | p
import matplotlib.pyplot as plt
# + tags=["parameters"]
model = 'sklearn.ensemble.RandomForestRegressor'
params = {'min_sa | mples_leaf': 1, 'n_estimators': 50}
# + tags=["model_name"]
model
# -
d = load_boston()
X = d['data']
y = d['target']
tokens = model.split('.')
name, module = tokens[-1], '.'.join(tokens[:-1])
class_ = getattr(importlib.import_module(module), name)
# + tags=["feature_names"]
list(d['feature_names'])
# -
X_train, X... |
FederatedAI/FATE | python/fate_arch/protobuf/python/inference_service_pb2_grpc.py | Python | apache-2.0 | 3,942 | 0.005835 | #
# Copyright 2019 The FATE 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 appli... | pc.unary_unary_rpc_method_handler(
servicer.startInferenceJob,
request_deserializer=inference__service__pb2.InferenceMessage.FromString,
response_serializer=inference__service__pb2.InferenceMessage.SerializeToString,
),
'getInferenceResult': grpc.unary_unary_rpc_method_handler(... | response_serializer=inference__service__pb2.InferenceMessage.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.webank.ai.fate.api.serving.InferenceService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
|
googleapis/python-orchestration-airflow | google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py | Python | apache-2.0 | 45,966 | 0.00124 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | ironmentsAsyncClient: The constructed client.
"""
return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this ... | ng the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
... |
paleocore/paleocore | mlp/admin.py | Python | gpl-2.0 | 12,404 | 0.004918 | from django.contrib import admin
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
import unicodecsv
import base.admin # import default PaleoCore admin classes
from models import Occurrence, Biology, Taxon, Tax... | = ('Detailed Description', {'fields': [('element', 'element_modifier')]})
biology_fieldsets.insert(2, taxonomy_fieldsets)
biology_fieldsets.insert(3, element_fieldsets)
fieldsets = biology_fieldsets
def create_data_csv(self, request, queryset):
"" | "
Export data to csv format. Still some issues with unicode characters.
:param request:
:param queryset:
:return:
"""
request.GET.getlist()
response = HttpResponse(content_type='text/csv') # declare the response type
response['Content-Disposition'] = 'att... |
mick-d/nipype | nipype/interfaces/ants/tests/test_auto_AffineInitializer.py | Python | bsd-3-clause | 1,633 | 0.028169 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..utils import AffineInitializer
def test_AffineInitializer_inputs():
input_map = dict(args=dict(argstr='%s',
),
dimension=dict(argstr='%s',
position=0,
usedefault=True,
),
environ=dict(nohas... | ition=5,
usedefault=True,
),
search_factor=dict(argstr='%f',
position=4,
usedefault=True,
),
terminal_output=dict(deprecated='1.0.0',
nohash=True,
),
)
inputs = AffineInitializer.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in lis... | s()[key], metakey) == value
def test_AffineInitializer_outputs():
output_map = dict(out_file=dict(),
)
outputs = AffineInitializer.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metak... |
jmuhlich/indra | models/ras_220_genes/get_ras_pmids.py | Python | bsd-2-clause | 8,882 | 0.001689 | import csv
import sys
from indra.literature import pubmed_client
from collections import OrderedDict
from matplotlib import pyplot as plt
import pickle
import numpy as np
import boto3
import botocore
import os
from indra.literature import id_lookup
from indra.literature import crossref_client
from texttable import Text... |
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delim | iter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
pmids = OrderedDict()
pmids_from_gene = OrderedDict()
for gene in gene_list:
print "Querying for", gene
ids_gene = set(pubmed_client.get_ids_for_gene(gene))
print "Found %d in gene query" % len(id... |
Distrotech/bzr | bzrlib/tests/per_workingtree/__init__.py | Python | gpl-2.0 | 6,108 | 0.000164 | # Copyright (C) 2006-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | or workingtree_format in formats:
result.append((workingtree_format.__class__.__name__,
make_scenario(transport_server,
transport_readonly_server,
workingtree_format)))
default_wt_format = workingtree.format_reg... | TCPServer_for_testing
if remote_readonly_server is None:
remote_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
if remote_backing_server is None:
remote_backing_server = memory.MemoryServer
scenario = make_scenario(remote_server, remote_readonly_server,
... |
chinbat/google-python-exercises | basic/string1.py | Python | apache-2.0 | 3,640 | 0.012912 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic string exercises
# Fill in the code for the functions below. main() is already se... | eplaced by strb.
def fix_start(s):
# +++your code h | ere+++
h = s[0]
t = s.replace(h,"*")
return h+t[1:]
# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or mor... |
bubenkoff/Arkestra | arkestra_utilities/templatetags/insert_tags.py | Python | bsd-2-clause | 798 | 0.006266 | from django import template
from django.template.defaultfilters import safe
from arkestra | _utilities.models import Insert
from classytags.arguments import Argument
from classytags.core import Tag, Options
register = template.Library()
class RenderInserter(Tag):
name = 'insert'
options = Options(
Argument('insertion_point'),
Argument('width', | default=None, required=False),
)
def render_tag(self, context, insertion_point, width):
inserter, created = Insert.objects.get_or_create(insertion_point = insertion_point)
request = context.get('request', None)
if not request:
return ''
if not inserter.content:
... |
mattea/mattea-utils | matteautils/match/vectorsim.py | Python | apache-2.0 | 17,233 | 0.031103 | #!/usr/bin/python
from __future__ import division
import math
import signal
import sys
import numpy as np
from scipy.spatial import distance
from munkres import munkres
from . import Matcher
from itertools import izip
from scipy.stats import kendalltau
from matteautils.base import printd
import matteautils.config as co... | , [x.vector for x in s2])
class VecSim(Matcher):
def __init__(self, df=None, metric='cosine'):
self.metric = getMetric(m | etric)
@classmethod
def normalize(self, vec, df=None):
return vec, np.sum(vec, axis=0)
def match(self, pair):
self.pair = pair
self.s1 = pair.s1
self.s2 = pair.s2
self.tsim = 1 - self.metric([self.s1["vec_sum"]], [self.s2["vec_sum"]])[0, 0]
self.nmatches = -1
self.start = -1
self.end = len(self.s2[... |
allmende/synnefo | snf-django-lib/snf_django/management/tests.py | Python | gpl-3.0 | 977 | 0.001024 | import sys
from snf_django.management import utils
# Use backported unittest functionality if Python < 2.7
try:
import unittest2 as unittest
except ImportError:
if sys.version_info < (2, 7):
raise Exception("The unittest2 package is required for Python < 2.7")
import unittest
class ParseFiltersTe... | s = utils.parse_queryset_filters("x=2")
self.assertEqual(res, ({"x": "2"}, {}))
res = utils.parse_queryset_filters("x!=2")
self.assertEqual(res, ({}, {"x": "2"}))
def test_parse_many(self):
res = utils.parse_queryset_filters("x=2,x>=3,y!=4,z<3")
filters = {"x": "2", "x__gte"... | |
nephila/djangocms-newsletter | djangocms_newsletter/utils/vcard.py | Python | bsd-3-clause | 1,371 | 0.000729 | """VCard system for exporting Contact models"""
from datetime import datetime
import vobject
from django.http import HttpResponse
def vcard_contact_export(contact):
"""Export in VCard 3.0 a Contact model instance"""
if hasattr(contact.content_object, 'vcard_export'):
return contact.content_object.vc... | lize()
def vcard_contacts_export(contacts):
"""Export multiples contacts in VCard"""
export | = ''
for contact in contacts:
export += '%s\r\n' % vcard_contact_export(contact)
return export
def vcard_contacts_export_response(contacts, filename=''):
"""Return VCard contacts attached in a HttpResponse"""
if not filename:
filename = 'contacts_edn_%s' % datetime.now().strftime('%d-%... |
endlessm/chromium-browser | third_party/depot_tools/fix_encoding.py | Python | bsd-3-clause | 12,462 | 0.00979 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Collection of functions and classes to fix various encoding problems on
multiple platforms with python.
"""
from __future__ import print_function
im... | ly close the handle, that would only cause problems.
self.closed = True
def fileno(self):
return self._fileno
def flush(self):
raise NotImplementedError()
def write(self, text):
raise NotImplementedError()
def writelines(self, lines):
try:
for line in lines:
self.write(line... | nUnicodeOutputBase):
"""Output adapter to a Windows Console.
Understands how to use the win32 console API.
"""
def __init__(self, console_handle, fileno, stream_name, encoding):
super(WinUnicodeConsoleOutput, self).__init__(
fileno, '<Unicode console %s>' % stream_name, encoding)
# Handle to us... |
clld/pycdstar | tests/test_config.py | Python | apache-2.0 | 454 | 0 | import | os
import pytest
from pycdstar.config import Config
@pytest.fixture
def cfg_path(tmpdir):
return str(tmpdir.join('.config', 'config.ini'))
def test_new_config(cfg_path):
assert not os.path.exists(cfg_path)
Config(cfg=cfg_path)
assert os.path. | exists(cfg_path)
def test_existing_config(configfile):
cfg = Config(cfg=configfile)
assert cfg.get('service', 'user') == 'user'
assert cfg.get('a', 'b', default=9) == 9
|
Ekleog/nmgr | src/nmgr/route.py | Python | agpl-3.0 | 1,239 | 0.007264 | #
# This file is part of nmgr.
# Copyright (C) 2015 Leo Gaspard
#
# nmgr 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.
#
# nmgr is di... | e
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Licens | e
# along with nmgr. If not, see <http://www.gnu.org/licenses/>.
#
import nmgr
from collections import namedtuple
import sh
_RouteMetadata = namedtuple('_IpMetadata', ['action', 'subnet', 'meta'])
def _send_message(action, subnet, meta):
data = _RouteMetadata(
action = action,
subnet = subnet,
... |
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/subversion/bindings/ctypes-python/examples/mucc.py | Python | gpl-2.0 | 4,445 | 0.00315 | #!/usr/bin/env python
# Multiple URL Command Client
#
# Combine a list of mv, cp, rm, and put commands on URLs into a single commit
#
# To read the help for this program, type python mucc.py --help
import os
from csvn.core import *
from csvn.repos import RemoteRepository, RepositoryURI
from csvn.auth import User
from... | =args[2])
elif action == "rm":
txn.delete(args[1])
elif action == "mkdir":
txn.mkdir(args[1])
elif action == "put":
txn.upload(local_path=args[1], remote_path=args[2])
elif action == "propset":
txn.propset(key=args[1], value=args[2], path=args[3])
elif action == "prop... | (message)
print("r%ld committed by %s at %s" % (txn.committed_rev, options.username,
txn.committed_date))
|
NobodysNightmare/python-smadata2 | smadata2/db/tests.py | Python | gpl-2.0 | 8,741 | 0.000343 | #! /usr/bin/env python
from __future__ import print_function
import StringIO
import os
import os.path
import errno
import sqlite3
from nose.tools import *
import smadata2.db
import smadata2.db.mock
from smadata2 import check
def removef(filename):
try:
os.remove(filename)
except OSError as e:
... | ls(y2, 2*val)
|
def test_aggregate_one(self):
val = self.db.get_aggregate_one_historic(self.dusk,
(self.serial1, self.serial2))
assert_equals(val, 3*((self.dusk - self.dawn - 2) / 300))
def check_aggregate_range(self, from_, to_):
results = self.db.get_... |
pylixm/liBlog | liBlog/blogs/admin.py | Python | mit | 523 | 0.001927 | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Post, Tag, Category
# # 添加blogs models
# myapp = apps.get_app_config('blogs')
# for model in | myapp.get_models():
# admin.site.register(model)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_time', 'category', 'status',
'view_count', 'update_time']
search_fields = ['title', 'categ | ory__name']
admin.site.register(Post, PostAdmin)
admin.site.register(Tag)
admin.site.register(Category) |
Lamecarlate/gourmet | gourmet/plugins/nutritional_information/shopping_plugin.py | Python | gpl-2.0 | 3,401 | 0.010291 | from gourmet.plugin import ShoppingListPlugin
import gtk
import gourmet.recipeManager, gourmet.GourmetRecipeManager
from gourmet.prefs import get_prefs
from nutritionLabel import NutritionLabel
import os.path
from gettext import gettext as _
class ShoppingNutritionalInfoPlugin (ShoppingListPlugin):
ui_string = ''... | s(rec)
ni = rd.nd.get_nutinfo_for_inglist(rd.get_ings(rec),
rd)
if nutinfo:
nutinfo = nutinfo + ni
else:
nutinfo = ni
# Add extras...
for amt,unit,item in sg.extras:
ni = rd.nd.... | nutinfo = nutinfo + ni
else:
nutinfo = ni
self.nl.set_nutinfo(nutinfo)
self.nutrition_window.present()
def create_nutrition_window (self):
self.nutrition_window = gtk.Dialog(_('Nutritional Information'),
self.pluggable.w,
... |
DuCorey/bokeh | examples/models/server/linked_tap.py | Python | bsd-3-clause | 2,181 | 0.00917 | from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnData... | adius
source2.on_change('selected', on_selection_change2)
reset = Button(label="Reset")
def on_reset_click():
source1.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
source2.selected = {
'0d': {'flag': False, 'indices': []}... | : {'indices': []},
'2d': {'indices': {}}
}
reset.on_click(on_reset_click)
widgetBox = WidgetBox(children=[reset], width=150)
row = Row(children=[widgetBox, plot1, plot2])
document = curdoc()
document.add_root(row)
if __name__ == "__main__":
print("\npress ctrl-C to exit")
session = push_session(... |
rdio/translate-toolkit | search/indexing/PyLuceneIndexer1.py | Python | gpl-2.0 | 7,865 | 0.000636 | # -*- coding: utf-8 -*-
#
# Copyright 2008 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at y... | @type queries: list of xapian.Query
@param require_all: boolean operator
| (True -> AND (default) / False -> OR)
@type require_all: bool
@return: the resulting combined query object
@rtype: PyLucene.Query
"""
combined_query = PyLucene.BooleanQuery()
for query in queries:
combined_query.add(
PyLucene.Boolean... |
jesseengel/magenta | magenta/tensor2tensor/t2t_trainer.py | Python | apache-2.0 | 1,130 | 0.00354 | # Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tensor2Tensor trainer for Magenta problems."""
# Registers all Magenta problems with Tensor2Tensor.
from __future__ import absolute_import
from __future__ import division
from __... | port
from tensor2tensor.bin import t2t_trainer
import tensorflow as tf
def main(argv):
t2t_trainer.main(argv)
def console_entry_point():
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(main)
if __name__ == '__main__':
console_entry_point()
|
acsone/server-tools | auth_admin_passkey/tests/__init__.py | Python | agpl-3.0 | 1,069 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Admin Passkey module for Odoo
# Copyright (C) 2013-2014 GRAP (http://www.grap.coop)
# @author Sylvain LE GAL (https://twitter.com/legalsylvain)
#
# This program is free software: you can redistribute... | tion) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##########################################... |
3dfxsoftware/cbss-addons | clean_user_groups/wizard/__init__.py | Python | gpl-2.0 | 19 | 0 | i | mpo | rt clean_group
|
swkoubou/molt | molt_app.py | Python | mit | 5,850 | 0 | """Molt Web API with Interface."""
import re
import redis
import docker
import subprocess
import os
import shlex
import requests
import sys
import argparse
from flask import Flask, Response, render_template, abort, request
from molt import Molt, MoltError
app = Flask(__name__)
# コマンドライン引数のパース
parser = argparse.Argum... | mat(event)
event_stream += 'dat | a: {}\n'.format(data)
if id:
event_stream += 'id: {}\n'.format(id)
if retry:
event_stream += 'retry: {}\n'.format(id)
event_stream += '\n'
return event_stream
if __name__ == '__main__':
# RSA鍵の生成
user = os.getenv('USER')
ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_de... |
vickenty/ookoobah | pyglet-c9188efc2e30/tests/test.py | Python | mit | 20,890 | 0.002729 | #!/usr/bin/env python
'''Test framework for pyglet. Reads details of components and capabilities
from a requirements document, runs the appropriate unit tests.
How to Run the Tests
--------------------
::
python tests/test.py top app graphics clock resource # these all run automatically
python tests/test.py... | th::
2to3 --output-dir=tests3 -W -n tests
And then run the tests int tests3 directory.
'''
from __future__ import print_function
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import array
import logging
import os
imp | ort optparse
import re
import sys
import time
import unittest
# So we can find tests.regression and ensure local pyglet copy is tested.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pyglet import compat_platform
import tests.regression
import pyglet.image
regressions_path = os.path.join(os.p... |
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/doctorwhumour/app.py | Python | mit | 147 | 0.006803 | #encoding:utf-8
subreddit = 'DoctorWhumour'
t_channel = '@DoctorWhumour'
def send_post(submission, r2t) | :
return r2t.send_simple(submis | sion)
|
dschep/HELPeR | helper/utils/models.py | Python | gpl-3.0 | 1,457 | 0.001373 | from helper.models import AgentMeta
from django import forms
class OAuthAgentMixinMeta(AgentMeta):
def __init__(cls, name, bases, dct):
if bases: # not 1st base class(the mixin), only subclasses
from he | lper.utils.views import OAuth2Login
| class Login(OAuth2Login):
authorization_url = cls.oauth_opts['authorization_url']
token_url = cls.oauth_opts['token_url']
scopes = cls.oauth_opts.get('scopes', [])
cls.user_config_options = cls.user_config_options.copy()
cls.user_config_opt... |
alexandrucoman/vbox-neutron-agent | neutron/tests/unit/agent/linux/test_ip_lib.py | Python | apache-2.0 | 43,884 | 0.000456 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Li | cense"); 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, so | ftware
# 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.
import mock
import netaddr
from neutron.agent.common ... |
dosarudaniel/coala-bears | tests/general/KeywordBearTest.py | Python | agpl-3.0 | 6,974 | 0 | from collections import namedtuple
from queue import Queue
import unittest
from bears.general.KeywordBear import KeywordBear
from coalib.results.HiddenResult import HiddenResult
from coalib.results.SourceRange import SourceRange
from coalib.settings.Section import Section
from coalib.settings.Setting import Setting
fr... | y_results=dep_results) as result:
s | elf.assertEqual(result[0].diffs['F'].unified_diff,
'--- \n'
'+++ \n'
'@@ -1 +1 @@\n'
'-test = 55 # todo 123\n'
'+test = 55\n')
def test_keyword_outside_of_comment(self):
... |
mythmon/kitsune | kitsune/wiki/templatetags/jinja_helpers.py | Python | bsd-3-clause | 534 | 0.001873 | import jinja2
from django_jinja import library
from kitsune.sumo import parser
from kitsune.wiki.diff import BetterHtmlDiff
@library.global_function
def diff_table(content_from, content_to):
"""Creates an HTML diff of the passed in content_from and content_to."""
html_diff = BetterHtmlDiff()
diff = html_... | om.splitlines(), content_to.splitlines(), context=True)
return jinja2.Markup(diff)
@library.global_function
def generate_video(v):
return jinja2.Markup(par | ser.generate_video(v))
|
seankelly/buildbot | master/buildbot/test/unit/test_data_root.py | Python | gpl-2.0 | 3,723 | 0.001343 | # This file is part of Buildbot. Buildbot 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 program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | esourceTypeClass = root.Spec
def setUp(self):
self.setUpEndpoint()
# replace fakeConnector with real DataConnector
self.master.data.disownServiceParent()
self.master.data = connector.DataConnector()
| self.master.data.setServiceParent(self.master)
def tearDown(self):
self.tearDownEndpoint()
@defer.inlineCallbacks
def test_get(self):
specs = yield self.callGet(('application.spec',))
[self.validateData(s) for s in specs]
for s in specs:
# only test an endp... |
haypo/perf | pyperf/tests/test_timeit.py | Python | mit | 16,335 | 0.000306 | import errno
import os.path
import re
import shutil
import sys
import tempfile
import textwrap
import unittest
import pyperf
from pyperf import tests
from pyperf._timeit import Timer
PERF_TIMEIT = (sys.executable, '-m', 'pyperf', 'timeit')
# We only need a statement taking longer than 0 nanosecond
FAST_BENCH_ARGS = ... | , filename)
stdout = self.run_timeit(args)
bench = pyperf.Benchmark.load(filename)
return (bench, stdout)
def test_verbose_output(self):
args = ('-p', '2',
'-w', '1',
'-n', '3',
# don't pass --loops to test calibration
... | s = PERF_TIMEIT + args
# Don't check the exact output, only check that the verbose
# mode doesn't fail with an error (non-zero exist code)
self.run_timeit_bench(args)
def test_bench(self):
loops = 4
args = ('-p', '2',
'-w', '1',
'-n', '3',
... |
tobbelobb/D3D-Printrun | printrun/printcore.py | Python | gpl-3.0 | 25,268 | 0.005026 | #!/usr/bin/env python
# This file is part of the Printrun suite.
#
# Printrun 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.
#
# Prin... | from Queue import Queue, Empty as QueueEmpty
import time
import platform
import os
import sys
stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
reload(sys).setdefaultencoding('utf8')
sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
import loggi | ng
import traceback
import errno
import socket
import re
from functools import wraps
from collections import deque
from printrun import gcoder
from .utils import install_locale, decode_utf8
install_locale('pronterface')
def locked(f):
@wraps(f)
def inner(*args, **kw):
with inner.lock:
retur... |
mikeh77/mi-instrument | mi/idk/test/test_comm_config.py | Python | bsd-2-clause | 8,878 | 0.006195 | #!/usr/bin/env python
"""
@package mi.idk.test.test_comm_config
@file mi.idk/test/test_comm_config.py
@author Bill French
@brief test metadata object
"""
__author__ = 'Bill French'
__license__ = 'Apache 2.0'
from os.path import basename, dirname
from os import makedirs
from os import remove
from os.path import exist... | EVICE_DATA_BITS = 8
DEVICE_PARITY = 0 # 0=none, 1=odd, 2=even
DEVICE_STOP_BITS = 1 # 1 or 2
DEVICE_FLOW_CONTROL = 0 # 0=none, 1=hardware, 2=software
ROOTDIR="/tmp/test_config.idk_test"
# /tmp is a | link on OS X
if exists("/private/tmp"):
ROOTDIR = "/private%s" % ROOTDIR
CONFIG_FILE="comm_config.yml"
@attr('UNIT', group='mi')
class TestCommConfig(MiUnitTest):
"""
Test the comm config object.
"""
def setUp(self):
"""
Setup the test case
"""
if not exis... |
joelpg/usdxworldparty | game/languages/update.py | Python | gpl-3.0 | 4,599 | 0.031963 | #!/usr/bin/python
# UltraStar Deluxe - Karaoke Game
#
# UltraStar Deluxe is the legal property of its developers, whose names
# are too numerous to list here. Please refer to the COPYRIGHT
# file distributed with this source distribution.
#
# This program is free software; you can redistribute it and/or
# modify it un... | True
for or | ig in english:
m2 = re.match("\s*" + m.group(1) + "\s*=(.+)$", orig)
# ignore translated lines (already written in first pass)
if (m2):
unsupported = False
break
# unsupported translation
if (unsupported):
print(" -" + m.group(1))
outList.append(";UNUSED: " + m.group(1) + "=" + m.group(2))
... |
zulily/node_status | node_status/version.py | Python | apache-2.0 | 623 | 0 | # Copyright (C) 2015 zulily, llc
#
# 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, ... | e the License for the specific language governing permissions and
# limi | tations under the License.
"""node_status version"""
__version__ = '0.1.0'
|
co-ment/comt | src/cm/management/commands/create_manager.py | Python | agpl-3.0 | 1,407 | 0.014925 | from django.core.management.base import LabelCommand, CommandError, BaseCommand, make_option
from base64 import b64decode
class Command(LabelCommand):
option_list = BaseCommand.option_list + (
make_option('--base64', action='store_true', dest='base64', default=False,
help='Assume all input are ... | = b64decode(labels[2])
first_name = b64decode(labels[3])
last_name = b64decode(labels[4])
else:
email = labels[0]
username = labels[1]
password = labels[2]
| first_name = labels[3]
last_name = labels[4]
email = email.decode('utf8')
username = username.decode('utf8')
password = password.decode('utf8')
first_name = first_name.decode('utf8')
last_name = last_name.decode('utf8')
from cm.mode... |
datafiniti/Diamond | src/diamond/handler/multigraphitepickle.py | Python | mit | 2,505 | 0.000399 | # coding=utf-8
"""
Send metrics to a [graphite](http://graphite.wikidot.com/) using the pickle
interface. Unlike GraphitePickleHandler, this one supports multiple graphite
servers. Specify them as a list of hosts divided by comma.
"""
from Handler import Handler
from graphitepickle import GraphitePickleHandler
from c... | alhost'],
'port': 2003,
'proto': 'tcp',
'timeout': 15,
'batch': 1,
'max_backlog_multiplier': 5,
'trim_backlog_multiplier': 4,
})
return config
def process(self, metric):
"""
Process a metric by passing it to Gr... | """
for handler in self.handlers:
handler.process(metric)
def flush(self):
"""Flush metrics in queue"""
for handler in self.handlers:
handler.flush()
|
matthewoliver/swift | test/unit/common/test_storage_policy.py | Python | apache-2.0 | 57,607 | 0 | # 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... | BaseStoragePolicy, 1, 'one')
@patch_policies([
| StoragePolicy(0, 'zero', is_default=True),
StoragePolicy(1, 'one'),
StoragePolicy(2, 'two'),
StoragePolicy(3, 'three', is_deprecated=True),
ECStoragePolicy(10, 'ten', ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=10, ec_nparity=4),
])
def test_swift_info(self):
... |
anokata/pythonPetProjects | flaskChat/config.py | Python | mit | 206 | 0 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATAB | ASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
CSRF_ENABLED = True
SECRET_KEY = 'f35fc593c73a35956a70d0a | 7eeac9bdb'
|
klen/bottle-manage | setup.py | Python | mit | 1,585 | 0.003155 | #!/usr/bin/env python
import re
from os import path as op
from setuptools import setup
def _read(fname):
try:
return open(op.join(op.dirname(__file__), fname)).read()
except IOError:
return ''
_meta = _read('bottle_manage.py')
_license = re.search(r'^__license__\s*=\s*"(.*)"', _meta, re.M).g... | search(r'^__project__\s*=\s*"(.*)"', _meta, re.M).group(1)
_version = re.search(r'^__version__\s*=\s*"(.*)"', _meta, re.M).group(1)
install_requires = [
l for l in _read('requirements.txt').split('\n')
if l and not l.startswith('#')]
setup(
name=_project,
version=_version,
license=_license,
de... | enov',
author_email='horneds@gmail.com',
url='https://github.com/klen/bottle-manage',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Natural Language :: Russi... |
CauldronDevelopmentLLC/OpenSCAM | examples/python/camotics_python_example.py | Python | gpl-2.0 | 7,363 | 0.003803 | #!/usr/bin/env python3
#
# CAMotics is an Open-Source simulation and CAM software.
# Copyright (C) 2011-2021 Joseph Coffland <joseph@cauldrondevelopment.com>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
... | .253
X191.300Y200.120
X192.050Y229.010
X188.157Y202.652
X187.735Y192.991
X182.952Y186.144
X183.233Y177.795
X189.987Y168.228
X186.891Y164.570
X175.729Y160.349
X170.851Y155.283
X170.101Y149.468
X165.724Y1 | 50.030
X155.281Y157.159
X142.524Y158.379
X137.083Y162.037
X136.333Y164.007
X126.203Y156.221
X123.107Y155.846
X122.638Y155.096
X120.293Y160.818
X117.761Y161.943
X117.010Y155.096
X113.258Y156.034
X114.196Y161.287
X111.945
X107.818Y153.970
X102.040Y159.973
X93.935Y165.320
X92.247Y165.414
X91.403Y161.849
X86.181Y159.223
X6... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/optimize/tests/test_nonlin.py | Python | mit | 15,054 | 0.006311 | """ Unit tests for nonlinear solvers
Author: Ondrej Certik
May 2007
"""
from __future__ import division, print_function, absolute_import
from numpy.testing import assert_
import pytest
from scipy._lib.six import xrange
from scipy.optimize import nonlin, root
from numpy import matrix, diag, dot
from numpy.linalg impor... | for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
df = f - self.fs[last_j]
dx = x - self.xs[last_j]
H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df)
jac.update(x, f)
assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13))
... | st_anderson(self):
# Anderson mixing (with w0=0) satisfies secant conditions
# for the last M iterates, see [Ey]_
#
# .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3)
class TestLinear(object):
"""Solve a linear equ... |
cbertinato/pandas | pandas/tests/tseries/offsets/test_offsets.py | Python | bsd-3-clause | 131,811 | 0 | from datetime import date, datetime, timedelta
from distutils.version import LooseVersion
import numpy as np
import pytest
from pandas._libs.tslibs import (
NaT, OutOfBoundsDatetime, Timestamp, conversion, timezones)
from pandas._libs.tslibs.frequencies import (
INVALID_FREQ_ERR_MSG, get_freq_code, get_freq_s... | 'BusinessDay': Timestamp('2011-01-03 09:00:00'),
'CustomBusinessDay': Timestamp('2011-01-03 09:00:00'),
'CustomBusinessMonthEnd': Timestamp('2011-01-31 09:00:00'),
'CustomBusinessMonthBegin': Timestamp('2011-01-03 09:00:00'),
'MonthBegin': Timestamp('2... | 9:00:00'),
'MonthEnd': Timestamp('2011-01-31 09:00:00'),
'SemiMonthEnd': Timestamp('2011-01-15 09:00:00'),
'SemiMonthBegin': Timestamp('2011-01-15 09:00:00'),
'BusinessMonthEnd': Timestamp('2011-01-31 09:00:00'),
'YearBegin': Timestamp... |
open-austin/influence-texas | src/influencetx/finances/apps.py | Python | gpl-2.0 | 91 | 0 | from django.apps import AppConfig
class Finan | cesConfig(AppConfi | g):
name = "finances"
|
YelaSeamless/mysql-connector-python | tests/test_errorcode.py | Python | gpl-2.0 | 2,311 | 0 | # MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... | n, MA 02110-1301 USA
"""Unittests for mysql.connector.errorcode
"""
from datetime import | datetime
import tests
from mysql.connector import errorcode
class ErrorCodeTests(tests.MySQLConnectorTests):
def test__MYSQL_VERSION(self):
minimum = (5, 6, 6)
self.assertTrue(isinstance(errorcode._MYSQL_VERSION, tuple))
self.assertTrue(len(errorcode._MYSQL_VERSION) == 3)
self.ass... |
bajo/ros_installer_gui | tkmain.py | Python | gpl-2.0 | 8,340 | 0.004796 | #!/usr/bin/python
__author__ = 'Markus Bajones'
__license__ = 'GPL'
__version__ = '1.0.0'
__email__ = 'markus.bajones@gmail.com'
"""
- download ROS key from keyserver and install it
- show settings (mirror/package selection/ROS distro)
- install selected packages
- rosdep update, and init
"""
import ImageTk
import l... | ef write_shell_config(self):
shell = self.select_shell.get()
| content = "".join(['source /opt/ros/', self.select_ros_version.get(), '/setup.', shell])
file = os.path.join(os.environ['HOME'], "".join(['.',shell,'rc']))
try:
if not os.path.exists(file) or not content in open(file).read():
with open(file, 'a+') as f:
... |
yotchang4s/cafebabepy | src/main/python/test/test_binhex.py | Python | bsd-3-clause | 1,498 | 0.003338 | """Test script for the binhex C module
Uses the mechanism of the python binhex module
Based on an original test by Roger E. Masse.
"""
import binhex
import unittest
from test import support
cla | ss BinHexTestCase(unittest.TestCase):
def setUp(self):
self.fname1 = support.TESTFN + "1"
self.fname2 = support.TESTFN + "2"
self.fname3 = support.TESTFN + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__"
def tearD | own(self):
support.unlink(self.fname1)
support.unlink(self.fname2)
support.unlink(self.fname3)
DATA = b'Jack is my hero'
def test_binhex(self):
f = open(self.fname1, 'wb')
f.write(self.DATA)
f.close()
binhex.binhex(self.fname1, self.fname2)
bin... |
HEP-DL/proton_decay_study | setup.py | Python | mit | 1,937 | 0.003614 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools import setup, find_packages
from pip.req import parse_req | uirements
import pip
install_reqs = reqs = [str(ir.req) for ir in parse_requirements('requirements.txt',
session=pip.download.PipSession())]
dev_reqs = [str(ir.req) for ir in parse_requirements('requirements_dev.txt',
session=pip.download.PipSession())]
setup(
name='proton_decay_study',
version='0.2.... | description="Looks for proton decay. USING NEURAL NETWORKS",
long_description="""
Top-level code base for CNN study of LArTPC data for proton decay.
This relies primarily on Kevlar and Keras with the Tensorflow backend.
Kevlar provides the data interface consumed by the generators. Keras a... |
maheswaranm/finman | finman/urls.py | Python | mit | 1,149 | 0.00087 | """finman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | e, url
from django.contrib | import admin
from django.contrib.auth.views import login, logout_then_login
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('finmancore.urls')),
url(r'^login', login, name='login'),
url(r'^logout', logout_then_login, name='logout'),
]
if settings.DEBUG:
import debug_toolbar
... |
fsbr/se3-path-planner | scratch/cones.py | Python | mit | 473 | 0.019027 | # attempting to implement the parametric equations of a cone
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes | 3D
# from http://mathworld.wolfram.com/Cone.html
h = 1
r = 1 # r is a constant
u = np.linspace(0,h)
tht = np.linspace(0,2*np.pi)
x = ((h-u)/(h))*r*np.cos(tht)
y = ((h-u)/(h))*r*np.sin(tht)
z = u
x,y = np.meshgrid(x,y)
fig = plt.figure()
ax = plt.subplot(111,projection='3d')
ax.plot_surface(x,y,z)
ax.legend()
plt.sho... | )
|
GdZ/scriptfile | software/googleAppEngine/google/net/proto2/python/public/text_format.py | Python | mit | 19,690 | 0.010157 | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | L_REPEATED:
for element in value:
PrintField(field, element, out, indent, as_utf8, as_one_line)
else:
| PrintField(field, value, out, indent, as_utf8, as_one_line)
def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False):
"""Print a single field name/value pair. For repeated fields, the value
should be a single element."""
out.write(' ' * indent);
if field.is_extension:
out.write('... |
vprusso/youtube_tutorials | utility_scripts/wav_to_mp3/wav_to_mp3.py | Python | gpl-3.0 | 356 | 0 | # YouTube Video: https://www.youtube.com/watch?v=4E7N7W | 1lUkU
import os
import pydub
import glob
wav_files = glob.glob('./*.wav')
for wav_file in wav_files:
mp3_file = os.path.splitext(wav_file)[0] + '.mp3'
sound = pydub.AudioSegment.from_wav(wav_file)
sound.export(mp3_file, format="mp3")
os.remove(wav_file)
print("Conv | ersion Complete")
|
SecPi/SecPi | worker/speaker.py | Python | gpl-3.0 | 1,590 | 0.030818 | import pygame
import logging
from tools.action import Action
class Speaker(Action):
def __init__(self, id, params):
super(Speaker, self).__init__(id, params)
try:
self.path_to_audio = params["path_to_audio"]
self.repetitions = int(params["repetitions"])
except ValueError as ve: # if repetitions can't be... | lay audio")
pygame.mixer.init()
try:
pygame.mixer.music.load | (self.path_to_audio)
except Exception as e: # audio file doesn't exist or is not playable
logging.error("Speaker: Wasn't able to load audio file: %s" % e)
pygame.mixer.quit()
return
pygame.mixer.music.set_volume(1)
for i in range(0, self.repetitions):
pygame.mixer.music.rewind()
pygame.mixer.music... |
pythonistas-tw/academy | web-api/0x90/models.py | Python | gpl-2.0 | 1,061 | 0.002828 | import hashlib
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import validates
from sqlalchemy.ext.declarative import declar | ative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'User'
id = Column(Integer, primary_key=True)
account = Column(String)
password = Column(String)
@validates('account')
def validate_email_format(self, key, account):
assert '@' in account
return account
... | f __init__(self, account, password):
self.account = account
self.password = hashlib.sha1(password).hexdigest()
def __repr__(self):
return "User('%s', '%s')" % \
(self.account, self.password)
def check_password(self, password):
if hashlib.sha1(password).hexdigest() == se... |
chrisspen/django-pjm | django_pjm/migrations/0003_auto__add_lmpdastatus.py | Python | mit | 3,576 | 0.007271 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LMPDAStatus'
db.create_table(u'django_pjm_lmpdastatus', (... | node': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'day_ahead_prices'", 'to': "orm['django_pjm.Node']"}),
'start_datetime': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'total': ('django.db.models.fields.DecimalField', [], {'max_digits': '10', 'de... | teField', [], {'unique': 'True', 'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'loaded_zones': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'})
},
'django_pjm.node': {
'Meta': {'o... |
jakobadam/origo-desktops | manage.py | Python | gpl-3.0 | 246 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.enviro | n.setdefault("DJANGO_SETTINGS_MODULE", "rds.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys | .argv)
|
jeremymcrae/denovoFilter | denovoFilter/missing_symbols.py | Python | mit | 5,967 | 0.007206 | """
Copyright (c) 2016 Genome Research Ltd.
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, publish, distr... | TWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PY | THON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series ... |
dreid/cql3parser | cql3parser/types.py | Python | mit | 682 | 0 | def _type(name, package='org.apache.cassandra.db.marshal'):
return '{0}.{1}'.format(package, name)
native | _types = {
'ASCII': _type('AsciiType'),
'BIGINT': _type('LongType'),
'BLOB': _type('BytesType'),
'BOOLEAN': _type('BooleanType'),
'COUNTER': _type('CounterColumnType'),
'DECIMAL': _type('DecimalType'),
'DOUBLE': _t | ype('DoubleType'),
'FLOAT': _type('FloatType'),
'INET': _type('InetAddressType'),
'INT': _type('Int32Type'),
'TEXT': _type('UTF8Type'),
'TIMESTAMP': _type('DateType'),
'UUID': _type('UUIDType'),
'VARCHAR': _type('UTF8Type'),
'VARINT': _type('IntegerType'),
'TIMEUUID': _type('TimeUUID... |
ramielrowe/python-magnumclient | magnumclient/exceptions.py | Python | apache-2.0 | 2,751 | 0.000364 | # -*- coding: utf-8 -*-
#
# 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 i... | t/* then it expects
# the response to have a 'text' attribute, but that
# doesn't always seem to necessarily be the case.
# This is to work around that problem.
| response.text = ''
return exceptions.from_response(response, message, url)
|
supersheep/huixiang | controller/page/auth_redirect.py | Python | mit | 329 | 0.006079 | # /auth/redirect/(douban|weibo)
imp | ort web
import traceback
from util import oauth
class auth_redirect:
def GET(self,name):
try:
client = oauth.createClientWithName(name)
url = client.redirect()
web.seeother(url)
except Exception:
return traceback.format_ex | c()
|
xiaoyongaa/ALL | 函数和常用模块/81sys模块.py | Python | apache-2.0 | 276 | 0.043478 | import s | ys
import os
#sys.exit("sd")
def jingd | u(i,max):
shu=i/max
shu=int(shu*max)
shu="\r{du}>{shu}%".format(du="#"*i,shu=shu)
#print(shu)
sys.stdout.write(shu)
sys.stdout.flush()
def main():
for i in range(0,101):
jingdu(i,100)
main() |
ehem/kdztools | libexec/gpt.py | Python | gpl-3.0 | 8,879 | 0.032098 | #!/usr/bin/env python
"""
Copyright (C) 2016 Elliott Mitchell <ehem+android@m5p.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | def display(self, idx):
"""
Display t | he data for this slice of a GPT
"""
if self.type == UUID(int=0):
verbose("Name: <empty entry>")
return None
verbose("Name({:d}): \"{:s}\" start={:d} end={:d} count={:d}".format(idx, self.name, self.startLBA, self.endLBA, self.endLBA-self.startLBA+1))
verbose("typ={:s} id={:s}".format(str(self.type), str... |
ParallelDots/WordEmbeddingAutoencoder | tyrion/train.py | Python | mit | 3,305 | 0.006354 | '''
Code to train Word embeddings on given corpus.
'''
import sys
from probarray import ProbArray
from compatibility import range, pickle
import re
import json
import os
import numpy as np
import argparse
import time
import pdb
CONFIG_PATH = sys.argv[1]
DATA_PATH = sys.argv[2]
config_file = open(CONFIG_PATH, 'r')
C... | ord = pa.wordnumrelation.getWord(num)
if backend == 'tf':
embedding = tm.getoutput(wordvec, './embedding.chk')
else:
embedding = tm.getoutput(wordvec)
| wordembeddings[word] = embedding
print ("Training proces done, dumping embedding into persistant storage!")
with open(r'./embeddings.pickle', "wb") as outfile:
pickle.dump(wordembeddings, outfile)
print ("Training completed! Embedding done.")
print ("time is %f" % (time.time()-t))
if __nam... |
Caparrini/pyGenreClf | classifier.py | Python | apache-2.0 | 19,503 | 0.006512 | from sklearn.model_selection import StratifiedKFold
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.metrics import confusion_matrix
from tools import ConfusionMatrixUtils
import pydotplus
import numpy as np
import matplotlib.pyp... | ETC = ExtraTreesClassifier(bootstrap=True, criterion="gini",max_features=1, min_samples_leaf=2,min_samples_split=10, n_estimators=100)
# Accuracy 138 step 50 with BPM essentia (0.56260869565217386, 0.012251306785743798)
#ETC = E | xtraTreesClassifier(bootstrap=False, criterion="gini",max_features=0.5, min_samples_leaf=2,min_samples_split=10, n_estimators=100)
# Best with GTZAN
#1 0.534 +- 0.01 with beatsdataset.csv
#2 0.46 +- 0.01 with beatsdataset1-1-01-005.csv
#3 0.48 +- 0.014 with beatsdataset1-1-01-01.csv
#4 0.422 +- 0.0... |
Teagan42/home-assistant | homeassistant/components/bitcoin/sensor.py | Python | apache-2.0 | 6,395 | 0.000625 | """Bitcoin information service that uses blockchain.info."""
from datetime import timedelta
import logging
from blockchain import exchangerates, statistics
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY... | e == "total_btc":
self._state = "{0:.2f}".format(stats.total_btc * 0.00000001)
elif self.type == "total_blocks":
self._state = "{0:.0f}".format(stats.total_blocks)
elif self.type == "next_retarget":
self._state = "{0:.2f}".format(stats.next_retarget)
elif self... | e == "miners_revenue_btc":
self._state = "{0:.1f}".format(stats.miners_revenue_btc * 0.00000001)
elif self.type == "market_price_usd":
self._state = "{0:.2f}".format(stats.market_price_usd)
class BitcoinData:
"""Get the latest data and update the states."""
def __init__(self):... |
flask-admin/flask-admin | flask_admin/tests/mongoengine/__init__.py | Python | bsd-3-clause | 537 | 0 | from unittest import SkipTest
from wtforms import __version__ as wtforms_version
if int(wtforms_version[0]) < 2:
raise SkipTest('MongoEngine does not support WTForms 1.')
from flask import Flask
fro | m flask_admin import Admin
from flask_mongoengine import MongoEngine
def setup():
app = Flask(__name__)
app.config['SECRET_KEY'] = '1'
app.config['CSRF_ENABLED'] = False
app.config['MONGODB_SETTINGS'] = {'DB': 'tests'}
db = MongoEngine()
db.init_app(app)
admin = Admin(app)
return ap... | dmin
|
Akasurde/virt-manager | virtinst/cli.py | Python | gpl-2.0 | 79,481 | 0.001334 | #
# Utility functions for the command line drivers
#
# Copyright 2006-2007, 2013, 2014 Red Hat, Inc.
# Jeremy Katz <katzj@redhat.com>
#
# This program is free software; you can redistribute it and | /or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) 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... | he
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import argparse
import logging
import logging.handlers
... |
martinbalfanz/reads-api | src/reads/settings.py | Python | mit | 45 | 0 | from reads.conf.development import * # | NOQA
| |
ryan-lane/keystone-redis | keystoneredis/token.py | Python | apache-2.0 | 3,492 | 0.000286 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Ian Good
# Copyright 2014 Ryan Lane
#
# 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... | d)
value = self.readonly.get(token_key)
if value:
toke | n = jsonutils.loads(value)
if token.get('expires', None) is not None:
token['expires'] = dateutil.parser.parse(token['expires'])
if token['expires'] > timeutils.utcnow():
return token
else:
return token
raise exception.T... |
dls-controls/dls_ade | dls_ade/module_creator.py | Python | apache-2.0 | 17,511 | 0 | import os
import shutil
import logging
from getpass import getuser
from dls_ade import vcs_git, Server
from dls_ade.exceptions import (RemoteRepoError, VerificationError,
ArgumentError)
class ModuleCreator(object):
"""Abstract base class for the management of the creation of new m... | eation.
"""
self._usermsg = loggin | g.getLogger("usermessages")
self._area = area
self._cwd = os.getcwd()
self._module_path = module_path
self._module_name = os.path.basename(os.path.normpath(
self._module_path))
self.server = Server()
self.abs_module_path = o... |
spaam/svtplay-dl | lib/svtplay_dl/fetcher/dash.py | Python | mit | 15,830 | 0.002716 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
import copy
import math
import os
import re
import time
import xml.etree.ElementTree as ET
from datetime import datetime
from urllib.parse import urljoin
from svtplay_dl.error import ServiceError
from svtplay_dl.error import UIExc... | []
dirname = os.path.dirname(url) + "/"
if baseurl:
dirname = urljoin(dirname, baseurl)
for element | in elements:
role = "main"
template = element.find("{urn:mpeg:dash:schema:mpd:2011}SegmentTemplate")
represtation = element.findall(".//{urn:mpeg:dash:schema:mpd:2011}Representation")
role_elemets = element.findall(".//{urn:mpeg:dash:schema:mpd:2011}Role")
codecs = None
... |
stackforge/monasca-log-api | monasca_log_api/conf/role_middleware.py | Python | apache-2.0 | 1,759 | 0 | # Copyright 2017 FUJITSU 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 writ... | F ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
| from oslo_config import cfg
role_m_opts = [
cfg.ListOpt(name='path',
default='/',
help='List of paths where middleware applies to'),
cfg.ListOpt(name='default_roles',
default=['monasca-user'],
help='List of roles allowed to enter api'),
cfg.Li... |
AppScale/crisismap | perms_test.py | Python | apache-2.0 | 9,382 | 0.011405 | #!/usr/bin/python
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | Login('owner'):
# Check owner roles.
self.assertEquals({'MAP_OWNER', 'MAP_EDITOR', 'MAP_VIEWER'},
GetRolesForMap(m))
| # Verify the owner can perform expected operations.
self.assertRaises(
perms.AuthorizationError, model.Map.Create, '{}', 'xyz.com')
version_id = m.PutNewVersion('{}')
m.SetWorldReadable(False)
m.GetCurrent()
m.GetVersions()
m.GetVersion(version_id)
with test_utils.Lo... |
userzimmermann/robotframework | utest/utils/test_frange.py | Python | apache-2.0 | 3,046 | 0.001641 | from six.moves import range
import unittest
from robot.utils.frange import frange, _digits
from robot.utils.asserts import assert_equals, assert_true, assert_raises
class TestFrange(unittest.TestCase):
def test_basics(self):
for input, expected in [([6.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
... | 3e20, 5e20, 7e20, 9e20]),
([1e-21, 1.1e-20, 3e-21], [1e-21, 4e-21, 7e-21, 1e-20]),
([1.1e-20, 1.1e-21, -5e-21], [1.1e-20, 6e-21])]:
result = frange(*input)
| assert_equals(len(result), len(expected))
# Floats are not accurate and values depend on Python versions
diffs = [round(r-e, 30) for r, e in zip(result, expected)]
assert_equals(sum(diffs), 0)
def test_compatibility_with_range(self):
for input in [(10,), (-10,), (... |
googleapis/protoc-java-resource-names-plugin | plugin/utils/proto_utils.py | Python | bsd-3-clause | 3,560 | 0 | # Copyright 2016, Google Inc.
# 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 list of conditions and the f... | other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor t | he 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 WARRANTI... |
dssg/education-college-public | code/etl/uploaders/load_kippnj.py | Python | mit | 3,663 | 0.07644 | from etl.pipeline.tableuploader import UploadTable
import etl.cleaners.clean_kippnj as clean_kippnj
import etl.db_schema.SQLtables_cols as SQLtables_cols
import config
def main():
# Student IDs
UploadTable(rawcsv_dict = { 'kipp_nj_students': config.DATA_PATH + 'kipp_nj/raw_data/students_db_jul20.csv' },
rawtoc... | an_kippnj.act_table,
sq | ltable_name = 'kipp_nj.acttests',
sqltable_cols = SQLtables_cols.acttests,
overwrite=True
)
# Courses
UploadTable(rawcsv_dict = { 'kipp_nj_courses': config.DATA_PATH + 'kipp_nj/raw_data/courses_db_aug5.csv' },
rawtoclean_fn = clean_kippnj.courses_table,
sqltable_name = 'kipp_nj.courses',
sql... |
ohsu-qin/qiutil | qiutil/ast_config.py | Python | bsd-2-clause | 8,113 | 0.006163 | import os
import re
import ast
from six.moves.configparser import ConfigParser as Config
from .logging import logger
class ConfigError(Exception):
"""Configuration parsing error."""
pass
def read_config(*locations):
"""
Reads and parses the given configuration files.
:param locations: the i... | :return: the equivalent AST string
"""
# Trivial case.
if not s:
return
| # If the input is a boolean, number or already quoted,
# then we are done.
if ASTConfig.PARSEABLE_ITEM_PAT.match(s):
return s
# If the string is a list, then make a quoted list.
# Otherwise, if the string signifies a boolean, then return the boolean.
# ... |
gdementen/PyTables | tables/tests/test_array.py | Python | bsd-3-clause | 95,636 | 0.000073 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import tempfile
import warnings
import numpy
from numpy import testing as npt
import tables
from tables import Atom, ClosedNodeError, NoSuchNodeError
from tables.utils import byteorders
from ta... | ptarr[...] = a
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
root = fileh.root
# Read the saved array
b = root.somearray.read()
# Compare them. Th | ey should be equal.
if common.verbose and not allequal(a, b):
print("Write and read arrays differ!")
# print("Array written:", a)
print("Array written |
youtube/cobalt | third_party/web_platform_tests/tools/wptserve/tests/functional/test_handlers.py | Python | bsd-3-clause | 11,798 | 0.002119 | import json
import os
import unittest
import uuid
import pytest
from six.moves.urllib.error import HTTPError
wptserve = pytest.importorskip("wptserve")
from .base import TestUsingServer, doc_root
class TestFileHandler(TestUsingServer):
def test_GET(self):
resp = self.request("/document.txt")
sel... | boundary = resp.info()["Content-Type"].split("boundary=")[1]
parts = data.split("--" + boundary)
self.assertEqual("\r\n", parts[0])
self.assertEqual("--", parts[-1])
expected_parts = [("1-2", expected | [1:3]), ("5-10", expected[5:11])]
for expected_part, part in zip(expected_parts, parts[1:-1]):
header_string, body = part.split("\r\n\r\n")
headers = dict(item.split(": ", 1) for item in header_string.split("\r\n") if item.strip())
self.assertEqual(headers["Content-Type"], "t... |
jhseu/tensorflow | tensorflow/python/keras/losses.py | Python | apache-2.0 | 45,944 | 0.003635 | # Copyright 2015 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... | compile` and `fit`, please use 'SUM' or 'NONE' reduction
types, and reduce losses explicitly in your training loop. Using 'AUTO' or
'SUM_OVER_BATCH | _SIZE' will raise an error.
Please see
https://www.tensorflow.org/tutorials/distribute/custom_training for more
details on this.
You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like:
```python
with strategy.scope():
loss_obj = tf.keras.losses.CategoricalCrossentropy(
reduction=... |
FBergeron/FeedNotifier | templates.py | Python | bsd-3-clause | 954 | 0.005241 | import os
import jinja2 as jinja
import util
DEFAULT_THEME = | 'default'
def create_env():
path = os.path.abspath('.')
loader = jinja.FileSystemLoader(path)
env = jinja.Environment(loader=loader)
return env
def render(theme, item, context=None):
feed = item.feed
reldir = 'themes/%s' % theme
absdir = util.abspath(reldir)
if | feed.has_favicon:
icon = util.abspath(feed.favicon_path)
else:
icon = util.abspath('icons/feed.png')
context = context or {}
context['item'] = item
context['feed'] = feed
context['icon'] = icon
context['reldir'] = reldir
context['absdir'] = absdir
try:
template = ... |
Esri/community-parcels-python | source/arcrest/agol/featureservice.py | Python | apache-2.0 | 30,058 | 0.00682 | """
.. module:: featureservice
:platform: Windows, Linux
:synopsis: Represents functions/classes used to control Feature Services
.. moduleauthor:: Esri
"""
import types
from base import BaseAGOLClass
import layer as servicelayers
import common
from filters import LayerDefinitionFilter, GeometryFilter, TimeFi... | lf._maxRecordCount
#----------------------------------------------------------------------
@property
def supportedQueryFormats(self):
""" returns the supported query formats """
if self._supportedQueryFormats is None:
self.__init()
return self._supportedQueryFormats
#... | "" returns a list of capabilities """
if self._capabilities is None:
self.__init()
return self._capabilities
#----------------------------------------------------------------------
@property
def description(self):
""" returns the service description """
if self._d... |
conda/kapsel | conda_kapsel/plugins/providers/redis.py | Python | bsd-3-clause | 15,703 | 0.003121 | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | pr | oject_option = """Always start a
project-dedicated redis-server, using a port between <input type="text" name="lower_port"/>
and <input type="text" name="upper_port"/>
"""
return """
<div>
<label><input type="radio" name="source" value="find_all"/>Use system default Redis when it's running,
... |
nylas/sync-engine | migrations/versions/153_revert_account_unique_constraint.py | Python | agpl-3.0 | 921 | 0.001086 | """revert account unique constraint
Revision ID: 4032709362da
Revises: 211e93aff1e1
Create Date: 2015-03-25 23:46:25.649192
"""
# revision identifiers, used by Alembic.
revision = '4032709362da'
down_revision = '211e93aff1e1'
from alembic import op
def upgrade():
conn = op.get_bind()
index_name = conn.exe | cute(
'''SELECT index_name FROM information_schema.statistics WHERE
table_name="account" AND non_unique=0 AND
| column_name="_canonicalized_address"''').fetchone()[0]
op.drop_constraint(index_name, 'account', type_='unique')
if index_name == 'ix_account__canonicalized_address':
op.create_index('ix_account__canonicalized_address', 'account',
['_canonicalized_address'], unique=False)
def... |
oesteban/quality-assessment-protocol | qap/dvars.py | Python | bsd-3-clause | 6,915 | 0.016486 | import nibabel as nib
import numpy as np
from scipy import stats
def remove_zero_variance_voxels(func_timeseries, mask):
for i in range(0, len(func_timeseries)):
for j in range(0, len(func_timeseries[0])):
for k in range(0, len(func_timeseries[0][0])):
var = func_timeseries... | eviation
func_sd = robust_stdev(func, interp)
# AR1
func_ar1 = ar1(func)
# Predicted standard deviation of temporal derivative
func_sd_pd = np.sqrt(2 * (1 - func_ar1)) * func_sd
diff_sd_mean= func_sd_pd.mean()
# Compute temporal difference time series
func_deriv = np.dif... | _plain = func_deriv.std(1, ddof=1) # TODO: Why are we not ^2 this & getting the sqrt?
## standardization
dvars_stdz = dvars_plain/diff_sd_mean
## voxelwise standardization
diff_vx_stdz= func_deriv/func_sd_pd
dvars_vx_stdz = diff_vx_stdz.std(1, ddof=1)
if output_all:
out = np.vstack... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.