repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
feilchenfeldt/enrichme | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
import sys, os
import enrichme
def publish():
"""Publish to PyPi"""
os.system("python setup.py bdist_wheel sdist upload"... |
lqez/hog | hog/hog.py | # -*- coding: utf-8 -*-
"""
hog
~~~
Sending multiple HTTP requests ON GREEN thread.
:copyright: (c) 2014-2019 by Park Hyunwoo.
:license: MIT, see LICENSE for more details.
"""
from six import itervalues, iteritems
from six.moves import xrange
import eventlet
eventlet.monkey_patch()
import click
import re
import r... |
maistrovas/My-Courses-Solutions | Coursera Algorithmic Thinking (Part 1)/Module 2/Project/BFS_project.py | '''
commant regarding project
Raw Score 100.00 / 100.00
'''
import test_graphs as test
from collections import deque
import random
#import poc_queue
def bfs_visited(ugraph, start_node):
'''
Input:
ugraph - undirected graph represented as adjacent list
start_node - initial node. (in this case integer... |
shad7/trakt.py | tests/test_trending.py | from tests.core.helpers import read
from trakt import Trakt
import responses
@responses.activate
def test_movie():
responses.add(
responses.GET, 'http://mock/movies/trending',
body=read('fixtures/movies/trending.json'), status=200,
content_type='application/json'
)
Trakt.base_url... |
colobas/gerador-horarios | tt_generator.py | class TimetableGenerator:
def __init__(self):
self.generated = []
self.generated2 = []
self.total_combinations = 0
def store_timetable(self, tt):
self.total_combinations += 1
tt.heuristic = tt.total_time()
tt.heuristic2 = tt.total_time2()
if len(self.generated) <= 99:
self.generated.append(tt)
... |
mjenrungrot/competitive_programming | UVa Online Judge/v121/12143.py | # =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12143.py
# Description: UVa Online Judge - 12143
# =============================================================================
import math
... |
chenke91/ckPermission | app/admin/admin/roles.py | #coding: utf-8
from flask import jsonify, request
from flask.ext.login import current_user
from app.exceptions import JsonOutputException
from app import db, cache
from sqlalchemy.exc import IntegrityError
from app.auth.models import Role, Module
from .. import admin_blueprint
@admin_blueprint.route('/roles/')
def ro... |
psf/black | tests/data/long_strings.py | x = "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three."
x += "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even ta... |
sirodoht/pylis | parser.py | def parse_coefficients(coefficient_list, monomial):
"""
:rtype : None
:param coefficient_list: List in which coefficients will be stored
:param monomial: A string (e.g. -3x1) which will be parsed to its coefficient (e.g. -3)
"""
import re
# Check which pattern matches. Valid are: (s)(n)lv
... |
parrt/dtreeviz | testing/cancer.py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import graphviz
import graphviz.backend
from numpy.distutils.system_info import f2py_info
from sklearn import tree
from sklearn.datasets import load_boston, load_iris, load_wine, load_digits, \
load_breast_cancer, load_diabetes, fetch_mldata
from matplo... |
MaxIV-KitsControls/netspot | netspot/lib/spotmax/tests/test_network_device.py | #!/usr/bin/python -tt
"""JUNOS link down test
Run: python -m unittest tests.test_network_device
"""
import unittest
import network_device
VLAN_INTERFACES = """ Untagged interfaces: ge-0/0/0.0, ge-0/0/1.0,
ge-0/0/46.0, ge-0/0/47.0, xe-2/0/0.0
Tagged interfaces: ae0.... |
renmengye/imageqa-public | src/imageqa_crosstest.py | import sys
import numpy as np
import imageqa_test as it
import prep
import nn
def reindexDataset(
srcQuestions,
srcAnswers,
srcQuestionIdict,
dstQuestionDict,
srcAnsIdict,
dstAnsDict):
dstQuestions = np.zeros(srcQuesti... |
MidwestCommunications/django-askmeanything | askmeanything/migrations/0001_initial.py |
from south.db import db
from django.db import models
from askmeanything.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Poll'
db.create_table('askmeanything_poll', (
('id', orm['askmeanything.Poll:id']),
('question', orm['askmeanythin... |
rnelson/adventofcode | advent2015/partial_day24.py | #!/usr/bin/env python
"""
http://adventofcode.com/day/24
Part 1
------
It's Christmas Eve, and Santa is loading up the sleigh for this year's
deliveries. However, there's one small problem: he can't get the sleigh
to balance. If it isn't balanced, he can't defy physics, and nobody gets
presents this year.
No pressure... |
RyanBalfanz/reservoir-sampling-cli | setup.py | import os
from setuptools import setup, find_packages
setup(
name = "reservoir-sampling-cli",
version = "0.1",
description = "A command line tool to randomly sample k items from an input S containing n items.",
# long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
url = "https://g... |
raphaottoni/pinterest-twitter | twitter/checkTweets.py | #! /usr/bin/python
import sys,fcntl,json,re
import time,random
import os.path
import gzip
from multiprocessing import Pool
tweetPath= "/net/data/twitter/gardenhose-data/summarized"
#return urls of a string
def findUrl(tweet):
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9... |
wbinventor/openmc | openmc/examples.py | from numbers import Integral
import numpy as np
import openmc
import openmc.model
def pwr_pin_cell():
"""Create a PWR pin-cell model.
This model is a single fuel pin with 2.4 w/o enriched UO2 corresponding to a
beginning-of-cycle condition and borated water. The specifications are from
the `BEAVRS ... |
kfdm/wanikani | wanikani/core.py | import collections
import datetime
import json
import logging
import requests
logger = logging.getLogger(__name__)
__all__ = ['WaniKani', 'Radical', 'Kanji', 'Vocabulary']
WANIKANI_BASE = 'https://www.wanikani.com/api/v1.4/user/{0}/{1}'
def split(func):
# From http://stackoverflow.com/a/21767522/622650
de... |
SocialNPHS/SocialNPHS | SocialNPHS/sources/twitter/auth.py | """
Get authenticated tweepy API object
"""
import json
import os
import tweepy
def _get_secret_stuffs():
""" Retrieves Twitter API tokens & keys from stored secrets """
secrets = ["CONSUMER_KEY",
"CONSUMER_SECRET",
"ACCESS_TOKEN",
"ACCESS_SECRET"]
return [os... |
ThayaFluss/fde-ipn | tests/test_fde_sc_c2.py | import unittest
import numpy as np
from fde_sc_c2 import *
from random_matrices import *
from matrix_util import *
class TestSmiCircular(unittest.TestCase):
def test_set_params(self):
d = 20
p = 100
sc = SemiCircular(dim=d, p_dim=p)
diag_A = np.arange(d)/d
sigma = 0.1
... |
haobtc/bitcoin | qa/rpc-tests/test_framework/util.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.
#
# Helpful routines for regression testing
#
import os
import sys
from binascii import hexlify, unhex... |
peterbe/django-cron | django_cron/base.py | """
Copyright (c) 2007-2008, Dj Gilcrease
All rights reserved.
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, me... |
einsfr/cmc | cmc/conf/prod.py | ALLOWED_HOSTS = []
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.Secur... |
harshitanand/Git-Issue-Tracker | Git_Issue_Tracker/settings.py | """
Django settings for Git_Issue_Tracker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DI... |
cigno5/pyscripts | scripts/icsexport.py | import argparse
import getpass
import json
import os
import re
import sys
from datetime import datetime, timedelta
import requests
import abnconv
from abnconv import QIFOutput, Trsx
def extract_transactions():
base_url = "https://www.icscards.nl"
login_url = "%s/pub/nl/pub/login" % base_url
account_url ... |
goldshtn/linux-tracing-workshop | nhttpslower.py | #!/usr/bin/env python
#
# nhttpslower Snoops and prints Node.js HTTP requests slower than a threshold.
# This tool is experimental and designed for teaching purposes
# only; it is neither tested nor suitable for production work.
#
# NOTE: Node http__client* probes are not accurate in that ... |
JustF0rWork/malware | core/httpd.py | #!/usr/bin/env python
"""
Copyright (c) 2014-2016 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""
import BaseHTTPServer
import cStringIO
import datetime
import httplib
import glob
import gzip
import hashlib
import io
import json
import mimetypes
import os
import re
import socket
import ... |
Bystroushaak/abclinuxuapi | src/abclinuxuapi/shared.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import re
import time
import types
import datetime
from urlparse import urljoin
import requests
import dhtmlparser
# Variables =========================... |
IzunaDevs/nsfw_dl | nsfw_dl/loaders/xbooru.py | """
Read the license at:
https://github.com/IzunaDevs/nsfw_dl/blob/master/LICENSE
"""
from nsfw_dl.bases import BaseSearchXML
class XbooruRandom:
""" Gets a random image from xbooru. """
data_format = "bs4/html"
@staticmethod
def prepare_url(args):
""" ... """
type(args)
retur... |
pwittchen/learn-python-the-hard-way | exercises/exercise03.py | # Exercise 3: Numbers and Math
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7... |
PythonClutch/python-clutch | migrations/versions/575dde6b846_.py | """empty message
Revision ID: 575dde6b846
Revises: 472b0bb2ebe
Create Date: 2015-03-24 14:56:28.790901
"""
# revision identifiers, used by Alembic.
revision = '575dde6b846'
down_revision = '472b0bb2ebe'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... |
dmazzer/nors | remote/nors.py | #!/usr/bin/env python2
"""
nors.py: Noticia Remote Management and Supervisor
"""
__author__ = "Daniel Mazzer"
__copyright__ = "Copyright 2016, NORS project"
__credits__ = ""
__license__ = "GPL"
__maintainer__ = "Daniel Mazzer"
__email__ = "dmazzer@gmail.com"
from sensorservice.sensorservice import Nors_SensorServi... |
JasonTam/ndsb2015 | feature/extract_feats.py | __author__ = 'jason'
import os
import numpy as np
from skimage.io import imread
import feature.improc as improc
from skimage.transform import resize
def im_features(im_path):
im = imread(im_path, as_grey=True)
im_bw = improc.gray_to_bw(im)
labels = improc.bw_labels(im_bw)
region_max = improc.get_max_... |
begoldsm/azure-data-lake-store-python | tests/test_core.py | # -*- coding: utf-8 -*-
# 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.
# ---------------------------------------------... |
shawnsi/amicleanup | upload.py | #!/usr/bin/env python
from __future__ import print_function
import sys
from tempfile import TemporaryFile
from zipfile import ZipFile
import boto3
from botocore.exceptions import ClientError
assume_role_policy_document = """{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow"... |
thesgc/cbh_datastore_model | runtests.py | import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="cbh_dat... |
yuzie007/ph_plotter | ph_plotter/sf_plotter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os
import h5py
import numpy as np
from ph_plotter.plotter import Plotter
from ph_plotter.plotter import read_band_labels
__author__ = "Yuji Ikeda"
class S... |
sixohsix/musi | musi/examples/emitter.py | from time import sleep
from simplecoremidi import MIDISource
from musi import C, Buffer, Tap, If, midi, math, waves, play, countdown
def FilterLFO():
inner_lfo = waves.Sine(C(7.0))
ramp_per = math.Sub(C(3.0), math.Mul(C(2.9), inner_lfo))
ramp = waves.Ramp(ramp_per)
return midi.ControllerChange(
... |
dunkenj/smpy | dist/astro-smpy-0.1.dev/smpy/version.py | from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 1
_version_micro = '' # use '' for first of series, number for 1 and above
_version_extra = 'dev'
#_version_extra = '' # Uncomment this for full releases
# Construct ful... |
nkoech/csacompendium | csacompendium/indicators/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-06-28 08:54
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contentt... |
viaict/viaduct | migrations/versions/2018_03_14_22710e6fd2b1_set_category_of_alv_document_revisions.py | """Set category of ALV document revisions.
Revision ID: 22710e6fd2b1
Revises: 4a3debf40b72
Create Date: 2018-03-14 15:35:30.841219
"""
from alembic import op
import sqlalchemy as sa
from app.models.base_model import BaseEntity
from app.enums import FileCategory
from sqlalchemy.ext.declarative import declarative_base... |
ponycoin/ponycoin-obsolete | contrib/bitrpc/bitrpc.py | from jsonrpc import ServiceProxy
import sys
import string
# ===== 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:6932")
else:
access = Ser... |
davemcphee/sensu-pager-handler | python-handler/sensu-handler.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python sensu handler - now with decision making ability!
You know what, now that I've built the sensu slackbot, we can make this app as dumb as a box of rocks.
Just take every check event and forward it to slackbot, let it decide what to do.
"""
import json
import lo... |
ForceBru/PyVM | VM/kernel/kernel.py | from typing import Callable
from ..ctypes_types import dword as Int, udword as Uint
import logging
logger = logging.getLogger(__name__)
class KernelMeta(type):
def register(cls, syscall_number: int):
def actually_register(function: Callable[..., int]):
assert syscall_number not in cls.sy... |
texastribune/scuole | scuole/cohorts/urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.urls import path
from .views import (
AcceptCohortRedirectView,
CohortsLandingView,
CountyCohortsDetailView,
RegionCohortsDetailView,
StateCohortsDetailView,
)
app_name = "cohorts"
urlpatterns = [
pa... |
rajarahulray/iDetector | tests_and_ References/scrollbar_test_3.py | import tkinter as tk
import os
import tkinter.filedialog
import tkinter.messagebox
class Main(tk.Tk):
def __init__(self, *args, **kwargs):
'''This initialisation runs the whole program'''
#textBoxList = []
tk.Tk.__init__(self, *args, **kwargs)
self.title('Untitled')
self.g... |
angadpc/Alexa-Project- | twilio/rest/pricing/v1/__init__.py | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.pricing.v1.messaging import MessagingList
from twilio.rest.pricing.v1.phone_number import PhoneNumberList
from twilio.rest.pricing.v1.voice imp... |
nachomaro/AsteriskIVR | agi-math.py | #!/usr/bin/python
import sys
import re
import time
import random
from db import Database
# Read and ignore AGI environment (read until blank line)
env = {}
tests = 0;
while 1:
line = sys.stdin.readline().strip()
if line == '':
break
key,data = line.split(':')
if key[:4] <> 'agi_':
#skip inp... |
onshape-public/onshape-clients | python/onshape_client/oas/models/btfs_value_map2062.py | # coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
renzon/fatec-script-2 | backend/test/book_tests/command_tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from base import GAETestCase
from decimal import Decimal
from book_app.commands import SaveBookCommand
from book_app.model import Book
from gaebusiness.business import CommandExecutionException
class SaveBookTests(GAETestCase):
def t... |
twilio/twilio-python | twilio/rest/conversations/v1/service/__init__.py | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... |
rwl/PyCIM | CIM14/IEC61970/Wires/HeatExchanger.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... |
juliosueiras/atlas-vim | vim/plugged/vimshell/rplugin/python3/deoplete/sources/vimshell.py | #=============================================================================
# FILE: vimshell.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license {{{
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation fi... |
Sispheor/piclodio3 | back/utils/scheduler_manager.py | import asyncio
import logging
from apscheduler.jobstores.base import JobLookupError
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from piclodio3 import settings
from utils.player_manager import PlayerManager
from utils.singleton import Singleton
... |
craigcabrey/axel | axel/util.py | import pushbullet
from axel import config
pushbullet_client = None
sender = None
if not pushbullet_client and config['pushbullet_key']:
pushbullet_client = pushbullet.Pushbullet(config['pushbullet_key'])
if config['pushbullet_channel']:
for channel in pushbullet_client.channels:
if channel.name == c... |
quanta-computing/suprabackup | suprabackup/scripts/receive.py | #!/usr/bin/env python
"""
Usage: suprabackup_receive.py
Author: Matthieu 'Korrigan' Rosinski <mro@quanta-computing.com>
This script is a wrapper to handle xtrabackup uploads for Percona server
backups
"""
import os
import sys
import datetime
from suprabackup import db
from suprabackup.logging import setup_logging
fr... |
lotharwissler/bioinformatics | python/fasta/fasta-sort.py | #!/usr/bin/python
import os, sys # low level handling, such as command line stuff
import string # string methods available
import re # regular expressions
import getopt # comand line argument handling
from low import * # custom functions, written by myself
import anydbm
# =========================... |
sisap-ics/sidiap | sidiap/ramify/ramify.py | # -*- coding: utf8 -*-
"""
Eines per a al traspàs de dades de MariaDB a Redis.
Es defineixen 3 classes:
- Ramify: controla l'execució i instancia la resta de classes
- Domini: crea les eines necessàries per cada domini (query, conversors, etc.)
- Particio: executa el traspàs per cada partició de cada taula (en un pool... |
luis-martinez/HackerRank | Algorithms/Warmup/solve-me-second/solve-me-second.py | olveMeSecond(a,b):
return a+b
n = int(raw_input()) #faster than n = input() , since input() executes the line as python command
for i in range(0,n):
a, b = raw_input().split()
a, b = int(a),int(b)
res = solveMeSecond(a,b)
print res
'''
Alternate code
n = int(raw_input())
for _ in range(n):
... |
pgavlin/coreclr | tests/scripts/optdata/bootstrap.py | #!/usr/bin/env python
"""
This script prepares the local source tree to be built with
custom optdata. Simply run this script and follow the
instructions to inject manually created optdata into the build.
"""
import argparse
import os
from os import path
import shutil
import subprocess
import sys
import xm... |
dsimandl/teamsurmandl | music/models.py |
from django.db import models
from profiles.models import SurmandlUser
class Music(models.Model):
song_title = models.CharField('Song Title', max_length=255)
album_name = models.CharField('Album Name', max_length=255)
artist_name = models.CharField('Artist Name', max_length=255)
comments = models.... |
zhangziang/MyLeetCodeAlgorithms | python/328-odd_even_linked_list.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
... |
mr-karan/Udacity-FullStack-ND004 | Project3/udacityblog-159515/handlers/editpost.py | from google.appengine.ext import db
from handlers.blog import BlogHandler
from helpers import *
class EditPostHandler(BlogHandler):
def get(self, post_id):
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
return self.redirect('/log... |
arineto/twitter_monitor | monitor/models.py | from django.db import models
from monitor import enums
from tweepy.error import TweepError
from twitter_monitor.twitter_api import get_api
class TwitterUser(models.Model):
user_id = models.CharField(max_length=20)
username = models.CharField(max_length=100, unique=True)
status = models.IntegerField(
... |
denverfoundation/storybase | apps/storybase_asset/migrations/0004_auto__chg_field_localdataset_file.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):
# Changing field 'LocalDataSet.file'
db.alter_column('storybase_asset_localdataset', 'file_id', self.gf('d... |
comger/migrant | web/action/index.py | # -*- coding:utf-8 -*-
"""
author comger@gmail.com
migrant 前端展示公共页面
"""
from kpages import url,get_context
from kpages.model import ModelMaster
from utility import BaseHandler
mmaster = ModelMaster()
AModel = mmaster('AccountModel')
AreaModel = mmaster('AreaModel')
@url(r'/?')
class Index(BaseHandler):
d... |
Zylphrex/faver | faver_site/faver_app/migrations/0003_contract.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-21 20:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('faver_app', '0002_faverrequest_issuer'),
]
operati... |
qwergram/imgur_clone | imagersite/imager_profile/tests/test_model.py | from django.test import TestCase
from django.contrib.auth.models import User
import factory
from imager_profile import models
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.Faker('word')
password = factory.PostGenerationMethodCall('set_password'... |
jeremiedecock/snippets | python/tkinter/python3/button1.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Jérémie 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 the Software without restriction, including witho... |
just-an-dev/sodogetip | commands/hall_of_fame.py | from jinja2 import Template
import bot_logger
import config
import lang
import models
def hall_of_fame(msg):
user = models.User(msg.author.name)
if user.is_registered():
message = "Donation Tip to " + config.bot_name + " : "
donator_list = {}
hist = models.HistoryStorage.get_user_hist... |
maxzheng/part-of-family | app/main.py | import base64
from pathlib import Path
import aiohttp_jinja2
import aiohttp_session
import jinja2
from aiohttp import web
from aiohttp_jinja2 import APP_KEY as JINJA2_APP_KEY
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from aiopg.sa import create_engine
from sqlalchemy.engine.url import URL
fro... |
pjgb/dailyprogrammer | ch280e.py | #!/usr/bin/env python3
# Oh, how cursed we are to have but 10 digits upon our fingers. Imagine the
# possibilities were we able to count to numbers beyond! But halt!
# With 10 digits upon our two appendages, 1024 unique combinations appear!
# But alas, counting in this manner is cumbersome, and counting to such a
#... |
Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.1/async_samples/sample_strongly_typing_recognized_form_async.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.
# --------------------------------------------------------------------... |
Azure/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE:... |
fffy2366/image-processing | tests/python/nude.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import copy
import math
import sys
import time
from collections import namedtuple
from PIL import Image
def is_nude(path_or_io):
nude = Nude(path_or_io)
return... |
Phonemetra/TurboCoin | test/functional/rpc_getblockstats.py | #!/usr/bin/env python3
# Copyright (c) 2017-2019 TurboCoin
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test getblockstats rpc call
#
from test_framework.test_framework import TurbocoinTestFramework
from test_framework.util... |
MargaritaLubimova/python_park_mail | homework/homework3.4.5/weather.py | import datetime
import json
import urllib.request
class Weather():
def __time_converter(self, time):
converted_time = datetime.datetime.fromtimestamp(int(time)).strftime('%I:%M %p')
return converted_time
def __url_builder(self, city_id):
user_api = '0b1eaf7ce235a1ebaba14d5e07ee4228'
... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/vpn_client_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 ... |
dubejf/three.js | utils/exporters/blender/addons/io_three/exporter/base_classes.py | from . import utilities
from .. import constants, exceptions
class BaseClass(constants.BASE_DICT):
"""Base class which inherits from a base dictionary object."""
_defaults = {}
def __init__(self, parent=None, type=None):
constants.BASE_DICT.__init__(self)
self._type = type
self.... |
Clarity-89/clarityv2 | src/clarityv2/accounts/models.py | from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django_countries.fields import CountryField
from solo.models import SingletonModel
from .managers import UserManager
c... |
meantheory/dotfiles | dos/src/dos/pkg/base.py | class Package:
def __init__(self, name, **kwargs):
state = kwargs.get("state", "latest")
pass
def apt_get(self):
pass
def yum(self):
pass
def plan(self):
pass
def apply(self):
pass
class Packages:
def __init__(self, *args):
self.packa... |
aymara/verbenet-editor | syntacticframes_project/syntacticframes/migrations/0006_auto_20141103_0939.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def copy_primary_key_id(apps, schema_editor):
VerbNetFrameSet = apps.get_model('syntacticframes', 'VerbNetFrameSet')
for fs in VerbNetFrameSet.objects.all():
fs.tree_id = fs.id
fs.save()
c... |
alexey-ernest/ml-for-trading | global_statistics.py |
import os
import pandas as pd
import matplotlib.pyplot as plt
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from ... |
luzfcb/django-mtr-sync | mtr/sync/helpers.py | import os
from functools import wraps
from django.shortcuts import render
from .settings import THEME_PATH
def themed(template):
"""Changing template themes by setting THEME_PATH"""
return os.path.join('mtr', 'sync', THEME_PATH(), template)
def render_to(template, *args, **kwargs):
"""Shortuct for r... |
sindresf/The-Playground | Python/Artificial Intelligence/Evolutionary Algorithm/G.E-A images/G.E-A generic/genome/genes.py | #genes of simple types are just the types
#don't make genes that aren't bigger structs
#Example:
class CircleGene(object):
def __init__(self, config): #config sets the init through random ranges
self.x = 0
self.y = 0
self.radius = 1.0
self.color = (0,0,0)
self.alpha = 1.0
cl... |
CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_rnaseqdiffexpression/trackers/Genelists.py | from RnaseqDiffExpressionReport import ProjectTracker
from RnaseqDiffExpressionReport import linkToEnsembl, linkToUCSC
class TopDifferentiallyExpressedGenes(ProjectTracker):
'''output differentially expressed genes.'''
limit = 10
pattern = '(.*)_gene_diff'
sort = ''
def __call__(self, track, sli... |
jefftc/changlab | scripts/annotate_geneset.py | #!/usr/bin/env python
# Functions:
# read_geneset
# read_all_genesets
# read_annotations
import os
def read_geneset(geneset):
# Parse a geneset specified by the user. geneset is in the format
# of <filename>[,<geneset>,<geneset>,...]. Return a list of
# (<filename>, <geneset>, list of genes).
fro... |
hbldh/skboost | skboost/milboost/softmax/nor.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`nor`
==================
.. module:: nor
:platform: Unix, Windows
:synopsis:
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2015-11-05
"""
from __future__ import division
from __future__ import print_function
from __future__ import uni... |
bbengfort/inigo | migrations/env.py | # env.py
# Alembic autogenerated environment file for managing migrations.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sun Jul 05 16:03:31 2015 -0400
#
# Copyright (C) 2015 Bengfort.com
# For license information, see LICENSE
#
# ID: env.py [] benjamin@bengfort.com $
"""
Alembic autogenerated en... |
vdmann/cse-360-image-hosting-website | src/filter/models.py | # from django.db import models
# from dragdrop.files import get_path
# from django.contrib.auth.models import User
# from drinker.models import Drinker
# from django.conf import settings
# def _upload_path(instance, filename):
# return instance.get_upload_path(filename)
# class UploadFile(models.Model):
# file = mo... |
cprogrammer1994/ModernGL | examples/integration_pycairo.py | """
Using pycairo with moderngl.
We simply create a screen aligned quad with texture coordinates
to render the uploaded texture from cairo.
Textures in OpenGL are stored "upside-down" so we build
a vertex array with inverted y coordinates
"""
import math
from array import array
import cairo
import moderngl
from mod... |
lmazuel/azure-sdk-for-python | azure-mgmt-authorization/azure/mgmt/authorization/operations/__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 ... |
trottmpq/test_manager | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'transitions'
# TODO: put package requirements here
]
test_requirem... |
gouthambs/qtk-python | test/test_options.py | from unittest import TestCase
from qtk import Controller
class TestOptions(TestCase):
def test_european_option(self):
asof_date = '5/8/2015'
data = [
{'MaturityDate': '1/15/2016',
'ObjectId': 'EuropeanOption',
'OptionType': 'Call',
'Strike': 130,... |
ulule/django-linguist | linguist/utils.py | # -*- coding: utf-8 -*-
import copy
import itertools
import collections
from importlib import import_module
from django.db.models import QuerySet
from django.core import exceptions
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.translation import get_language a... |
ryanpdwyer/jittermodel | jittermodel/tests/scratchwork.py | # -*- coding: utf-8 -*-
"""
scratchwork.py
Created by Ryan Dwyer on 2013-10-15.
Copyright (c) 2013 Cornell University. All rights reserved.
"""
from jittermodel import u
from jittermodel.base import Cantilever, Transistor, Experiment
from jittermodel.plot import GeneratePlotData
import cProfile
import pstats
def ma... |
xelzmm/proxy_server_crawler | crawler/spiders/chunzhen.py | from scrapy.spiders import Spider
from scrapy.http import Request
from scrapy.selector import Selector
from crawler.items import ProxyIPItem
class ChunzhenSpider(Spider):
name = "chunzhen"
allowed_domains = ["cz88.net"]
start_urls = [
"http://www.cz88.net/proxy/index.shtml",
"http://www.cz8... |
MarcAndreJean/PCONC | Modules/04-06-RAM.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Projet : Editeur, Compilateur et Micro-Ordinateur pour
un langage assembleur.
Nom du fichier : 04-06-RAM.py
Identification : 04-06-RAM
Titre : RAM
Auteurs : Francis Emond, Malek Khattech,
... |
exercism/xpython | exercises/protein-translation/protein_translation_test.py | import unittest
from protein_translation import proteins
# Tests adapted from `problem-specifications//canonical-data.json`
class ProteinTranslationTest(unittest.TestCase):
def test_methionine_rna_sequence(self):
value = "AUG"
expected = ["Methionine"]
self.assertEqual(proteins(value), e... |
relet/peergov | cryptutils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from hashlib import md5
from datetime import datetime
import pyme.core, pyme.constants.sig
import yaml
class CryptUtilException(Exception):
pass
def getPassphrase(hint, desc, prev_bad):
print "Passphrase Callback! %s %s %s" % (hint, desc, prev_bad)
sys... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.