code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... | robb-brown/IntroToDeepLearning | 6_MRISegmentation/ccseg.py | Python | mit | 4,404 |
import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="treemap.marker.colorbar", **kwargs
):
super(TicklenValidator, self).__init__(
plotly_name=plotly_name,
paren... | plotly/python-api | packages/python/plotly/plotly/validators/treemap/marker/colorbar/_ticklen.py | Python | mit | 515 |
from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Assessment.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_GET
def getAssignmentByCode(request):
resp... | IEEEDTU/CMS | Assessment/views/Assignment.py | Python | mit | 2,991 |
instr = [x.strip().split(' ') for x in open("input/dec25").readlines()]
skip = {}
modified = {}
#instr[1] = ['add', 'a', '2572']
#skip[2] = skip[3] = skip[4] = skip[5] = skip[6] = skip[7] = skip[8] = skip[9] = True
#instr[6] = ['add', 'a', 'c'] # adds c to d, sets c to 0
#skip[7] = True
#skip[8] = True
#modified[6] =... | matslindh/codingchallenges | adventofcode2016/25.py | Python | mit | 3,632 |
import enum
from typing import Dict, Optional, Set
@enum.unique
class MediaTag(enum.IntEnum):
# ndb keys are based on these! Don't change!
CHAIRMANS_VIDEO = 0
CHAIRMANS_PRESENTATION = 1
CHAIRMANS_ESSAY = 2
MEDIA_TAGS: Set[MediaTag] = {t for t in MediaTag}
TAG_NAMES: Dict[MediaTag, str] = {
Medi... | the-blue-alliance/the-blue-alliance | src/backend/common/consts/media_tag.py | Python | mit | 1,026 |
from django.template import Library
register = Library()
@register.simple_tag(takes_context=True)
def assign(context, **kwargs):
"""
Usage:
{% assign hello="Hello Django" %}
"""
for key, value in kwargs.items():
context[key] = value
return ''
@register.filter
def get(content, key):... | redisca/django-redisca | redisca/template/templatetags/builtin.py | Python | mit | 833 |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import start_nodes
from test_framework.mininode import CTran... | litecoinz-project/litecoinz | qa/rpc-tests/bip65-cltv-p2p.py | Python | mit | 3,533 |
# output formatting
# reprlib provides a version of repr()
import reprlib
print(reprlib.repr(set('supercalifragilisticexpialidocious')))
# pprint - more sophisticated control over printing objects in a way readable by the interpreter
import pprint
t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],... | CajetanP/code-learning | Python/Learning/Language/stdlib_2.py | Python | mit | 5,228 |
"""
Wind Turbine Company - 2013
Author: Stephan Rayner
Email: stephan.rayner@gmail.com
"""
import time
from test.Base_Test import Base_Test
class Maintenance_153Validation(Base_Test):
def setUp(self):
self.WindSpeedValue = "4.5"
self.interface.reset()
self.interface.write("Yaw_Generation... | stephan-rayner/HIL-TestStation | Tests/e3120/Maintenance/TransitionIntoState0.py | Python | mit | 3,533 |
# -*- encoding: utf-8 -*-
import ast
import inspect
class NameLower(ast.NodeVisitor):
def __init__(self, lowered_names):
self.lowered_names = lowered_names
def visit_FunctionDef(self, node):
code = '__globals = globals()\n'
code += '\n'.join("{0} = __globals['{0}']".format(name) for ... | xu6148152/Binea_Python_Project | PythonCookbook/meta/newlower.py | Python | mit | 1,116 |
from django.utils.encoding import python_2_unicode_compatible
from allauth.socialaccount import app_settings
from allauth.account.models import EmailAddress
from ..models import SocialApp, SocialAccount, SocialLogin
from ..adapter import get_adapter
class AuthProcess(object):
LOGIN = 'login'
CONNECT = 'conn... | sih4sing5hong5/django-allauth | allauth/socialaccount/providers/base.py | Python | mit | 5,951 |
XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX ... | dnaextrim/django_adminlte_x | adminlte/static/plugins/datatables/extensions/ColReorder/examples/predefined.html.py | Python | mit | 16,794 |
from ..baseapi import BaseApi
class Template(BaseApi):
def __init__(self, *args, **kwargs):
super(Template, self).__init__(*args, **kwargs)
self.endpoint = 'templates'
self.list_id = None
def all(self):
"""
returns a list of available templates.
"""
re... | s0x90/python-mailchimp | mailchimp3/entities/template.py | Python | mit | 887 |
import datetime
import os
import sys
from contextlib import contextmanager
import freezegun
import pretend
import pytest
from pip._vendor import lockfile
from pip._internal.index import InstallationCandidate
from pip._internal.utils import outdated
class MockPackageFinder(object):
BASE_URL = 'https://pypi.pyth... | zvezdan/pip | tests/unit/test_unit_outdated.py | Python | mit | 6,190 |
import sys, math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
class Tree(object):
def __repr__(self):
return self.val
def __init__(self, val=None):
self.val = val
self.childs = []
def add_number(self, number):
... | hibou107/algocpp | telephone.py | Python | mit | 1,349 |
# coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr... | ShaguptaS/faker | faker/providers/fr_FR/internet.py | Python | mit | 1,414 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-21 04:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0011_auto_20170621_1224'),
]
operations = [
migrations.AddField(
... | r26zhao/django_blog | blog/migrations/0012_auto_20170621_1250.py | Python | mit | 586 |
import _plotly_utils.basevalidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="tickvals", parent_name="parcoords.dimension", **kwargs
):
super(TickvalsValidator, self).__init__(
plotly_name=plotly_name,
par... | plotly/python-api | packages/python/plotly/plotly/validators/parcoords/dimension/_tickvals.py | Python | mit | 473 |
from django.forms import ModelForm, ModelChoiceField
from django.utils.translation import ugettext_lazy as _
from apps.task.models import Task
class FormChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class TaskForm(ModelForm):
"""
Task form used to add or update a task in t... | hgpestana/chronos | apps/task/forms.py | Python | mit | 630 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import redis
import json
class Redis(object):
def __init__(self, host="localhost", port=6379):
self._host = host
self._port = port
self._redis_cursor = None
def conn(self):
if self._redis_cursor is None:
pool = redis.C... | huhuchen/asyncqueue | asyncqueue/_redis.py | Python | mit | 720 |
__author__ = 'thorwhalen'
import requests
from serialize.khan_logger import KhanLogger
import logging
class SimpleRequest(object):
def __init__(self, log_file_name=None, log_level=logging.INFO):
full_log_path_and_name = KhanLogger.default_log_path_with_unique_name(log_file_name)
self.logger = Kh... | thorwhalen/ut | slurp/simple_request.py | Python | mit | 787 |
import os
import glob
#####################################################
######Init the files##################################
#####################################################
os.remove("a0.txt")
os.remove("a1.txt")
os.remove("a2.txt")
os.remove("a3.txt")
os.remove("a4.txt")
os.remove("a5.txt")
os.remove("a6... | doylew/detectionsc | format_py/ngram_nskip.py | Python | mit | 6,042 |
#
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... | joushou/stackable | utils.py | Python | mit | 3,175 |
from flask_pymongo import PyMongo
from flask_cors import CORS
mongo = PyMongo()
cors = CORS() | TornikeNatsvlishvili/skivri.ge | backend/backend/extensions.py | Python | mit | 94 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
import uchicagohvz.overwrite_fs
from django.conf import settings
import django.utils.timezone
import uchicagohvz.game.models
class Migration(migrations.Migratio... | kz26/uchicago-hvz | uchicagohvz/game/dorm_migrations/0001_initial.py | Python | mit | 11,763 |
import torch
import sys
import types
class VFModule(types.ModuleType):
def __init__(self, name):
super(VFModule, self).__init__(name)
self.vf = torch._C._VariableFunctions
def __getattr__(self, attr):
return getattr(self.vf, attr)
sys.modules[__name__] = VFModule(__name__)
| ryfeus/lambda-packs | pytorch/source/torch/nn/_VF.py | Python | mit | 310 |
"""
Constructs a planner that is good for being kinda like a car-boat thing!
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from params import *
import lqrrt
################################################# DYNAMICS
magic_rudder = 6000
def dynamics(x, u, dt):
"""
Returns... | jnez71/lqRRT | demos/lqrrt_ros/behaviors/car.py | Python | mit | 3,231 |
from django.test import TestCase
from builds.models import Version
from projects.models import Project
class RedirectTests(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.client.login(username='eric', password='test')
r = self.client.post(
'/dashboard/import/',
... | ojii/readthedocs.org | readthedocs/rtd_tests/tests/test_redirects.py | Python | mit | 3,374 |
import hexchat
import re
import sys
import twitch.hook, twitch.jtvmsghandler, twitch.user, twitch.channel
import twitch.normalize, twitch.commands, twitch.exceptions, twitch.topic
import twitch.logger, twitch.settings
from twitch import irc
log = twitch.logger.get()
# regex for extracting time from ban message
ban_msg... | RenaKunisaki/hexchat-twitch | twitch/hooks.py | Python | mit | 11,648 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
from ._version import __version__, __version_info__ # noqa
from .decorators import route, resource, asynchronous
from .helpers import use
from .relationship import Relationship
__all__ = [
'route',
'resource',
'asyn... | armet/python-armet | armet/__init__.py | Python | mit | 363 |
#!/usr/bin/env python
#
# License: MIT
#
from __future__ import absolute_import, division, print_function
##############################################################################
# Imports
##############################################################################
import os
import sys
import argparse
import ... | pyros-dev/ros1_template | ros1_pytemplate/scripts/question_cli.py | Python | mit | 2,859 |
from flask.ext.login import UserMixin, AnonymousUserMixin
from codeta import app, auth, logger
from codeta.models.course import Course
class User(UserMixin):
def __init__(self, user_id, username, password, email, fname, lname, active=True, courses=[]):
self.user_id = user_id
self.username = userna... | CapstoneGrader/codeta | codeta/models/user.py | Python | mit | 6,342 |
# Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import sys
import time
from datetime import datetime
from pathlib import Path
from ezdxf.acc import USE_C_EXT
from ezdxf.render.forms import ellipse
if USE_C_EXT is False:
print("C-extension disabled or not available.")
sys.exit(1)
from ezdxf.math._... | mozman/ezdxf | profiling/construct.py | Python | mit | 3,719 |
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..."
import random
# this is the function that will execute the program
def program():
# These are the ... | starnes/Python | guessnameclass.py | Python | mit | 1,452 |
import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f``... | knoppo/pi3bar | pi3bar/plugins/disk.py | Python | mit | 3,744 |
"""Process `site.json` and bower package tools."""
import os
import json
import subprocess
from functools import partial
import importlib
import sys
from flask import Flask, render_template, g, redirect, current_app
from gitloader import git_show
from import_code import import_code
try:
from app import app
exce... | cacahootie/deckmaster | deckmaster/app/process_site.py | Python | mit | 4,475 |
#!env/bin/python
from app import app
import sys
port = 5000
debug = True
if len(sys.argv) == 3:
debug = sys.argv[1] == 'debug'
port = int(sys.argv[2])
app.run(debug = debug, port = port)
| BamX/dota2-matches-statistic | run.py | Python | mit | 191 |
#!/usr/bin/env python3
"""
Find characters deep in the expanded string, for fun.
"""
import sys
from collections import Counter
def real_step(s, rules):
out = ""
for i in range(len(s)):
out += s[i]
k = s[i:i+2]
if k in rules:
out += rules[k]
return out
def step(cn... | msullivan/advent-of-code | 2021/14balt.py | Python | mit | 1,674 |
from raptiformica.utils import list_all_files_in_directory
from tests.testcase import TestCase
class TestListAllFilesInDirectory(TestCase):
def setUp(self):
self.walk = self.set_up_patch('raptiformica.utils.walk')
self.walk.return_value = [
('/tmp/a/directory', ['dir'], ['file.txt', 'f... | vdloo/raptiformica | tests/unit/raptiformica/utils/test_list_all_files_in_directory.py | Python | mit | 1,134 |
import threading, time
from sqlalchemy import pool, interfaces, select, event
import sqlalchemy as tsa
from sqlalchemy import testing
from sqlalchemy.testing.util import gc_collect, lazy_gc
from sqlalchemy.testing import eq_, assert_raises
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing im... | rclmenezes/sqlalchemy | test/engine/test_pool.py | Python | mit | 37,265 |
from .models import EmailUser
class EmailOrPhoneModelBackend:
def authenticate(self, username=None, password=None):
if '@' in username:
kwargs = {'email__iexact': username}
else:
kwargs = {'phone': username}
try:
user = EmailUser.objects.get(**kwargs)
... | pannkotsky/groupmate | backend/apps/users/login_backend.py | Python | mit | 618 |
"""
Production settings
Debug OFF
Djeroku Defaults:
Mandrill Email -- Requires Mandrill addon
dj_database_url and django-postgrespool for heroku postgres configuration
memcachify for heroku memcache configuration
Commented out by default - redisify for heroku redis cache configuration
What you need t... | collingreen/djeroku | project/settings/prod.py | Python | mit | 4,008 |
import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400... | codeka/website | handlers/snip.py | Python | mit | 955 |
# 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 ... | lmazuel/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/cluster_upgrade_description_object.py | Python | mit | 5,840 |
#!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | testing-cabal/extras | setup.py | Python | mit | 1,687 |
import tensorflow as tf
import numpy as np
import deep_architect.modules as mo
import deep_architect.hyperparameters as hp
from deep_architect.contrib.misc.search_spaces.tensorflow.common import siso_tfm
D = hp.Discrete # Discrete Hyperparameter
def dense(h_units):
def compile_fn(di, dh): # compile function
... | negrinho/deep_architect | dev/tutorials/mnist/tensorflow/mnist_tf_keras.py | Python | mit | 7,276 |
from cuescience_shop.models import Client, Address, Order
from natspec_utils.decorators import TextSyntax
from cart.cart import Cart
from django.test.client import Client as TestClient
class ClientTestSupport(object):
def __init__(self, test_case):
self.test_case = test_case
self.client = TestClie... | cuescience/cuescience-shop | shop/tests/support/model_support.py | Python | mit | 1,689 |
# type command prints file contents
from lib.utils import *
def _help():
usage = '''
Usage: type (file)
Print content of (file)
Use '%' in front of global
vars to use value as file
name.
'''
print(usage)
def main(argv):
if len(argv) < 1 or '-h' in argv:
_help()
return
# The shell ... | nayas360/pyterm | bin/type.py | Python | mit | 1,002 |
# 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... | rwl/PyCIM | CIM14/IEC61970/OperationalLimits/ActivePowerLimit.py | Python | mit | 1,717 |
# Python - 2.7.6
to_freud = lambda sentence: ' '.join(['sex'] * len(sentence.split(' ')))
| RevansChen/online-judge | Codewars/8kyu/freudian-translator/Python/solution1.py | Python | mit | 91 |
def filename_directive(filename):
return "\t.file\t\"{0}\"\n".format(filename)
def compiler_ident_directive():
return "\t.ident\t\"{0}\"\n".format("HEROCOMP - Tomas Mikula 2017")
def text_directive():
return "\t.text\n"
def data_directive():
return "\t.data\n"
def quad_directive(arg):
return... | wilima/herocomp | herocomp/asm/Asm.py | Python | mit | 901 |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^$', 'tests.views.index'),
)
| codeinthehole/django-async-messages | tests/urls.py | Python | mit | 119 |
from flask import Flask, redirect, url_for, session, request, render_template_string, abort
import requests
import os
import ast
import base64
from nocache import nocache
#App config
ALLOWED_EXTENSIONS = set(['mp4'])
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.errorhandler(404)
@nocache
def error_40... | sharadbhat/Video-Sharing-Platform | Client/client.py | Python | mit | 36,232 |
import pytest
from bcbio.pipeline import rnaseq
@pytest.yield_fixture
def ericscript_run(mocker):
yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True)
@pytest.fixture
def sample():
return {
'config': {
'algorithm': {
'fusion_mode': True,
... | biocyberman/bcbio-nextgen | tests/unit/pipeline/test_rnaseq.py | Python | mit | 976 |
# TODO:
# 1. Fix broken functions
# 2. Network architecture changed, but functions need to use mask differently
# 3. Evaluation function
from __future__ import print_function
import cPickle as pickle
import sys
import time
from collections import OrderedDict
import numpy
import theano
import theano.tensor as tensor
... | bitesandbytes/upgraded-system | src/simple_5_lstm.py | Python | mit | 26,400 |
from django.shortcuts import render
from django.middleware.csrf import get_token
from ajaxuploader.views import AjaxFileUploader
from pandora.backends import SignalBasedLocalUploadBackend
from pandora.models import Item
def home(request):
return render(request, 'pandora/home.html', {
'items': Item.ob... | vrde/pandora | pandora/views.py | Python | mit | 458 |
#!/usr/bin/env python
import os
import re
from setuptools import find_packages, setup
def text_of(relpath):
"""
Return string containing the contents of the file at *relpath* relative to
this file.
"""
thisdir = os.path.dirname(__file__)
file_path = os.path.join(thisdir, os.path.normpath(rel... | python-openxml/python-docx | setup.py | Python | mit | 2,381 |
"""
Author: Junhong Chen
"""
from Bio import SeqIO
import gzip
import sys
import os
pe1 = []
pe2 = []
pname = []
for dirName, subdirList, fileList in os.walk(sys.argv[1]):
for fname in fileList:
tmp = fname.split(".")[0]
tmp = tmp[:len(tmp)-1]
if tmp not in pname:
pname... | macmanes-lab/MCBS913 | code/Junhong Chen/concatReads.py | Python | mit | 925 |
class Color:
''' print() wrappers for console colors
'''
def red(*args, **kwargs): print("\033[91m{}\033[0m".format(" ".join(map(str,args))), **kwargs)
def green(*args, **kwargs): print("\033[92m{}\033[0m".format(" ".join(map(str,args))), **kwargs)
def yellow(*args, **kwargs): print("\033[93m{}\033... | banderlog/greed | greed/colors.py | Python | mit | 370 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-23 22:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backups', '0001_initial'),
]
operations = [
migrations.RemoveField(
model... | Landver/netmon | apps/backups/migrations/0002_auto_20170424_0117.py | Python | mit | 737 |
###################################################################
# Numexpr - Fast numerical array expression evaluator for NumPy.
#
# License: MIT
# Author: See AUTHORS.txt
#
# See LICENSE.txt and LICENSES/*.txt for details about copyright and
# rights to use.
##########################################... | cpcloud/numexpr | numexpr/version.py | Python | mit | 855 |
# coding: utf-8
# # Preprocessing Notebook
#
# ### Author: James Foster, jmfoster@gmail.com
#
# #### Install gomill: http://mjw.woodcraft.me.uk/gomill/doc/0.7.4/install.html
# In[1]:
import numpy as np
import pandas as pd
from gomill import sgf
from gomill import ascii_boards
from gomill import sgf_moves
from IPy... | hotfuzzy/go | preprocessing.py | Python | mit | 11,844 |
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtim... | zellahenderson/PennApps2013 | src/prettydate.py | Python | mit | 1,307 |
'''
Pull one page of 100 results from seeclickfix using the global PARAMS
value if the parameters are not supplied. If there are more than 100
results, make another pull passing paramters that include the next page to
be pulled.
Nicole Donnelly 30May2016, updated 21Oct2016
'''
import requests
import json
def get_se... | nd1/women_in_tech_summit_DC2017 | api/seeclickfix_api.py | Python | mit | 2,074 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import argparse
import tensorflow as tf
from gym import wrappers
from yarll.environment.registration import make
class ModelRunner(object):
"""
Run an already learned model.
Currently only supports one variation of an environment.
"""
def __i... | arnomoonens/DeepRL | yarll/scripts/run_model.py | Python | mit | 2,858 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-25 15:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0012_auto_20160519_1740'),
]
operations = [
migrations.AddField(
... | bruecksen/isimip | isi_mip/pages/migrations/0013_formpage_button_name.py | Python | mit | 500 |
from __future__ import print_function
import argparse
from collections import OrderedDict
import json
import os
import logging
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac... | sergiooramas/tartarus | src/train.py | Python | mit | 27,751 |
from jinja2 import Template
import codecs
def render(file, props=None):
if props == None:
return '404'
with codecs.open('./views/' + file + '.html', 'r', encoding='utf8') as f:
content = f.read()
templated = Template(content).render(props)
return templated
| avocadoinnocenceproject/farflungfruit | render.py | Python | mit | 303 |
#!/usr/bin/env python3
from mathbind.types import BasicType
class BasicValueType(BasicType):
"""
Represents a basic pure type that can be passed by value, thus excluding arrays and pointers.
Attributes:
- typename (str): basic C typename (int, long long, unsigned, bool, etc)
- c_math_name (str): ... | diogenes1oliveira/mathbind | mathbind/types/basicvaluetype.py | Python | mit | 3,498 |
import os
from setuptools import setup
LONG_DESCRIPTION = """
A modular framework for mobile surveys and field data collection via offline-capable mobile web apps.
"""
def readme():
try:
readme = open('README.md')
except IOError:
return LONG_DESCRIPTION
else:
return readme.read()
... | wq/wq | setup.py | Python | mit | 2,538 |
# Retrieves all text files from CNAM ABU (see license here : http://abu.cnam.fr/cgi-bin/donner_licence) for further treatment
import urllib.request
import os
from bs4 import BeautifulSoup, SoupStrainer
# Proxy handling
proxies = {'http':''}
opnr = urllib.request.build_opener(urllib.request.ProxyHandler(proxies))
u... | Mandrathax/Entropy | Scripts/french_texts_dl.py | Python | mit | 2,276 |
#!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... | xmikos/soapy_power | soapypower/psd.py | Python | mit | 4,040 |
# This file starts the WSGI web application.
# - Heroku starts gunicorn, which loads Procfile, which starts manage.py
# - Developers can run it from the command line: python runserver.py
import logging
from logging.handlers import RotatingFileHandler
from app import create_app
app = create_app()
# Start a development... | dleicht/planx | manage.py | Python | mit | 559 |
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^sql/$', 'sqlparser.views.parse_sql'),
)
| slack-sqlbot/slack-sqlbot | slack_sqlbot/urls.py | Python | mit | 164 |
'''
Created by auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Ram20140214GetUserRequest(RestApi):
def __init__(self,domain='ram.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.AccountSpace = None
self.UserName = None
def getapiname(self):
return 'ram.aliyuncs.com.GetUse... | francisar/rds_manager | aliyun/api/rest/Ram20140214GetUserRequest.py | Python | mit | 334 |
class Paginator(object):
def __init__(self, collection, page_number=0, limit=20, total=-1):
self.collection = collection
self.page_number = int(page_number)
self.limit = int(limit)
self.total = int(total)
@property
def page(self):
start = self.page_number * ... | michaelcontento/whirlwind | whirlwind/view/paginator.py | Python | mit | 1,921 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP 9 soft forks.
Connect to a single node.
regtest lock-in with 108/144 block signalling
activa... | appop/bitcoin | qa/rpc-tests/bip9-softforks.py | Python | mit | 10,528 |
from contrib import *
import re
def tokenize(text):
tokens = re.findall('(?u)[\w.-]+',text)
tokens = [t for t in tokens if not re.match('[\d.-]+$',t)]
#tokens = [t for t in tokens if len(t)>2]
# TODO remove stopwords
return u' '.join(tokens)
## text = KV('data/text.db',5)
## tokens = KV('data/tokens.db',5)
text... | mobarski/sandbox | topic/tokens.py | Python | mit | 455 |
from ...plugin import hookimpl
from ..custom import CustomBuilder
from ..sdist import SdistBuilder
from ..wheel import WheelBuilder
@hookimpl
def hatch_register_builder():
return [CustomBuilder, SdistBuilder, WheelBuilder]
| ofek/hatch | backend/src/hatchling/builders/plugin/hooks.py | Python | mit | 229 |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import Submission
from .serializers import SubmissionSerializer
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from django.utils.decorators import method_deco... | wangzitian0/BOJ-V4 | submission/views.py | Python | mit | 2,454 |
#! /usr/bin/env python
"""
This programs plots the electronic coupling between two states.
It reads all Ham_*_im files and cache them in a tensor saved on disk.
Usage:
plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0
p = path to the hamiltonian files
s1 = state 1 index
s2 = state 2 index
dt = time step in fs
"""
i... | felipeZ/nonAdiabaticCoupling | scripts/hamiltonians/plot_couplings.py | Python | mit | 2,000 |
import ast
import traceback
import os
import sys
userFunctions = {}
renames = ['vex.pragma','vex.motor','vex.slaveMotors','vex.motorReversed']
classNames = []
indent = ' '
sameLineBraces = True
compiled = {}
def module_rename(aNode):
if aNode.func.print_c() == 'vex.pragma':
asC = '#pragma '
useComma =... | NoMod-Programming/PyRobotC | pyRobotC.py | Python | mit | 19,127 |
# -*- coding: utf-8 -*-
# from __future__ import (unicode_literals, nested_scopes, generators, division,
# absolute_import, with_statement, print_function)
import datetime
import math
class Funcionario(object):
def __init__(self, nome = "Albert", sobrenome = "Einstein", idade = 29, salari... | josecostamartins/pythonreges | aula10/funcionario.py | Python | mit | 1,679 |
""" This module provides a lexical scanner component for the `parser` package.
"""
class SettingLexer(object):
""" Simple lexical scanner that tokenizes a stream of configuration data.
See ``SettingParser`` for further information about grammar rules and
specifications.
Example Usage:... | xtrementl/focus | focus/parser/lexer.py | Python | mit | 9,227 |
from datetime import date
from workalendar.tests import GenericCalendarTest
from workalendar.asia import HongKong, Japan, Qatar, Singapore
from workalendar.asia import SouthKorea, Taiwan, Malaysia
class HongKongTest(GenericCalendarTest):
cal_class = HongKong
def test_year_2010(self):
""" Interestin... | sayoun/workalendar | workalendar/tests/test_asia.py | Python | mit | 17,173 |
import logging
from ask import alexa
import car_accidents
import expected_population
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
... | geoaxis/ask-sweden | ask_sweden/lambda_function.py | Python | mit | 3,656 |
def lucky_search(index, ranks, keyword):
urls = index.get(keyword)
if urls and ranks:
return max(urls, key = lambda x: ranks[x])
else:
return None
def ordered_search(index, ranks, keyword):
urls = index.get(keyword)
if urls and ranks:
return sorted(urls, key = lambda x: ranks[x])
else:
return None
| CrazyWearsPJs/minimalist_web_crawler | src/search.py | Python | mit | 314 |
# 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 ... | Azure/azure-sdk-for-python | sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration/azure/mgmt/kubernetesconfiguration/v2021_03_01/operations/_operations.py | Python | mit | 4,985 |
from django.shortcuts import render
from rest_framework import viewsets
from basin.models import Task
from basin.serializers import TaskSerializer
def index(request):
context = {}
return render(request, 'index.html', context)
def display(request):
state = 'active'
if request.method == 'POST':
... | Pringley/basinweb | basin/views.py | Python | mit | 1,780 |
"""
This module allows you to mock the config file as needed.
A default fixture that simply returns a safe-to-modify copy of
the default value is provided.
This can be overridden by parametrizing over the option you wish to
mock.
e.g.
>>> @pytest.mark.parametrize("extension_initial_dot", (True, False))
... def test_f... | INCF/pybids | bids/conftest.py | Python | mit | 1,063 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This module defines how cells are stored as tunacell's objects
"""
from __future__ import print_function
import numpy as np
import warnings
import treelib as tlib
from tunacell.base.observable import Observable, FunctionalObservable
from tunacell.base.datatools impo... | LeBarbouze/tunacell | tunacell/base/cell.py | Python | mit | 15,188 |
# -*- coding: utf-8 -*-
import scrapy
import numpy
import quandl
from mykgb import indicator
from myapp.models import Quandlset
from mykgb.items import MykgbItem
quandl.ApiConfig.api_key = "taJyZN8QXqj2Dj8SNr6Z"
quandl.ApiConfig.api_version = '2015-04-09'
class QuandlDataSpider(scrapy.Spider):
name = "quandl_dat... | back1992/mezzanine-api-docker | web/mykgb/spiders/quandl_data.py | Python | mit | 2,840 |
def settings(request):
"""
Add settings (or some) to the templates
"""
from django.conf import settings
tags = {}
tags['GOOGLE_MAPS_KEY'] = settings.GOOGLE_MAPS_KEY
tags['GOOGLE_ANALYTICS_ENABLED'] = getattr(settings, 'GOOGLE_ANALYTICS_ENABLED', True)
tags['MAP_PROVIDER'] = settings.M... | JustinWingChungHui/electionleaflets | electionleaflets/apps/core/context_processors.py | Python | mit | 467 |
from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... | NUKnightLab/slackdice | app.py | Python | mit | 1,779 |
# coding=utf-8
"""
desc: 错误处理handler
author: congqing.li
date: 2016-10-28
"""
from werkzeug.exceptions import HTTPException
class CustomError(HTTPException):
code = None
description = "NIMABI"
def __init__(self, description=None, response=None):
if isinstance(description, tuple):
... | levi-lq/flask-vue-example | api_rest/error_handlers.py | Python | mit | 669 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "radiocontrol.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Simon-Hohberg/Pi-Radio | radiocontrol/manage.py | Python | mit | 255 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import hashlib
from django.utils import six
URL_LIST_CACHE = 'powerpages:url_list'
SITEMAP_CONTENT = 'powerpages:sitemap'
def get_cache_name(prefix, name):
"""
Cache name constructor. Uses the same methods as django cache system
... | Open-E-WEB/django-powerpages | powerpages/cachekeys.py | Python | mit | 1,418 |
# -*- coding: utf-8 -*-
__author__ = 'Sergey Sobko'
class HashSet(object):
_set_dict = None
def __init__(self):
self._set_dict = dict()
def add(self, key, value):
self._set_dict[hash(key)] = value
def get(self, key):
return self._set_dict.get(hash(key))
def __repr__(se... | profitware/python-sandbox-algo | sandboxalgo/sets.py | Python | mit | 861 |
import pyglet
import tkinter
WINDOW_WIDTH = 800 # x
WINDOW_HEIGHT = 600 # y
LEVEL = 6 # original was 4
X_SIZE = 2 * LEVEL
Y_SIZE = 3 * LEVEL
def get_resolution():
root = tkinter.Tk()
return root.winfo_screenwidth(), root.winfo_screenheight()
def get_position(x, y):
return ((x // X_SIZE) * X_SIZE, ... | celestian/simCTC | sctc.py | Python | mit | 2,726 |
import re
import numpy as np
from scipy import ndimage, spatial
import bresenham
import mpl_tools
import vtk_tools
def load_pdb(name):
with open(name+'.pdb') as fp:
points = []
conns = []
for line in fp:
if line.startswith('HET'):
pattern = r'(-?\d+.\d\d\d)'... | RodericDay/CIF-characterize | characterize.py | Python | mit | 2,124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.