repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
jskopek/editor | editor/utils.py | from collections import Counter
from dateutil import parser
from datetime import date
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import simplejson
import dropbox
import os
import re
def count_question_answers(client, question, num_days=None):
counts = Counter()
... |
brownan/Logging-Goodies | logginggoodies/__init__.py | import logging
class ExtraRecordsFormatter(logging.Formatter):
"""A Formatter that adds a few items to the record:
filenameandlineno
a combination of filename:linenumber so they can be justified together
shortfuncname
the function name truncated and left justified to 15 characters. Yo... |
torpedro/SimpleJsonDB | server/jsondb/tablemanager.py | import os
from logger import Logger
from table import Table
from results import ErrorResult
class TableManager(object):
"""TableManager"""
def __init__(self, data_path):
super(TableManager, self).__init__()
Logger.log("Initializing database in '%s'" % (data_path))
self._path = data_path
self._tables = {}
... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/models/__init__.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 ... |
greencoder/shipwrecksproject | shipwrecks/settings.py | """
Django settings for shipwrecks project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... |
LucidAi/nlcd | husky/parsers.py | # coding: utf-8
# Author: Vova Zaytsev <zaytsev@usc.edu> (2014)
import lxml.html
from lxml.html.clean import Cleaner
class ArticleParser(object):
"""
TODO(zaytsev@usc.edu):
"""
SELECTOR = "descendant-or-self::*"
SELECTOR_PATTERN = "%s[re:test(@%s, \"%s\", \"i\")]"
NAMESPACE = {"re": "http://... |
Unthinkingbit/bitcointools | deserialize.py | #
#
#
from BCDataStream import *
from enumeration import Enumeration
from base58 import public_key_to_bc_address, hash_160_to_bc_address
import socket
import time
from util import short_hex, long_hex
def parse_CAddress(vds):
d = {}
d['nVersion'] = vds.read_int32()
d['nTime'] = vds.read_uint32()
d['nServices']... |
thiderman/network-kitten | test/test_server.py | import signal
import pytest
import gevent
import zmq
from mock import MagicMock, patch, call, mock_open
from test.utils import builtin
from kitten import server
from kitten.server import KittenServer
from kitten.server import setup_parser
from kitten.server import execute_parser
from kitten.request import KittenReque... |
Lodour/Weibo-Album-Crawler | weibo/spiders/video.py | import os.path
from urllib.parse import urlparse
import scrapy
from weibo import api, utils
from weibo import configs
from weibo.items import WeiboItem
class VideoSpider(scrapy.Spider):
name = 'video'
allowed_domains = ['weibo.com']
download_warnsize = 100 << 20 # 100 MB
download_timeout = 10 * 60 ... |
AravindK95/ee106b | project1/src/lab1/src/pd.py | #!/usr/bin/env python
import tf
import sys
import math
import numpy as np
import rospy
from tf2_msgs.msg import TFMessage
from std_msgs.msg import Int16, Bool, Float64
from geometry_msgs.msg import Transform, Vector3, Twist
# FOR CHANGING THE ORIENTATION OF THE ZUMY TO TAGS
# NOT IMPLEMENTED YET!!
# import exp_quat_fun... |
INCF/pybids | bids/layout/tests/test_writing.py | """Tests related to file-writing functionality."""
import shutil
import os
from os.path import join, exists, islink, dirname
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from bids.layout.writing import build_path, _PATTERN_FIND
from bids.tests import get_test_data_path
f... |
imanolarrieta/angrybirds | RL/HW1/Python/PCRL.py | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 21:55:46 2015
@author: Imanol
This code implements PSRL for the chain problem.
1-2-3-4-5-...-H
Where there is a positive reward only at the last state.
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 10:53:57 2015
@author: Imanol
"""
import numpy as np
import ... |
ashish-joglekar/7-Segment-Display-Digitizer | webcam3.py | #MIT License
#Copyright (c) 2016 Ashish Joglekar, RBCCPS, IISc <https://github.com/ashish-joglekar>
#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... |
oshbec/linear-algebra | tests/vector_test.py | from pytest import raises
from la.vector import Vector
def test_throwsValueErrorIfCoordinatesEmpty():
with raises(ValueError): Vector([])
def test_throwsTypeErrorIfCoordinatesNotIterable():
with raises(TypeError): Vector(5)
def test_castsToString():
assert 'Vector: (1, 2, 3)' == Vector([1, 2, 3]).__str__... |
pebble/pebble-tool | pebble_tool/commands/sdk/create.py | from __future__ import absolute_import, print_function
import errno
import json
import os
import re
import shutil
from string import Template
from uuid import uuid4
from . import SDKCommand
from pebble_tool.sdk import SDK_VERSION, sdk_version
from pebble_tool.exceptions import ToolError
from pebble_tool.util.analyti... |
MadWookie/Survivor-Bot | cogs/exp.py | from random import randint
import time
import asyncpg
import asyncio
from discord.ext import commands
import discord
from cogs.menus import Menus, ARROWS, CANCEL
from utils import checks
exp_cooldown = 60
exp_min_amount = 15
exp_max_amount = 25
# exp_min_amount = 30 #Double EXP
# exp_max_amount = 50 #Double EXP
de... |
owenwater/french-verb-test | src/result_frame.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import Tkinter
import tkFileDialog
from exam import Exam
from test_frame import TitleFrame
class ButtonFrame(Tkinter.Frame):
def __init__(self, master, is_first, is_last):
Tkinter.Frame.__init__(self, master)
self.is_first = is_first
self.is_last... |
gautes/TrollCoinCore | test/functional/txn_doublespend.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet accounts properly when there is a double-spend conflict."""
from test_framework.test_f... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_09_01/operations/virtual_network_gateway_connections_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 ... |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/constants.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/packet_capture_parameters_py3.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 ... |
keurfonluu/StochOPy | test/helpers.py | import numpy as np
import stochopy
def rosenbrock():
fun = stochopy.factory.rosenbrock
bounds = [[-5.12, 5.12], [-5.12, 5.12]]
return fun, bounds
def optimize(method, options, xref):
options.update({"maxiter": 128, "popsize": 8, "seed": 42, "return_all": True})
fun, bounds = rosenbrock()
i... |
Ayrx/pyDropSecure | src/configure.py | from getpass import getpass
import os
import dropbox
import sqlite3
from pbkdf2 import PBKDF2
import aes
from settings import APP_PATH, APP_KEY, APP_SECRET, CONFIG_PATH, CONFIG_DB
__author__ = 'Terry Chia'
def new_configuration():
if not os.path.exists(APP_PATH):
os.makedirs(APP_PATH)
flow = dropbo... |
clearcare/railgun | railgun/engines/elasticsearch.py | from __future__ import absolute_import
import certifi
from elasticsearch.client import Elasticsearch
from elasticsearch.exceptions import TransportError
from railgun.exceptions import EngineConfigurationError
from .storage_engine import StorageEngine
class ElasticsearchEngine(StorageEngine):
required_fields = (... |
Medvezhopok/poker-player-pythonpokerteam | handtype/hand.py | from card import Card
from handtype.flush import Flush
from handtype.four_cards import FourCard
from handtype.full_house import FullHouse
from handtype.high_card import HihgCard
from handtype.pair import Pair
from handtype.straight import Straight
from handtype.straight_flush import StraightFlush
from handtype.three_ca... |
MEhlinger/rpi_pushbutton_games | pet_cemetary/food.py | # Food Class
class Food:
def __init__(self, x, y):
self.location = (x, y)
self.eaten = False
def getX(self):
return self.location[0]
def getY(self):
return self.location[1]
def setX(self, newX):
self.location[0] = newX
def setY(self, newY):
self.location[1] = newY
def isEaten(self):
return se... |
genavarov/ladacoin | contrib/bitrpc/bitrpc.py | from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8832")
e... |
phfaist/pylatexenc | pylatexenc/macrospec/_spechelpers.py | # -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2019 Philippe Faist
#
# 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 t... |
davidsoncolin/IMS | UI/QGLViewer.py | #!/usr/bin/env python
from math import sin, cos, tan
from PySide.QtOpenGL import QGLFormat
import numpy as np
from time import time
from PySide import QtCore, QtGui, QtOpenGL
from OpenGL import GL, GLU, GLUT
import QApp
from UI import GLSkeleton
from UI import DRAWOPT_DEFAULT, DRAWOPT_IMAGE, DRAWOPT_HUD, GLGrid, GLM... |
rajeevs1992/pyhealthvault | src/healthvaultlib/methods/getauthorizedpeople.py | from lxml import etree
from healthvaultlib.methods.method import Method
from healthvaultlib.utils.xmlutils import XmlUtils
from healthvaultlib.objects.personinfo import PersonInfo
from healthvaultlib.methods.methodbase import RequestBase, ResponseBase
class GetAuthorizedPeopleRequest(RequestBase):
def __init... |
dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/samples/printing/printing.py | import wx
from six import print_
import os
FONTSIZE = 10
class TextDocPrintout(wx.Printout):
"""
A printout class that is able to print simple text documents.
Does not handle page numbers or titles, and it assumes that no
lines are longer than what will fit within the page width. Those
features a... |
DavidGrey/game-theory_gunner | shotgun/ascii_art.py | """Ascii art imported by the main file"""
gun_art = "/-\________________\n | |\n \-----------------\n / /) /\n / /----\n / /\n/____/ "
shield_art = "|`-._/\_.-`|\n| || |\n|___o()o___|\n|__((<>))__|\n\ o\/o /\n \ || /\n \ || /\n '.||.'\n ''"
reload_art = """ _____... |
anugrah-saxena/pycroscopy | pycroscopy/analysis/model.py | """
Created on 7/17/16 10:08 AM
@author: Numan Laanait, Suhas Somnath, Chris Smith
"""
from __future__ import division, print_function, absolute_import, unicode_literals
from warnings import warn
import numpy as np
import psutil
import scipy
from .guess_methods import GuessMethods
from .fit_methods import Fit_Methods... |
ruffoa/Qhacks2016 | Sigma-Securities/src/sentiment/categories.py |
# Load the AlchemyAPI module code.
import AlchemyAPI
# Create an AlchemyAPI object.
alchemyObj = AlchemyAPI.AlchemyAPI()
# Load the API key from disk.
alchemyObj.loadAPIKey("api_key.txt");
# Categorize a web URL.
result = alchemyObj.URLGetCategory("http://www.techcrunch.com/");
print result
# Categorize some ... |
vandorjw/django-assessment | demo/urls.py | """Urls for the demo of django-assessment"""
from django.conf import settings
from django.conf.urls import url
from django.conf.urls import include
from django.views.static import serve
from django.views.defaults import bad_request
from django.views.defaults import server_error
from django.views.defaults import page_n... |
gdsfactory/gdsfactory | gdsfactory/geometry/functions.py | from typing import List, Optional, Union
import numpy as np
from numpy import cos, float64, ndarray, sin
from gdsfactory.coord2 import Coord2
RAD2DEG = 180.0 / np.pi
DEG2RAD = 1 / RAD2DEG
def sign_shape(pts: ndarray) -> float64:
pts2 = np.roll(pts, 1, axis=0)
dx = pts2[:, 0] - pts[:, 0]
y = pts2[:, 1] ... |
dhylands/Bioloid | bioloid/bus.py | """This module provides the bioloid.Bus abstract base class for
implementing bioloid busses.
"""
import logging
from bioloid import packet
from bioloid.dumpmem import dump_mem
class BusError(Exception):
"""Exception which is raised when non-successful status packet."""
def __init__(self, error_code, *args... |
jefftc/changlab | scripts/get_palette.py | #!/usr/bin/env python
def main():
import argparse
from genomicode import parallel
import arrayplot2
parser = argparse.ArgumentParser()
DEFAULT_COLOR_SCHEME = "brewer-rdylbu-div"
COLOR_SCHEMES = [x[0] for x in arrayplot2.SCHEME2FN]
assert DEFAULT_COLOR_SCHEME in COLOR_SCHEMES
#x = ar... |
shaoke/reserveamerica | reserve_america/spiders/campsite.py | # -*- coding: utf-8 -*-
import datetime
import re
from urllib.parse import urlparse, parse_qs
import logging
from scrapy.spiders import CrawlSpider
from scrapy.http import Request
from pydash import strings
from reserve_america.items import ParkItem, CampsiteItem, CampsiteDetailItem
from reserve_america.data_mapping ... |
gawel/irc3 | examples/async_command.py | # -*- coding: utf-8 -*-
from irc3.plugins.command import command
from irc3.compat import Queue
import irc3
@irc3.plugin
class AsyncCommands(object):
"""Async commands example. This is what it's look like on irc::
<gawel> !get
<gawel> !put item
<irc3> items added to queue
<irc3> it... |
bitmazk/django-privacy | privacy/tests/urls.py | """
This ``urls.py`` is only used when running the tests via ``runtests.py``.
As you know, every app must be hooked into yout main ``urls.py`` so that
you can actually reach the app's views (provided it has any views, of course).
"""
from django.conf.urls.defaults import include, patterns, url
from django.contrib impo... |
andregouws/mrMeshPy | matlabRoutines/pyMeshBuild.py | #!/usr/bin/python
# TODO - python path - assuming condo here
## HEALTH WARNING - BETA CODE IN DEVELOPMENT ##
'''
This standalone application will build a mesh from a nifti classification file.
To keep the procedure as similar as possible to the way mrMesh used to do this,
we will keep this as a standalon applicatio... |
nathants/py-util | util/cached.py | import os
import threading
import subprocess
import time
import hashlib
import inspect
import collections
import functools
import util.exceptions
import util.misc
import util.func
import json
_attr = '_cached_value'
_cache_root = os.environ.get('CACHED_ROOT', '/tmp')
def _disk_cache_path(fn):
try:
file_n... |
menify/sandbox | aql/aql/util_types/aql_list_types.py | #
# Copyright (c) 2011,2012 The developers of Aqualid project - http://aqualid.googlecode.com
#
# 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 limitati... |
plotly/python-api | packages/python/plotly/plotly/validators/scatterpolar/marker/_line.py | import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="line", parent_name="scatterpolar.marker", **kwargs):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
Delosari/dazer | bin/lib/cloudy_library/Cloudy_PlottingModels_v7.py | '''
Created on Apr 17, 2016
@author: vital
'''
from collections import OrderedDict
from numpy import log10 as nplog10, zeros, min, max, linspace, array, concatenate, isfinite, greater
from pandas import Series
from uncertainties.unumpy import uarray, n... |
tmm1/pygments.rb | vendor/pygments-main/pygments/lexers/pony.py | # -*- coding: utf-8 -*-
"""
pygments.lexers.pony
~~~~~~~~~~~~~~~~~~~~
Lexers for Pony and related languages.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups, words
from pygments.token im... |
ua-snap/downscale | snap_scripts/epscor_sc/symlink_pr_tas_epscor_sc.py | # symlink matts pr/tas data to the folder structure in the EPSCoR directory...
# cp -rs /Data/Base_Data/Climate/AK_CAN_2km/projected/AR5_CMIP5_models/rcp26/CCSM4/pr/ pr/
def run( x ):
return os.system( x )
if __name__ == '__main__':
import os, glob, subprocess, itertools
from pathos.mp_map import mp_map
output_p... |
balbinot/arghphot | arghphot/arghphot.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
## temp imports
from matplotlib import pyplot as p
from matplotlib import cm
import tempfile
import numpy as np
from astropy.io import fits, ascii
from astropy.coordinates import SkyCoord
from astropy import units as u
from astropy import wcs
import aplpy
from pyraf impo... |
butlerx/IntroToGit | randomnames.py | import random
import os
def generate_random_names(count):
first_names = ["Drew", "Mike", "Landon", "Jeremy", "Tyler", "Tom", "Avery",
"Sarah", "Clare", "Jennifer"]
last_names = ["Smith", "Jones", "Brighton", "Taylor"]
for filename in os.listdir(os.path.join(os.getcwd(), "names")):
... |
drogen120/GAN_MNIST | ops.py | import math
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from utils import *
try:
image_summary = tf.image_summary
scalar_summary = tf.scalar_summary
histogram_summary = tf.histogram_summary
merge_summary = tf.merge_summary
SummaryWriter = tf.train.SummaryWriter
ex... |
luckielordie/conan | conans/test/command/create_test.py | from conans import tools
from conans.test.utils.tools import TestClient
import unittest
import os
from parameterized.parameterized import parameterized
from conans.util.files import load
class CreateTest(unittest.TestCase):
def dependencies_order_matches_requires_test(self):
client = TestClient()
... |
dchaplinsky/garnahata.in.ua | garnahata_site/cms_pages/migrations/0002_auto_20150702_0240.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django import VERSION as DJANGO_VERSION
def reset_homepage(apps, schema_editor):
Site = apps.get_model('wagtailcore.Site')
Page = apps.get_model('wagtailcore.Page')
HomePage = apps.get_model('cms... |
ESA-VirES/eoxserver-magnetism | instance/instance/settings.py | #-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Stephan Krause <stephan.krause@eox.at>
# Stephan Meissl <stephan.meissl@eox.at>
#
#-------------------------------------------------------------------------------
# Copyrigh... |
all3fox/algos-py | src/sset/trie.py | class Node:
def __init__(self, top, val=None):
self.top = top
self.val = val
self.edges = {}
def __len__(self):
return len(self.edges)
def __bool__(self):
return self.val is not None or bool(len(self))
def __iter__(self):
return iter(self.edges)
... |
aidanknowles/TweetVibe | app/helper.py | from mongoengine import *
from app.models import *
from datetime import datetime, timedelta
def tweet_collection_size():
"""
:return: Number total number of documents in the database's Tweet collection
"""
return len(Tweet.objects())
def count_tweets(search_term, location=None):
"... |
akloster/blender-vraag | vraag/construct/__init__.py | import numpy as np
import math
import bpy
from vraag.utils import *
from .base import VraagConstruct, register_constructor
from .primitives import VraagObject
from .transform import *
from .boolean import *
from .turtle import *
from .mesh_builder import MeshBuilder, extrude2
class Material(VraagObject):
def __i... |
bittner/django-allauth | allauth/socialaccount/providers/microsoft/provider.py | from __future__ import unicode_literals
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class MicrosoftGraphAccount(ProviderAccount):
def to_str(self):
name = self.account.extra_data.get('displayName')
if... |
shixing/pyPBMT | py/mert/mert_framework.py | import configparser
from utils.weights import *
from .bleu import Bleu
from .line_search import search_line
from decode.reorder_lm_framework import decode_batch_config_weight
import logging
import cPickle
import os,sys
from datetime import datetime
from random import random
def main():
# python mert_framework mer... |
stiphyMT/plantcv | plantcv/plantcv/sobel_filter.py | # Sobel filtering
import cv2
import os
from plantcv.plantcv import print_image
from plantcv.plantcv import plot_image
from plantcv.plantcv import params
def sobel_filter(gray_img, dx, dy, ksize):
"""This is a filtering method used to identify and highlight gradient edges/features using the 1st derivative.
... |
universalyouth/picopico | picopico/utils/oauth/github.py | # -*- coding: utf-8 -*-
# PROJECT : picopico
# TIME : 17-4-11 下午2:46
# AUTHOR : youngershen <younger.x.shen@gmail.com>
from urllib.parse import urlencode, quote
from django.conf import settings
import requests
import logging
logger = logging.getLogger(__name__)
class Client:
API_END_POINT = 'https://api.gith... |
fabiansinz/labloid | manage.py | #!/usr/bin/env python
import os
# --- import environment variables from hidden file
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
# --- import extensions a... |
ActiveState/code | recipes/Python/578151_affinitypy/recipe-578151.py | """Allow a simple way to ensure execution is confined to one thread.
This module defines the Affinity data type that runs code on a single thread.
An instance of the class will execute functions only on the thread that made
the object in the first place. The class is useful in a GUI's main loop."""
__author__ = 'Step... |
kharidiron/willie_modules | russian_roulette.py | # coding=utf8
"""
russian_roulette.py - A Russian Roulette bot for Willie
Copyright 2015, Kharidiron [kharidiron@gmail.com]
"""
from __future__ import unicode_literals
from willie.module import commands, example
import random
def setup(bot):
bot.memory["rr_game"] = RussianRoulette(bot)
@commands("rr")
def manag... |
mjenrungrot/competitive_programming | UVa Online Judge/v100/10007.py | # =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 991.py
# Description: UVa Online Judge - 991
# =============================================================================
MAXN = 303
cat ... |
geoffrey-a-reed/minimal | docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# minimal documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 6 21:35:03 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... |
project-rig/nengo_spinnaker | nengo_spinnaker/builder/ensemble.py | import collections
import nengo
from nengo.builder import connection as connection_b
from nengo.builder import ensemble
from nengo.dists import Distribution
from nengo.exceptions import BuildError
from nengo.processes import Process
from nengo.utils.builder import full_transform
from nengo.utils import numpy as npext
i... |
mizuy/seqtool | seqtool/util/xmlwriter.py | from xml.sax.saxutils import quoteattr,escape
import io
__author__ = "MIZUGUCHi Yasuhiko"
__copyright__ = "Copyright (C) 2010 MIZUGUCHI Yasuhiko"
__license__ = "MIT"
__version__ = "1.0"
class XmlWriter(object):
def __init__(self, output, indent=True):
self._indent = indent
self._output = output
... |
samueljackson92/CSAlumni-client | tests/test_helpers.py | __author__ = "Samuel Jackson"
__date__ = "November 26, 2014"
__license__ = "MIT"
import os
import json
import responses
from csa_client.request_handler import RequestHandler
from csa_client.api import CsaAPI
from csa_client import constants
FIXTURES_FOLDER = "fixtures"
def load_fixture(file_name):
"""Load a tex... |
thejunglejane/datums | datums/migrations/versions/f24937651f71_add_altitude_reports_table.py | """Add altitude_reports table
Revision ID: f24937651f71
Revises: 457bbf802239
Create Date: 2016-01-25 23:07:52.202616
"""
# revision identifiers, used by Alembic.
revision = 'f24937651f71'
down_revision = '457bbf802239'
branch_labels = None
depends_on = None
from alembic import op
from sqlalchemy import Column, For... |
splitbrain/Watcher | watcher.py | #!/usr/bin/env python
# Copyright (c) 2010 Greggory Hernandez
# 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, mod... |
jeremiedecock/snippets | python/setuptools/example_without_dependency/setup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PyNurseryRhymesDemo
# The MIT License
#
# Copyright (c) 2010,2015 Jeremie DECOCK (http://www.jdhp.org)
#
# 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 ... |
sburnett/seattle | production_nat_new/src/nmpatch/seash.py | """
Author: Justin Cappos
Module: A shell for Seattle called seash (pronounced see-SHH). It's not meant
to be the perfect shell, but it should be good enough for v0.1
Start date: September 18th, 2008
This is an example experiment manager for Seattle. It allows a user to
locate vessels they control and ... |
xylsxyls/xueyelingshuang | src/ProcessClient/scripts/rebuild_lib_ProcessClient.py | #!python3
# -*- coding:utf-8 -*-
import os
import sys
import time
import ctypes
import shutil
import subprocess
IsPy3 = sys.version_info[0] >= 3
if IsPy3:
import winreg
else:
import codecs
import _winreg as winreg
BuildType = 'Release'
IsRebuild = True
Build = 'Rebuild'
Update = False
C... |
levilucio/SyVOLT | UMLRT2Kiltera_MM/MT_pre__hasArgs.py | """
__MT_pre__hasArgs.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: gehan
Modified: Sun Feb 15 10:22:14 2015
_________________________________________________________________________
"""
from ASGNode import *
from ATOM3Type impo... |
NewAcropolis/api | migrations/versions/0006.py | """empty message
Revision ID: 0006 add alternate_names speaker
Revises: 0005 Add speakers table
Create Date: 2018-02-28 23:11:00.863456
"""
# revision identifiers, used by Alembic.
revision = '0006 add alternate_names speaker'
down_revision = '0005 Add speakers table'
from alembic import op
import sqlalchemy as sa
... |
systocrat/psmtool | example-migrations/vegetables.py | from __future__ import print_function
from psmtool.autocommit import autocommit
PSM_NAME = 'vegetables'
PSM_VERSION = 0
def up(db, cursor):
cursor.execute('CREATE TYPE vegetable_rating AS ENUM(\'bad\', \'mediocre\', \'good\');')
cursor.execute('''CREATE TABLE IF NOT EXISTS vegetables (
name TEXT PRIM... |
jbahamon/dudo-bot | statemachine.py | import asyncio
import concurrent
import logging
import sys
from announcer import Announcer
from states import State
MIN_PLAYERS = 2
FINAL_GUESS_DOUBT = "doubt"
FINAL_GUESS_FIT = "fit"
class DudoStateMachine(Announcer):
def __init__(self, sender):
Announcer.__init__(self, sender)
self.logger = lo... |
danhuss/faker | faker/providers/job/ja_JP/__init__.py | from .. import Provider as BaseProvider
class Provider(BaseProvider):
"""
source: https://ja.wikipedia.org/wiki/%E8%81%B7%E6%A5%AD%E4%B8%80%E8%A6%A7
"""
jobs = [
'アイドル',
'アーティスト',
'アートディレクター',
'アナウンサー',
'アニメーター',
'医師',
'イラストレーター',
'医療事務員... |
ggjjl1/pyscript | generate_pass.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import urandom
from random import choice
char_set = {'small': 'abcdefghijklmnopqrstuvwxyz',
'nums': '0123456789',
'big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'special': '^!\$%&/()=?{[]}+~#-_.:,;<>|\\'
}
def generate_pas... |
genomeannotation/capn_primer | src/dependency_checker.py | #!/usr/bin/env python
import subprocess
import sys
def check_dependencies():
# check primer3_core
if primer3_core_is_installed():
print("...Yarr! primer3_core be installed.")
else:
print("Yarr! Why ye not install primer3_core, scurvy dog.")
sys.exit()
# check makeblastdb
i... |
PRByTheBackDoor/ElectionRunner | src/inputs/election_from_csv.py |
# The MIT License (MIT)
#
# Copyright (c) 2014 PRByTheBackDoor
#
# 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, ... |
gpatonay/popy | pycerberus/validators/email.py | # -*- coding: UTF-8 -*-
#
# The MIT License
#
# Copyright (c) 2010, 2012, 2013 Felix Schwarz <felix.schwarz@oss.schwarz.eu>
#
# 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 restric... |
MoeLove/qyweixin | setup.py | #!/usr/bin/env python
import os
import re
import sys
from codecs import open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'qyweixin',
]
requires = []
versio... |
Arthur2e5/arguman.org | web/premises/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from premises.constants import MAX_PREMISE_CONTENT_LENGTH
from premises.mixins import FormRenderer
from premises.models import Contention, Premise, Report
class ArgumentCreationForm(FormRenderer, forms.ModelForm):
... |
kbase/narrative | src/biokbase/narrative/exception_util.py | from requests.exceptions import HTTPError
from biokbase.execution_engine2.baseclient import ServerError as EEServerError
from biokbase.userandjobstate.baseclient import ServerError as UJSServerError
class JobIDException(ValueError):
"""
Raised when a job ID is not provided, invalid (e.g., None, ""),
not r... |
johnswanson/pypicloud | pypicloud/util.py | """ Utilities """
import posixpath
import logging
from distlib.locators import Locator, SimpleScrapingLocator
from distlib.util import split_filename
from six.moves.urllib.parse import urlparse # pylint: disable=F0401,E0611
LOG = logging.getLogger(__name__)
ALL_EXTENSIONS = Locator.source_extensions + Locator.binar... |
pre-commit/pre-commit | tests/languages/pygrep_test.py | from __future__ import annotations
import pytest
from pre_commit.languages import pygrep
@pytest.fixture
def some_files(tmpdir):
tmpdir.join('f1').write_binary(b'foo\nbar\n')
tmpdir.join('f2').write_binary(b'[INFO] hi\n')
tmpdir.join('f3').write_binary(b"with'quotes\n")
tmpdir.join('f4').write_binar... |
tatumdmortimer/popgen-stats | dadi_expansion.py | #!/usr/bin/env python
import argparse
import numpy
from numpy import array
import dadi
from datetime import datetime
def get_args():
# parse command line arguments
parser = argparse.ArgumentParser(description='Run dadi analysis')
parser.add_argument("sfs", help="SFS in dadi format",
... |
expressly/expressly-plugin-sdk-python3-core | expressly/tests/models/test_field_value.py | from unittest import TestCase
from expressly.models import FieldValue
from schematics.exceptions import ModelValidationError
class FieldValueTest(TestCase):
def setUp(self):
self.m = FieldValue().get_mock_object()
def test_required(self):
self.assertIsNotNone(self.m.field)
self.assert... |
chappers/sklearn-recipes | streaming/dpp_classifier_ogfs2.py | import sklearn
from sklearn.datasets import make_regression, make_classification
from sklearn.linear_model import SGDRegressor, SGDClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import euclidean_distances
import pandas as pd
import numpy as np
from scipy import stats
from sci... |
syscoin/syscoin | test/functional/rpc_getblockfilter.py | #!/usr/bin/env python3
# Copyright (c) 2018-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the getblockfilter RPC."""
from test_framework.test_framework import SyscoinTestFramework
from te... |
thomasnat1/DataScience2014CDC | googlehealth-tfidf.py | # 4/19/2014
# Charles O. Goddard
import feedparser
import google
import tfidf_search
rss_url = "http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=m&output=rss"
feed = feedparser.parse(rss_url)
for item in feed.entries:
print '-'*80
title, source = item.title.split(' - ')
searchstring = tfidf_s... |
jfalkner/Efficient-Django-QuerySet-Use | demo-optimized/example/utils.py | from django.utils.timezone import utc
from django_db_utils import pg_bulk_update
from example.models import Sample, SampleStatus
def now():
from datetime import datetime
return datetime.utcnow().replace(tzinfo=utc)
def make_fake_data(samples_to_make=100000, batch_threshold=100000, delete_existing=True, ma... |
BeeBubble/SnakeRace | Liao Xue Feng Py2 Edu/data type.py | # -*- coding: utf-8 -*
__author__ = 'shawn'
# 内部不转义
print '\\\n\\'
print r'\\\n\\'
# 换行
print '''
this
is
my
python
world
'''
# boolean
print 3 > 2
print 2 < 3 and 5 < 4
print not True
# pointer
a = 'abc'
b = a
a = "xyz"
print 'a=' + a, 'b=' + b
# 除法
print 10 / 3
print 10.0 / 3
|
lewissbaker/cake | src/cake/library/compilers/__init__.py | """Base Class and Utilities for C/C++ Compiler Tools.
@see: Cake Build System (http://sourceforge.net/projects/cake-build)
@copyright: Copyright (c) 2010 Lewis Baker, Stuart McMahon.
@license: Licensed under the MIT license.
"""
import sys
import weakref
import os
import os.path
import datetime
import tempfile
import... |
kradalby/sourceapi | models.py | # pyre-fixme[21]: Could not find `ext`.
from flask.ext.sqlalchemy import SQLAlchemy
# pyre-fixme[16]: Module `flask` has no attribute `ext`.
db = SQLAlchemy()
# pyre-fixme[11]: Annotation `Model` is not defined as a type.
class Query(db.Model):
id = db.Column(db.Integer, primary_key=True)
datetime = db.Colum... |
lisnb/leetcode | Remove Duplicates from Sorted List.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LiSnB
# @Date: 2014-10-23 21:33:47
# @Last Modified by: LiSnB
# @Last Modified time: 2014-10-23 21:37:03
# @Email: lisnb.h@gmail.com
"""
# @comment here:
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val =... |
dexterchiu/unchain | config/settings/production.py | # -*- coding: utf-8 -*-
"""
Production Configurations
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis for cache
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from... |
MarekSuchanek/repocribro | tests/test_commands.py | import datetime
import pytest
from sqlalchemy.exc import OperationalError
from repocribro.commands.assign_role import _assign_role
from repocribro.commands.check_config import _check_config
from repocribro.commands.db_create import _db_create
from repocribro.commands.repocheck import _repocheck
from repocribro.models ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.