repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
schneiml/uxr | cgi-bin/uxr.py | #!/usr/bin/env python3
import cgi
import os
import time
import re
import subprocess
import fnmatch
# Where the code lives, relative to the cgi $PWD
treename = "tree/"
# same for the index files
indexname = "index/"
# the path '/cgi-bin/uxr.py' to this script is hardcded in many places.
# too much trouble to make it va... |
sergey-dryabzhinsky/dedupsqlfs | dedupsqlfs/compression/quicklz.py | # -*- coding: utf8 -*-
__author__ = 'sergey'
"""
Class for QuickLz compression helper
@deprecated
"""
from dedupsqlfs.compression import BaseCompression
class QuickLzCompression(BaseCompression):
_method_name = "quicklz"
_minimal_size = 17
_deprecated = True
_has_comp_level_options = False
... |
Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-certificates/azure/keyvault/certificates/_generated/aio/_key_vault_client.py | # 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 ... |
pauloinca/estimators | treeClass.py | '''
by Paulo Inca <pauloginca@hotmail.com>
MIT Style License
'''
from Queue import Queue
class Node:
'''
Node class defines the nodes, where which node
has a value, a left and a right subtree.
'''
def __init__(self, key):
self.key = key
self.children = []
def children_number(self):
return len(... |
sdpython/pymyinstall | src/pymyinstall/packaged/packaged_config_A_orange.py | # -*- coding: utf-8 -*-
"""
@file
@brief Modules for Orange
"""
from ..installhelper.module_install import ModuleInstall
def orange_set():
"""
modules implemented for Orange, it requires the modules in set *ml*
"""
mod = [
ModuleInstall(
"pdfminer3k", "pip",
purpose="PD... |
DylanMcCall/stuartmccall.ca | galleries/admin.py | from django.contrib import admin
from django.urls import resolve, reverse
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from common.templatetags.image_tools import image_style
from galleries import models
import os
class PortfolioMediaInline(admin.TabularInline):... |
Acruxx/ARS | car.py | import sys, pygame
from Vec2 import *
import math
import pdb
import time
from Globals import *
class Car:
def __init__(self, ang, rad):
self.ang = ang
self.rad = rad
self.offsetAngle = 0
self.img = None
self.loadImage()
self.breakImgTemplate = pygame.image.load(... |
marrow/server | setup.py | #!/usr/bin/env python
# encoding: utf-8
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (2, 6):
raise SystemExit("Python 2.6 or later is required.")
exec(open(os.path.join("marrow", "server", "release.py")).read())
setup(
name = name,
version = version,... |
arruah/ensocoin | qa/rpc-tests/p2p-versionbits-warning.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Copyright (c) 2016-2017 The Ensocoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framewor... |
AutorestCI/azure-sdk-for-python | azure-batch/azure/batch/models/user_account.py | # 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 ... |
tautomer/langevin_dynamics | langevin_dynamics/force_eval.py | # functions to evaluate force
import numpy as np
from random import gauss
class ForceEval:
def __init__(self, lam, temp, arr_x, arr_y, d_x, d_y, n_y, k_pot, k_fx, k_fy, pot, fx, fy):
self.lam = lam
self.T = temp
self.arr_x = arr_x
self.arr_y = arr_y
self.dx = d_x
s... |
RobinCPC/algorithm-practice | Backtracking/permuteUnique.py | """
#: 47
Title: Permution II
Description:
------
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
```
[
[1,1,2],
[1,2,1],
[2,1,1]
]
```
------
Time: O(n*n!)
Space: O(n)
Difficulty: Medium
... |
t0adie/Adafruit_python_PN532 | examples/hhpi_listen.py | # Raspberry Pi Hilly Hundred NFC Tag Registration
# Author: Derek Naulls
# Copyright (c) 4D Concepts
#
# 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 l... |
westerncapelabs/django-grs-gatewaycms | gopher/migrations/0003_auto__add_field_airtimeapplication_sms__add_field_airtimeapplication_c.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'AirtimeApplication.sms'
db.add_column(u'gopher_airtimeapplication', 'sms',
... |
maartenbreddels/vaex | packages/vaex-core/vaex/samp.py | # -*- coding: utf-8 -*-
# from sampy import *
# from SocketServer import ThreadingMixIn
# try:
# import sampy
# except ImportError:
# import astropy.samp as sampy
import logging
import threading
import time
import astropy.samp
import getpass
import requests
from requests.auth import HTTPBasicAuth
import astropy.io.vota... |
vipmunot/HackerRank | Sorting-Bubble Sort.py | # -*- coding: utf-8 -*-
"""
@author: Vipul Munot
Python: 3
"""
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
def bubblesort(array):
no_of_pass = 0
for i in range(len(array)):
for j in range(i+1,len(array)):
if array[j] < array[i]:
array[j],array[i] =... |
hoafaloaf/seqparse | seqparse/containers.py | """Classes utilized by the Seqparse class."""
# Standard Libraries
import os
from collections import MutableMapping, MutableSet
from functools import total_ordering
from .files import File
from .sequences import FileSequence
__all__ = ("FileExtension", "FileSequenceContainer", "SingletonContainer")
################... |
claudio-walser/knack | knack/Hypervisor/VmwareWorkstation.py | #!/usr/bin/env python3
import os
import subprocess
from knack.Hypervisor.AbstractHypervisor import AbstractHypervisor
from knack.Hypervisor.VmwareWorkstationHelper.Vmx import Vmx
from knack.Hypervisor.VmwareWorkstationHelper.Disk import Disk
from knack.Hypervisor.VmwareWorkstationHelper.VmwareTools import VmwareTool... |
hackebrot/pytest-cookies | tests/conftest.py | # -*- coding: utf-8 -*-
import collections
import json
import pytest
pytest_plugins = "pytester"
@pytest.fixture(name="cookiecutter_template")
def fixture_cookiecutter_template(tmpdir):
template = tmpdir.ensure("cookiecutter-template", dir=True)
template_config = collections.OrderedDict(
[("repo_n... |
johnnyliu27/openmc | openmc/capi/__init__.py | """
This module provides bindings to C functions defined by OpenMC shared library.
When the :mod:`openmc` package is imported, the OpenMC shared library is
automatically loaded. Calls to the OpenMC library can then be via functions or
objects in the :mod:`openmc.capi` subpackage, for example:
.. code-block:: python
... |
dfm/getout | getout/frontend.py | # -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["frontend"]
import flask
from flask.ext.login import current_user, login_required
from .models import db
from .forms import SignupForm, ProfileForm
frontend = flask.Blueprint("frontend", __name__, template_folder="templates")
@fro... |
alephnullplex/mmdb | mmdb/wsgi.py | """
WSGI config for mmdb project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS... |
Avinch/CassBotPy | cogs/core.py | import asyncio
import datetime
import re
import textwrap
from io import BytesIO
import sys
import json
import aiohttp
import discord
from utils import checks
DISCORD_INVITE = r'discord(?:app\.com|\.gg)[\/invite\/]?(?:(?!.*[Ii10OolL]).[a-zA-Z0-9]{5,6}|[a-zA-Z0-9\-]{2,32})'
INVITE_WHITELIST = [
"https://discord.g... |
jmcarp/marshmallow-sqlalchemy | tests/test_marshmallow_sqlalchemy.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime as dt
import decimal
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref, column_property
from sqlalchemy.dialects import postgresql
from marshmallo... |
rswinkle/C_Interpreter | run_valgrind_tests.py | #!/usr/bin/env python
import sys, string, glob, argparse, os
#import tempfile
from subprocess import *
from os.path import *
language_tests = glob.glob("../tests/*.txt")
preprocessor_tests = [
"../tests/preprocessor/preprocessor.txt",
"../tests/preprocessor/include.c"
]
def main():
parser = argparse.Argume... |
cathywu/flow | examples/rllib/velocity_bottleneck.py | """Bottleneck example.
Bottleneck in which the actions are specifying a desired velocity
in a segment of space
"""
import json
import ray
try:
from ray.rllib.agents.agent import get_agent_class
except ImportError:
from ray.rllib.agents.registry import get_agent_class
from ray.tune import run_experiments
from ... |
macbre/index-digest | indexdigest/linters/linter_0020_filesort_temporary_table.py | """
This linter checks for SELECT queries whether they trigger filesort or temporary file
"""
from collections import OrderedDict
from indexdigest.utils import explain_queries, LinterEntry, shorten_query
def filter_explain_extra(database, queries, check):
"""
Parse "Extra" column from EXPLAIN query results, ... |
gengo/jirasurvivor | src/survivor/reporting.py | """
Reporting helpers
These functions take some date within a reporting period and return the start
and end dates of that period.
"""
from collections import namedtuple
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from dateutil import relativedelta as days
from survivor i... |
UMComp4140ATeam/Raymond | src/dimension_modulus_reduction.py | #!/bin/python
# -*- coding: utf-8 -*-
import ciphertext
import math
import numpy
class DimensionModulusReduction(object):
def __init__(self, short_dimension, long_dimension, short_modulus, long_modulus):
self.__short_dimension = short_dimension
self.__long_dimension = long_dimension
self._... |
losonczylab/Zaremba_NatNeurosci_2017 | scripts/Fig2_place_cell_intro.py | """Figure 2 - Place cell intro"""
FIG_FORMAT = 'svg'
import matplotlib as mpl
if FIG_FORMAT == 'svg':
mpl.use('agg')
elif FIG_FORMAT == 'pdf':
mpl.use('pdf')
elif FIG_FORMAT == 'interactive':
mpl.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import os
import seaborn.apionly as sns
impor... |
orionmelt/sherlock | reddit_user.py | # -*- coding: utf-8 -*-
import csv
import datetime
import re
import json
import time
import sys
import calendar
from collections import Counter
from itertools import groupby
from urlparse import urlparse
import requests
import pytz
from subreddits import subreddits_dict, ignore_text_subs, default_subs
from text_pars... |
peri-source/peri | peri/viz/plots.py | # monkey-batch the matplotlibrc for peri:
from peri.viz import base
from builtins import range
import matplotlib as mpl
import matplotlib.pylab as pl
from matplotlib import ticker
from matplotlib.gridspec import GridSpec
from matplotlib.offsetbox import AnchoredText
from mpl_toolkits.axes_grid1.inset_locator import ... |
matslindh/codingchallenges | knowit2016/knowit06.py | import sys
values = {}
def get_value(x, y):
if y in values and x in values[y]:
return values[y][x]
return x + y
def set_value(x, y, val):
if y not in values:
values[y] = {}
values[y][x] = val
def get_next(x, y):
current = get_value(x, y)
possible = [
(x - 2, y -... |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/neighbors/tests/test_neighbors.py | from itertools import product
import numpy as np
from scipy.sparse import (bsr_matrix, coo_matrix, csc_matrix, csr_matrix,
dok_matrix, lil_matrix)
from sklearn import metrics
from sklearn import neighbors, datasets
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.model_sel... |
kmillet/crabpytest | crabpy/tests/test_wsa.py | # -*- coding: utf-8 -*-
try:
import unittest2 as unittest
except ImportError: # pragma NO COVER
import unittest # noqa
from suds.sax.element import Element
from ..wsa import wsa
class ElementTests(unittest.TestCase):
def testAction(self):
from crabpy.wsa import Action
a = Action('htt... |
bicepjai/Deep-Survey-Text-Classification | data_prep/utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import os
import re
import numpy as np
import pandas as pd
#===========================================================================
# Custom Tokenizer
# donot forget... |
geoscixyz/em_examples | em_examples/TDEMDipolarfields.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
from scipy.special import erfc, erf
from SimPEG import Utils
# TODO:
# r = lambda dx, dy, dz: np.sqrt( ... |
jhanley634/testing-tools | problem/numeric/mandelbrot/cython_d/setup.py |
# Copyright 2020 John Hanley.
#
# 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, distribut... |
nmarley/dash | test/functional/llmq-dkgerrors.py | #!/usr/bin/env python3
# Copyright (c) 2015-2020 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import DashTestFramework
from test_framework.util import *
'''
llmq-dkge... |
iburadempa/versioned_dict | tests/test_versioned_dict.py | # -*- coding: utf-8 -*-
# Copyright (C) 2015 ibu@radempa.de
#
# 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,... |
gboone/wedding.harmsboone.org | rsvp/migrations/0005_auto__add_field_hotel_total_guest_count__add_field_room_room_type.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Hotel.total_guest_count'
db.add_column(u'rsvp_hotel', 'total_guest_count',
... |
mrc75/django-service-status | service_status/checks.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
from collections import namedtuple
from django.apps import apps
from django.utils.encoding import python_2_unicode_compatible
from django.utils.module_loading import import_string
from service_st... |
UrbanCCD-UChicago/plenario | plenario/api/shape.py | import json
from collections import OrderedDict
from flask import make_response, request
from sqlalchemy import func
from sqlalchemy.exc import NoSuchTableError
from plenario.api.common import crossdomain, extract_first_geometry_fragment, make_fragment_str
from plenario.api.condition_builder import parse_tree
from pl... |
HuberTRoy/MusicPlayer | MusicPlayer/features/configNativeFeatures.py | __author__ = 'cyrbuzz'
import os
import glob
import pickle
import os.path
try:
import eyed3
except ImportError:
print('eyed3没有成功加载或安装,请不要使用本地音乐功能!')
from base import QFileDialog, QObject, QTableWidgetItem, checkFolder
from addition import itv2time
def getAllFolder(topFolder):
result = []
def findF... |
dantezhu/yunbk | examples/auto_bk_demo.py | # -*- coding: utf-8 -*-
import datetime
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_MISSED
from yunbk.yunbk import YunBK
from yunbk.backend.local import LocalBackend
logger = logging.getLogger('main')
logger.addHandler(logging... |
sveetch/autobreadcrumbs | project_test/tests/test_002_registry.py | import pytest
from autobreadcrumbs.registry import AlreadyRegistered, NotRegistered, BreadcrumbSite
def test_registry_empty():
"""Initial empty registry"""
registry = BreadcrumbSite()
assert registry.get_registry() == {}
def test_registry_initial():
"""Registry initially filled"""
registry = B... |
PyCQA/isort | isort/output.py | import copy
import itertools
from functools import partial
from typing import Any, Iterable, List, Optional, Set, Tuple, Type
from isort.format import format_simplified
from . import parse, sorting, wrap
from .comments import add_to_line as with_comments
from .identify import STATEMENT_DECLARATIONS
from .settings imp... |
guangtunbenzhu/BGT-Cosmology | Examples/LRG-MgII/tabulate_pk_2h.py |
import time
import numpy as np
import halomodel as hm
CosPar = {'Omega_M':0.3, 'Omega_L':0.7, 'Omega_b':0.045, 'Omega_nu':1e-5, 'n_degen_nu':3., 'h':0.7, 'sigma_8':0.8, 'ns':0.96}
z = 0.52
k_min = 1E-6
k_max = 1E4
dlogk = 1.E-2
kk = np.exp(np.arange(np.log(k_min)-2.*dlogk,np.log(k_max)+2.*dlogk,dlogk))
time0=time.t... |
crs4/hl7apy | hl7apy/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018, CRS4
#
# 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... |
iwob/evoplotter | app/gecco19_regr/gecco19_processor_exp1.py | import os
import shutil
from evoplotter import utils
from evoplotter import plotter
from evoplotter import printer
from evoplotter import reporting
from evoplotter.dims import *
from gecco19_utils import *
def simplify_benchmark_name(name):
"""Shortens or modifies the path of the benchmark in order to make the ta... |
harinisuresh/yelp-district-clustering | LDAWithGensim.py | """For Training the LDA model"""
import logging
import gensim
from gensim.corpora import BleiCorpus
from gensim import corpora
from DataImporter import get_vegas_reviews
import re
from sklearn.feature_extraction import text as sktext
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=loggin... |
cdent/wsgi-intercept | wsgi_intercept/tests/test_response_headers.py | """Test response header validations.
Response headers are supposed to be bytestrings and some servers,
notably will experience an error if they are given headers with
the wrong form. Since wsgi-intercept is standing in as a server,
it should behave like one on this front. At the moment it does
not. There are tests for... |
rit-sailing/website | blog/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-18 02:14
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('main', '... |
laginha/django-user-roles | src/userroles/south_migrations/0001_initial.py | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserRole'
db.create_table('userroles_userrole', (
('id', self.gf('django.db.mo... |
davebshow/gremlinclient | tests/test_aiohttp.py | import asyncio
import uuid
import unittest
import aiohttp
from gremlinclient import Stream
from gremlinclient.aiohttp_client import (
GraphDatabase, Pool, Response, submit, create_connection, RemoteConnection)
from gremlin_python import PythonGraphTraversalSource, GroovyTranslator
class RemoteConnectionTest(un... |
plotly/plotly.py | packages/python/plotly/plotly/validators/sankey/node/_hoverlabel.py | import _plotly_utils.basevalidators
class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="hoverlabel", parent_name="sankey.node", **kwargs):
super(HoverlabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_n... |
duguyue100/tcor | tcor/group.py | """Task Group.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
import json
class TaskGroup(object):
"""Task Group."""
def __init__(self, task_group_dict=None, task_group_json=None):
"""Initialize TaskGroup.
Parameters
----------
task_group_dict : dict
The ta... |
Zephyrrus/ubb | YEAR 3/SEM 2/DP/Lab2/Token.py | class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
"""String representation of the class instance.
Examples:
Token(INTEGER, 3)
Token(PLUS, '+')
Token(MUL, '*')
"""
retur... |
lapisdecor/bzoinq | tests/test_bzoinq.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_bzoinq
----------------------------------
Tests for `bzoinq` module.
"""
import pytest
from bzoinq import bzoinq
# @pytest.fixture
# def response():
# """Sample pytest fixture.
# See more at: http://doc.pytest.org/en/latest/fixture.html
# """
# ... |
chrisjdavie/maps_base | getting_london_postcodes/london_postcode_shapes/generate_shapefile.py | '''
This takes all the postcodes from the UK and extracts the ones that
are in london into a new folder
Created on 28 Oct 2014
@author: chris
'''
def main():
source_shp_fname = '/home/chris/Projects/maps_base/drawing_a_map/postcode_shapefiles/Distribution/Districts.shp'
sink_shp_fname = '/home/chris/Projects... |
calebsmith/sebastian | sebastian/lilypond/interp.py | from sebastian import logger
from sebastian.core import OSequence, Point, OFFSET_64, MIDI_PITCH, DURATION_64
import re
MIDI_NOTE_VALUES = {
"c": 0,
"d": 2,
"e": 4,
"f": 5,
"g": 7,
"a": 9,
"b": 11,
}
token_pattern = re.compile(r"""^\s* # INITIAL WHITESPACE
(
( ... |
gwu-libraries/sfm-weibo-harvester | weibo_exporter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sfmutils.exporter import BaseExporter, BaseTable
from weibo_warc_iter import WeiboWarcIter
import logging
import re
from dateutil.parser import parse as date_parse
log = logging.getLogger(__name__)
QUEUE = "weibo_exporter"
SEARCH_ROUTING_KEY = "export.start.weibo.we... |
adiyengar/Spirit | spirit/user/utils/email.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from smtplib import SMTPException
import logging
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from django.core.mail import send_mail
fr... |
drivet/flask-git | test_flask_git.py | import unittest
from flask_git import Git
from flask import Flask
import os
from repoutils import TempRepo
import shutil
import tempfile
class TestFlaskGitInit(unittest.TestCase):
"""Flask git extension - init"""
def setUp(self):
self.root_dir = tempfile.mkdtemp()
self.app = Flask(__name__)
... |
OpenDataPolicingNC/Traffic-Stops | traffic_stops/celery.py | from __future__ import absolute_import
import os
from celery import Celery
from . import load_env
load_env.load_env()
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'traffic_stops.settings')
from django.conf import settings # noqa
app = Celery('... |
mainulhossain/phenoproc | app/biowl/dsl/interpreter.py | import ast
import logging
from .func_resolver import Library
from ..tasks import TaskManager
from .context import Context
from .provenance import BioProv
logging.basicConfig(level=logging.DEBUG)
class Interpreter:
'''
The interpreter for PhenoWL DSL
'''
def __init__(self):
self.context = Cont... |
pipermerriam/flex | tests/loading/definition/responses/headers/single/test_schema_validation.py | import pytest
from flex.exceptions import (
ValidationError,
)
from flex.loading.definitions.responses.single.headers.single import (
single_header_validator,
)
def test_schema_is_not_required(msg_assertions):
try:
single_header_validator({})
except ValidationError as err:
errors = er... |
rtluckie/seria | tests/test_seria.py | from seria import compat
import pytest
import os
test_resources = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources')
from seria.compat import StringIO
import seria
from seria.serializers import get_formats, Serializer
from seria.providers import XML, YAML, JSON
class TestSeriaFuncs(object):
... |
mmmatthew/floodx_data_preprocessing | process_csv.py | # This script manages the pre-processing of floodX data to make it easily readable, by humans and machines
#
# Steps:
# - read settings
# - read sensor list
# - for each sensor, check if output file was already generated
# - only reprocess the data if the overwrite setting is set to True
# - for reprocessing a sen... |
sidnarayanan/BAdNet | train/gen/freeze/models/particles/v4_freeze_trunc7_limit100/trainer.py | #!/usr/bin/env python2.7
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--nepoch',type=int,default=80)
parser.add_argument('--version',type=str,default='4_freeze')
parser.add_argument('--trunc',type=int,default=7)
parser.add_argument('--limit',type=int,default=100)
parser.add_argume... |
anthonyalmarza/neji | setup.py | from neji import __version__
import errno
import os
import sys
from setuptools import setup, find_packages
def file_name(rel_path):
dir_path = os.path.dirname(__file__)
return os.path.join(dir_path, rel_path)
def read(rel_path):
with open(file_name(rel_path)) as f:
return f.read()
def readline... |
WBradbeer/port-routing | tests/tests.py | import os
import unittest
import pandas as pd
import lp_helpers as lp
import opt_helpers as oh
FILE_PATH = os.path.abspath(os.path.dirname(__file__))
class OptTestCase(unittest.TestCase):
def setUp(self):
case_path = "/../data/test_cases/tc1/"
self.c_sent = pd.read_csv(FILE_PATH + case_path ... |
mohrtw/algorithms | algorithms/tests/test_stack.py | import unittest
from unittest import TestCase
from algorithms.dataStructures.stack import Stack
class stackTest(TestCase):
def setUp(self):
self.s = Stack()
def test_add_item_to_stack(self):
item = 1
self.s.push(item)
self.assertEqual(item, self.s.items[0])
def test_add... |
ThePolyscope/DeepView | deepview/qtComponents/tpqtreewidget.py | import logging
import os
from PyQt4 import QtGui, QtCore
class tpQTreeWidget(QtGui.QTreeWidget):
logger = logging.getLogger()
#http://stackoverflow.com/questions/14480835/placeholder-for-a-custom-widget
def __init__(self, parent = None):
super(tpQTreeWidget, self).__init__(parent)
self.in... |
rwl/PyCIM | CIM15/IEC61970/Informative/InfGMLSupport/Map.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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... |
levilucio/SyVOLT | UMLRT2Kiltera_MM/Properties/from_thesis/HPP2_IsolatedLHS.py | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HPP2_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HPP2_IsolatedLHS.
"""
# Flag this instance as compile... |
istrategylabs/django-trix | setup.py | from setuptools import setup
long_description = open('README.rst').read()
setup(
name="django-trix",
version='0.3.1',
packages=["trix"],
include_package_data=True,
description="Trix rich text editor widget for Django",
url="https://github.com/istrategylabs/django-trix",
author="Jeremy Carb... |
MaterialsDiscovery/PyChemia | pychemia/code/codes.py | from abc import ABCMeta, abstractmethod
import os
import subprocess
import collections
import psutil
import shlex
from pychemia import pcm_log
class CodeRun:
__metaclass__ = ABCMeta
def __init__(self, executable, workdir='.', use_mpi=False):
"""
CodeRun is the superclass defining the operation... |
thomasgurry/amplicon_sequencing_pipeline | scripts/raw2otu.py | """
OVERVIEW:
Script to convert raw 16S sequencing data into OTU tables. Acts on a directory containing a summary file and the raw data.
Outputs a directory with processing results.
"""
from __future__ import print_function
from optparse import OptionParser
import numpy as np
import os, sys
import os.path
import ... |
mozillazg/python-pinyin | pypinyin/standard.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
处理汉语拼音方案中的一些特殊情况
汉语拼音方案:
* https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3%E6%96%B9%E6%A1%88
* http://www.moe.edu.cn/s78/A19/yxs_left/moe_810/s230/195802/t19580201_186000.html
""" # noqa
from __future__ import unicode_literals
... |
duydao/Text-Pastry | text_pastry.py | import sublime
import sublime_plugin
import re
import operator
import datetime
import time
import uuid
import subprocess
import tempfile
import os
import json
import sys
import hashlib
import shlex
import unittest
import itertools
from os.path import expanduser, normpath, join, isfile
from decimal import *
SETTINGS_F... |
dkdeconti/PAINS-train | training_methods/classifier/heatmap.py | __author__ = 'ddeconti'
import FileHandler
import pandas
import random
import sys
from bokeh.palettes import Blues9
from bokeh.charts import HeatMap, output_file, show
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit.Chem import AllChem, DataStructs, SDMolSupplier, Fingerprints
def randomly_pick_from... |
KartikKannapur/Programming_Challenges | Project-Euler-Solutions/036.py | #Problem 36:
#The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
#Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
#(Please note that the palindromic number, in either base, may not include leading zeros.)
def isPalin(num):
if(num == int(st... |
ianastewart/cwltc-admin | venv/Lib/site-packages/waitress/channel.py | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... |
HurtowniaPixeli/pixelcms-server | cms/emails/models.py | import os
from smtplib import SMTPException
import logging
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import EmailMultiAlternatives, get_connection
from django.conf import settings
from django.utils import timezone
from django... |
euri10/populus | populus/plugin.py | import pytest
from populus.migrations.migration import (
get_migration_classes_for_execution,
)
from populus.project import Project
CACHE_KEY_MTIME = "populus/project/compiled_contracts_mtime"
CACHE_KEY_CONTRACTS = "populus/project/compiled_contracts"
@pytest.fixture(scope="session")
def project(request):
#... |
IECS/MansOS | tools/seal/components/avr.py | #
# Copyright (c) 2012 Atis Elsts
#
# 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 following disclaimer.
#... |
devsenexx/gtxamqp | gtxamqp/protocol.py | import random
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, Deferred
from txamqp.content import Content
from txamqp.protocol import AMQClient
from gtxamqp.consumer import Consumer
class AmqpProtocol(AMQClient):
"""
The protocol is created and destroyed each time a ... |
creative-workflow/pi-setup | services/lan/__init__.py | from piservices import PiService
import re
class LanService(PiService):
name = "lan"
managed_service = False
commands = ['start', 'stop', 'restart', 'interface']
def stop(self):
"""shout down the pi"""
def restart(self):
"""reboot the pi"""
def info(self, extended=False):
"... |
lizlee0225/dbms | Referrence/sample_conn_sql.py | import pymysql as pm
import sys
### the script needs to be run with berkeley's wifi. If at home, please use VPN
### set mysql server
Mysql_host = '128.32.78.26'
Mysql_username = 'xuancheng_fan'
Mysql_password = 't3BVxkAt'
Mysql_db = 'xuancheng_fan'
### connect to server
con = pm.connect(Mysql_host, Mysql_username, M... |
Bjwebb/detecting-clouds | test.py | from utils import get_sidereal_time
from process import open_fits, flatten_max, DataProcessor
import dateutil.parser
import os, shutil
dp = DataProcessor()
dp.outdir = 'test/out'
dp.verbose = 1
#date_obs = '2011-05-25T06:00:10'
date_obs = '2012-02-29T10:37:12'
name = date_obs + '.fits'
path = os.path.join('sym', nam... |
mistwave/leetcode | Python3/no51_N-Queens.py | class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
sample, result = [], []
self.validposition(n, 0, sample, result)
return [] if result == [] else self.printresult(result)
# return result
def validpos... |
HKuz/Test_Code | Problems/stringPerms.py | #!/usr/local/bin/python3
import math
def main():
# Test suite for strPermutations
print("=====Test Suite - Find Permutations of String=====")
print("(Assumes all characters in the string are unique)")
testStrings = ["", "a", "ab", "abc", "abcd"]
for string in testStrings:
result = strPerm... |
riggs/construct | construct/lib/py3compat.py | """
Some Python 2 & 3 compatibility code.
"""
import sys
PY = sys.version_info[:2]
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
PY27 = sys.version_info[:2] == (2,7)
PY32 = sys.version_info[:2] == (3,2)
PY33 = sys.version_info[:2] == (3,3)
PY34 = sys.version_info[:2] == (3,4)
PY35 = sys.version_info[... |
pystockhub/book | ch19/day05/01.py | import sys
from PyQt5.QtWidgets import *
import Kiwoom
MARKET_KOSPI = 0
MARKET_KOSDAQ = 10
class PyMon:
def __init__(self):
self.kiwoom = Kiwoom.Kiwoom()
self.kiwoom.comm_connect()
self.get_code_list()
def get_code_list(self):
self.kospi_codes = self.kiwoom.get_code_list_by... |
CorverDevelopment/Pandora | tests/test_database.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from os import path
from pandora import Manager
from pandora import Model
import pandora.database
from pytest import raises
from tempfile import mkdtemp
import peewee as p
from pandora.compat import StringIO
class TestDatabase(o... |
avasilevich/spolks | mpi/mpi_group.py | import numpy as np
import sys
from mpi4py import MPI
MATRIX_DIM = 1000
def validate(first, second):
import filecmp
return filecmp.cmp(first, second)
def convert(size, shape):
import os
for i in range(0, size):
data = np.fromfile('mpi/{}_1mpi2.bin'.format(i), dtype=np.int)
data = d... |
blaa/WaveSync | libwavesync/chunk_player.py | import asyncio
import random
from libwavesync import (
time_machine,
AudioOutput
)
class ChunkPlayer:
"Play received audio and keep sync"
def __init__(self, chunk_queue, stats, tolerance_ms,
buffer_size, device_index):
# Our data source
self.chunk_queue = chunk_queue
... |
Azure/azure-sdk-for-python | sdk/keyvault/azure-mgmt-keyvault/azure/mgmt/keyvault/v2021_06_01_preview/operations/_keys_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
Phosphenius/battle-snakes | src/mapedit.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Map editor using a pygame window embedded into a tkinter frame
"""
import tkinter as tk
import tkinter.filedialog as filedia
import tkinter.messagebox
import os
from collections import deque
from copy import copy
import pygame
from constants import BLACK, ORANGE, GREEN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.