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 |
|---|---|---|---|---|---|
#!/usr/bin/env python
"""
--------------------------------------------------------------------------------
Created: Jackson Lee 11/4/14
This script reads in a tab delimited file of annotations and queries
asynchronously the MGRAST REST API to parse back the original ncbi tax_id entry.
This script then uses the ncb... | leejz/meta-omics-scripts | query_ncbi_lineage_from_mgrast_md5.py | Python | mit | 8,172 |
"""Implementation of Pearson collaborative filtering algorithm"""
from math import sqrt, pow
from mlcollection.lib.collaborativefiltering.collaborativefilterbase import \
AbstractCollaborativeFilter
from operator import itemgetter
from scipy import stats, isnan
__author__ = 'Paul Osborne <osbpau@gmail.com>'
class... | posborne/mlcollection | mlcollection/lib/collaborativefiltering/pearson.py | Python | mit | 3,340 |
from django.shortcuts import render
from django.utils.translation import activate
def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# context = {'latest_question_list': latest_question_list}
# activate('pt-br')
# print(request.LANGUAGE_CODE)
context = {}
re... | torchmed/torchmed | torchmed/views.py | Python | mit | 364 |
# for accessing babusca library.
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import smatrix
import scattering
import g1
import g2
import generators
| georglind/babusca | examples/context.py | Python | mit | 209 |
from setuptools import setup, find_packages
with open('pyluno/meta.py') as f:
exec(f.read())
setup(
name='pyluno',
version=__version__,
packages=find_packages(exclude=['tests']),
description='A Luno API for Python',
author='Cayle Sharrock/Grant Stephens',
author_email='grant@stephens.co.za'... | grantstephens/pyluno | setup.py | Python | mit | 1,485 |
import re
from django.db.models import fields
from django.template.defaultfilters import slugify
def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'):
slug_field = instance._meta.get_field(slug_field_name)
slug_len = slug_field.max_length
# Sort out the initial s... | underlost/GamerNews | gamernews/apps/news/fields.py | Python | mit | 3,543 |
import _plotly_utils.basevalidators
class VsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="vsrc", parent_name="cone", **kwargs):
super(VsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwa... | plotly/python-api | packages/python/plotly/plotly/validators/cone/_vsrc.py | Python | mit | 426 |
# -*- coding: utf-8 -*-
""" hmacHash.py
Implemention of Request for Comments: 2104
HMAC: Keyed-Hashing for Message Authentication
HMAC is a mechanism for message authentication
using cryptographic hash functions. HMAC can be used with any
iterative cryptographic hash function, e.g., MD5, SHA-1, i... | TheDSCPL/SSRE_2017-2018_group8 | Projeto/Python/cryptopy/crypto/keyedHash/hmacHash.py | Python | mit | 3,613 |
from __future__ import absolute_import
import six
if six.PY3:
from unittest import TestCase, mock
else:
import sys
if sys.version_info < (2, 7, 0):
from unittest2 import TestCase
else:
from unittest import TestCase
import mock
from BacklogPy.base import BacklogBase
class TestBa... | koxudaxi/BacklogPy | tests/backlog/test_base.py | Python | mit | 3,123 |
# http://stackoverflow.com/questions/13202799/python-code-geometric-brownian-motion-whats-wrong
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.1
sigma = 0.1
S0 = 10
dt = 0.01
alpha = 0.1
N = round(T/dt)
t = np.linspace(0, T, N)
W = np.random.standard_normal(size = N)
W = np.cumsum(W)*np.sqrt(dt) ### s... | laputian/dml | test/bm_stacko_1_1.py | Python | mit | 489 |
import mock
import lxml.etree as ET
from .utils import make_cobertura
def test_parse_path():
from pycobertura import Cobertura
xml_path = 'foo.xml'
with mock.patch('pycobertura.cobertura.os.path.exists', return_value=True):
with mock.patch('pycobertura.cobertura.ET.parse') as mock_parse:
... | msabramo/pycobertura | tests/test_cobertura.py | Python | mit | 7,957 |
import time
from usb_vendor import PIC_USB
import traceback
# Product IDs: Master PIC is 0x0004, Rocket PIC is 0x0005, Barge PIC is 0x0006
comms = PIC_USB(0x0005)
def main():
print("START")
loop_time = .2 # How often to run the main loop, in seconds
while True:
start_time = time.clock()
# ... | RyanEggert/space-lander | rocket_control/printvals.py | Python | mit | 3,261 |
# coding: utf-8
# python 3.5
import Orange
from orangecontrib.associate.fpgrowth import *
import pandas as pd
import numpy as np
import sys
import os
from collections import defaultdict
from itertools import chain
from itertools import combinations
from itertools import compress
from itertools import product
from sklea... | gingi99/research_dr | python/FPgrowth/orange_fpgrowth.py | Python | mit | 10,802 |
#!/usr/bin/env python
"""
pitchanalysis.py
--
Christopher Kuech
cjkuech@gmail.com
--
Requires:
Python 2.7
Instructions:
python pitchanalysis.py [wav-file-name]
"""
import matplotlib
from math import log
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.fig... | chriskuech/wavelab | pitchanalysis.py | Python | mit | 5,174 |
from distutils.core import setup
setup(
name='Bioloid',
version='0.1.0',
author='Dave Hylands',
author_email='dhylands@gmail.com',
packages=['bioloid'],
scripts=[],
url='http://pypi.python.org/pypi/Bioloid/',
license='LICENSE',
description='Provides access to bioloid devices.',
... | dhylands/Bioloid | setup.py | Python | mit | 432 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pxmarkerdialog.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PxMarkerDialog(object):
def setupUi(self, PxMarkerDialog):
... | mohikhsan/px-labeler | px-labeler/pxgui/ui_pxmarkerdialog.py | Python | mit | 2,812 |
import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointe... | wnavarre/email-dictator | web/run_on.py | Python | mit | 1,802 |
# -*- coding:utf-8 -*-
# 使用 UTF-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import sys
from heap import Heap
class Rectangle(object):
"""docstring for Rectangle"""
def __init__(self, dimension, entry=None):
super(Rectangle, self).__init__()
self.dimension = dimension
se... | zegra1989/pytree | rtree.py | Python | mit | 14,094 |
# -*- coding:utf-8 -*-
from ...errors.httpbadrequestexception import HttpBadRequestException
import saklient
# module saklient.cloud.errors.dnsaaaarecordnotfoundexception
class DnsAaaaRecordNotFoundException(HttpBadRequestException):
## 不適切な要求です。対応するAAAAレコードが見つかりません。
## @param {int} status
# @param ... | hnakamur/saklient.python | saklient/cloud/errors/dnsaaaarecordnotfoundexception.py | Python | mit | 688 |
"""Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novar... | DeppSRL/open_bilanci | bilanci_project/bilanci/settings/staging.py | Python | mit | 1,991 |
#!/usr/bin/env python3
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_sheets_django.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason.... | chuck1/web_sheets | old/web_sheets_django/manage.py | Python | mit | 822 |
import os
from os import path
import sqlite3
from .link import Link
class Links(object):
def __init__(self):
self._links = {}
def add(self, link):
self._links[link.url] = link
def find_by_tag(self, tag):
return [link for link in self._links.values() if tag in link.tags]
def... | angelsanz/linkstore | linkstore/links.py | Python | mit | 6,633 |
"""
Django settings for dts_test_project 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... | sigma-geosistemas/django-tenants | dts_test_project/dts_test_project/settings.py | Python | mit | 3,048 |
#!/usr/bin/env python
"""
Jedi EPC server.
Copyright (C) 2012 Takafumi Arakaki
Author: Takafumi Arakaki <aka.tkf at gmail.com>
This file is NOT part of GNU Emacs.
Jedi EPC server 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 So... | kyon-bll/.dotfiles | .emacs.d/elpa/jedi-core-20191011.1750/jediepcserver.py | Python | mit | 15,847 |
from django.conf import settings
BACKENDS = getattr(settings, 'FAIREPART_BACKENDS', (
'fairepart.backends.facebook.FacebookBackend',
'fairepart.backends.google.GoogleOAuth2Backend',
))
RELATION_LIST_PAGINATE_BY = getattr(settings, 'FAIREPART_RELATION_LIST_PAGINATE_BY', 5)
GOOGLE_APP_NAME = getattr(settings,... | thoas/django-fairepart | fairepart/settings.py | Python | mit | 354 |
from frasco.ext import *
from frasco.assets import expose_package, register_assets_builder
from frasco.utils import join_url_rule
from flask import render_template
import os
import json
import re
import htmlmin
import codecs
class FrascoAngular(Extension):
name = "frasco_angular"
defaults = {"static_dir": Non... | frascoweb/frasco | frasco/angular/__init__.py | Python | mit | 5,809 |
""" Configuration for Flask app """
import os
import urllib
from flask import (Flask, abort, flash, Response)
from playhouse.flask_utils import FlaskDB
ADMIN_PASSWORD = 'secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
DATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db')
DEBUG = False
SECRET_... | econne01/flask_blog | app/app.py | Python | mit | 1,579 |
# Notes on classes
class Sample():
def __init__(self, name, number):
self.name = name
self.number = number
def print_values(self):
print(f"name: {self.name}")
print(f"number: {self.number}")
class SampleWithProperties():
def __init__(self, name, number)... | daveinnyc/various | python-practice/class_demos.py | Python | mit | 3,833 |
#!/usr/bin/env python3
# Copyright (c) 2015-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.
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and... | thelazier/dash | contrib/devtools/security-check.py | Python | mit | 8,242 |
#!/usr/bin/env python
#
# Machine Description Interface C API
#
# This software is delivered under the terms of the MIT License
#
# Copyright (c) 2016 STMicroelectronics
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Softwar... | guillon/mdi | examples/mini/scripts/generate_executions.py | Python | mit | 3,906 |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(setup_requires=['pbr'],
pbr=True,
test_suite="")
| CloudNiner/fadds-parser | setup.py | Python | mit | 122 |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, "Webluker")
| cflq3/getcms | plugins/Webluker_cdn.py | Python | mit | 127 |
# """Django Actions Log settings file."""
#
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
CREATE = 100
SUCCESS = 110
ACTIVATE = 130
AUTH = 150
VIEW = 180
UPDATE = 200
SUSPEND = 250
UNSUSPEND = 260
DELETE = 300
TERMINATE = 500
FAILED =... | shtalinberg/django-actions-logger | actionslog/settings.py | Python | mit | 910 |
# -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
import unittest
from pycmbs.icon import Icon
class TestPycmbsIcon(unittest.TestCase):
def setUp(self):
# requires local installation of ICON sample files... | pygeo/pycmbs | pycmbs/tests/test_icon.py | Python | mit | 1,061 |
#!/usr/bin/env python
"""Docstring."""
import re
from functools import reduce
from collections import Counter
from common import get_input
class SSLTester:
"""."""
def __init__(self, input_list=[]):
"""Initialize."""
self.input_list = input_list
def find_aba(self, seq):
"""Retu... | tlake/advent-of-code | 2016/day07_internet_protocol_version_7/python/src/part2.py | Python | mit | 2,010 |
import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
ins... | rahulg/eulerswift | setup.py | Python | mit | 1,487 |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.Emai... | pythonkr/pyconkr-2014 | pyconkr/forms.py | Python | mit | 1,760 |
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... | mandrive/FlaskTest | __init__.py | Python | mit | 2,578 |
#
# Copyright IBM Corp. 2014
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | vetlehjelmtvedt/TranscriptApp | sttClient.py | Python | mit | 13,934 |
import uuid
from random import randint
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Url
def index(request):
if request.session.has_key("has_url"):
url = request.session.get("has_url")
del request.session['has_url']
return render(req... | luisalves05/shortener-url | src/apps/miudo/views.py | Python | mit | 1,890 |
from .tables import Base, Component, Mixture, Ref, Measurement, Listing, Property
from .utils import get_or_create
__all__ = ['Base', 'Component', 'Mixture', 'Ref', 'Measurement', 'Listing', 'Property', 'get_or_create']
| Hariri-Institute-SAIL/materials | materials/db/__init__.py | Python | mit | 221 |
import tornado.web
import tornado.ioloop
import os
from handlers import *
urls = [
(r'/', IndexHandler),
(r'/api/(?P<action>[a-zA-Z0-9-_]+)', ApiServiceHandler),
(r'/about', AboutHandler),
]
settings = {
"static_path" : os.path.join(os.path.dirname(__file__), "static"),
"template_path" : os... | plusplus7/EasyMemo2 | server.py | Python | mit | 666 |
from __future__ import absolute_import
import logging
try:
from redis import Redis
from rq import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: que... | APSL/kaneda | kaneda/queues/rq.py | Python | mit | 1,504 |
"""
.. module:: radical.pilot.controller.pilot_launcher_worker
.. moduleauthor:: Ole Weidner <ole.weidner@rutgers.edu>
"""
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
from unit_manager_controller import UnitManagerController
from pilot_manager_controller import PilotManage... | JensTimmerman/radical.pilot | src/radical/pilot/controller/__init__.py | Python | mit | 462 |
class MiddlewareMixin(object):
def __init__(self, get_response=None):
super(MiddlewareMixin, self).__init__()
| rollbar/pyrollbar | rollbar/contrib/django/utils.py | Python | mit | 122 |
from json import JSONDecodeError
from flask import Blueprint, Flask, make_response, Response
from flask_cors import CORS
from google.appengine.api import wrap_wsgi_app
from werkzeug.routing import BaseConverter
from backend.api.handlers.district import (
district_events,
district_list_year,
district_ranki... | the-blue-alliance/the-blue-alliance | src/backend/api/main.py | Python | mit | 10,215 |
import _plotly_utils.basevalidators
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="legendgroup", parent_name="choropleth", **kwargs):
super(LegendgroupValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_n... | plotly/plotly.py | packages/python/plotly/plotly/validators/choropleth/_legendgroup.py | Python | mit | 412 |
#!/usr/bin/env python
from distutils.core import setup
execfile('modlunky/version.py')
with open('requirements.txt') as requirements:
required = requirements.read().splitlines()
kwargs = {
"name": "modlunky",
"version": str(__version__),
"packages": ["modlunky"],
"scripts": ["bin/modlunky"],
... | gmjosack/modlunky | setup.py | Python | mit | 1,002 |
# -*- coding: utf-8 -*-
import datetime
import nose
from nose.tools import assert_equal
from pyomni.object.task import OmniTask
class TestOmniTask(object):
def test_get_xml(self):
return
if __name__ == '__main__':
nose.main(argv=['nosetests', '-s', '-v'], defaultTest=__file__)
| taxpon/pyomni | tests/object/test_task.py | Python | mit | 299 |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 CNRS
# 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 ... | grantjenks/pyannote-core | pyannote/core/__init__.py | Python | mit | 1,810 |
from .fcn import FCN
| ellisdg/3DUnetCNN | unet3d/models/pytorch/fcn/__init__.py | Python | mit | 21 |
import numpy as np
def zero_mean_normalize_image_data(data, axis=(0, 1, 2)):
return np.divide(data - data.mean(axis=axis), data.std(axis=axis))
def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5):
data = np.copy(data)
if data.ndim == channel_dim or data... | ellisdg/3DUnetCNN | unet3d/utils/normalize.py | Python | mit | 7,176 |
from django.template.base import Library
from django.core.urlresolvers import reverse
from projects.models import ProjectBuild
register = Library()
@register.simple_tag()
def build_url(build_id):
"""
Fetches the ProjectBuild for a given build_id, if any.
"""
try:
build = ProjectBuild.object... | timrchavez/capomastro | projects/templatetags/projects_tags.py | Python | mit | 543 |
from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rott... | walidsa3d/shaman | shaman/providers/api.py | Python | mit | 951 |
"""Access and control log capturing."""
import logging
import os
import re
import sys
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from typing import AbstractSet
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing ... | nicoddemus/pytest | src/_pytest/logging.py | Python | mit | 29,805 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-18 06:21
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('CareerTinder', '0004_auto_20160918_0152'),
]
operations = [
migrations.RenameField(... | sarojaerabelli/HVGS | CareerTinderServer/CareerTinder/migrations/0005_auto_20160918_0221.py | Python | mit | 573 |
# Database
DB_NAME = 'censusreporter_ke'
DB_USER = 'censusreporter_ke'
DB_PASSWORD = 'censusreporter_ke'
| callmealien/wazimap_zambia | censusreporter/api/config.py | Python | mit | 106 |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import bcrypt
class BCryptPassword(object):
def __init__(se... | mic4ael/indico | indico/util/passwords.py | Python | mit | 2,145 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pesapal.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| nickaigi/django-pesapal | manage.py | Python | mit | 257 |
import os
from appdirs import AppDirs
class Config:
def __init__(self):
self.app_dir = get_app_dir()
def save_geometry(self, window):
path = os.path.join(self.app_dir, 'geometry.conf')
print(path)
with open(path, "w") as conf:
conf.write(window.geometry())
de... | bsiegfreid/tkdraw | tkdraw/config.py | Python | mit | 859 |
import json
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError
from .exceptions import SparkPostAPIException
class TornadoTransport(object):
@gen.coroutine
def request(self, method, uri, headers, **kwargs):
if "data" in kwargs:
kwargs["body"] = kwargs.pop("d... | thonkify/thonkify | src/lib/sparkpost/tornado/base.py | Python | mit | 1,048 |
#!C:\Python27\python.exe
# Filename: GenericBytecode.py
# -*- coding: utf-8 -*-
import os
import Settings
'''
Generic Bytecode
Simply add, remove or modify bytecode for use in KHMS
'''
createFrame = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1',
'iconst_1', 'iadd', 'putfield', 'il... | injectnique/KnuckleHeadedMcSpazatron | GenericBytecode.py | Python | mit | 46,794 |
# -*- coding: utf-8 -*-
import unittest
from activity_feed import ActivityFeed
class UtilityTest(unittest.TestCase):
def test_key(self):
'should return the correct key for the non-aggregate feed'
a = ActivityFeed()
self.assertEquals(a.feed_key('david'), 'activity_feed:david')
def tes... | simonz05/activity-feed | tests/test_utility.py | Python | mit | 886 |
# Copyright (c) 2016-2017 The OrarioTreniBot Authors (see AUTHORS)
#
# 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, cop... | MarcoBuster/OrarioTreniBot | src/updates/global_messages.py | Python | mit | 3,165 |
import sys, datetime, os, time
from mcstatus import MinecraftServer
# GLOBALS
# List containing all the mcstatus server objects
serverList = []
# appendLog() polls the server for population data and appends it to the log
# In: The hostname and population of a server, as well as the timestamp for its retrieval time
# ... | IronJew/mc-pop-log | poplog.py | Python | mit | 1,647 |
import django_filters
from django.contrib.auth.models import Group
from apps.authentication.models import OnlineUser as User
class PublicProfileFilter(django_filters.FilterSet):
year = django_filters.NumberFilter(field_name="year", method="filter_year")
group = django_filters.CharFilter(method="filter_group"... | dotKom/onlineweb4 | apps/profiles/filters.py | Python | mit | 728 |
from project_cron.utils import processutil
def open(app_name):
script = '''
if application "%s" is not running then
tell application "%s" to activate
end if
''' % (app_name, app_name)
processutil.call(['/usr/bin/osascript', '-e', script])
def close(app_name):
script ... | ecleya/project_cron | project_cron/utils/apputil.py | Python | mit | 424 |
# Copyright: Luis Pedro Coelho <luis@luispedro.org>, 2012-2018
# License: MIT
import numpy as np
def read_roi(fileobj):
'''
points = read_roi(fileobj)
Read ImageJ's ROI format
Parameters
----------
fileobj: should be a file-like object
Returns
-------
points: a list of points
... | luispedro/imread | imread/ijrois.py | Python | mit | 3,061 |
import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="showticklabels", parent_name="heatmap.colorbar", **kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/heatmap/colorbar/_showticklabels.py | Python | mit | 446 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'ByStudent'
def zhanzhuanxc(p,q,e):
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def mod... | ByStudent666/XsCrypto | XsCrypto/zhanzhuanxc.py | Python | mit | 592 |
def hsd_inc_beh(rxd, txd):
'''|
| Specify the behavior, describe data processing; there is no notion
| of clock. Access the in/out interfaces via get() and append()
| methods. The "hsd_inc_beh" function does not return values.
|________'''
if rxd.hasPacket():
data = rxd.get() + 1
... | hnikolov/pihdf | examples/hsd_inc/src/hsd_inc_beh.py | Python | mit | 340 |
""" Implementation of WaterFrame.plot_bar(key, ax=None, average_time=None)"""
import datetime
def plot_timebar(self, keys, ax=None, time_interval_mean=None):
"""
Make a bar plot of the input keys.
The bars are positioned at x with date/time. Their dimensions are given by height.
Parameters
... | rbardaji/oceanobs | mooda/waterframe/plot/plot_timebar.py | Python | mit | 2,204 |
import unittest, uuid
from nixie.core import Nixie, KeyError
class NixieErrorsTestCase(unittest.TestCase):
def test_read_missing(self):
nx = Nixie()
self.assertIsNone(nx.read('missing'))
def test_update_missing(self):
nx = Nixie()
with self.assertRaises(KeyError):
nx.update('missing')
de... | eiri/nixie | tests/test_nixie_errors.py | Python | mit | 579 |
#!/usr/bin/env python3
"""CnbetaApi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.h... | kagenZhao/cnBeta | CnbetaApi/CnbetaApi/urls.py | Python | mit | 847 |
from key_vault_agent import KeyVaultAgent
class SecretsAgent(KeyVaultAgent):
def get_secret(self):
self.data_client.restore_secret()
pass
| schaabs/sandbox | net/sandbox.keyvault/python/repl/secrets.py | Python | mit | 160 |
from c2cgeoportal_admin.views.layertree import itemtypes_tables
itemtypes_tables.update({
'lu_int_wms': 'lux_layer_internal_wms',
'lu_ext_wms': 'lux_layer_external_wms',
})
| Geoportail-Luxembourg/geoportailv3 | geoportal/geoportailv3_geoportal/admin/admin.py | Python | mit | 178 |
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
>>> get_ip_address('lo')
'127.0.0.1'
>>> get... | ActiveState/code | recipes/Python/439094_get_IP_address_associated_network_interface/recipe-439094.py | Python | mit | 357 |
import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... | Eylesis/Botfriend | Cogs/GameTime.py | Python | mit | 1,883 |
#!/usr/bin/env python
import unittest
import logging
import logging.config
import sys
import argparse
DESCRIPTION="""
Harness for tests in the cloaca/tests/ directory.
Run all tests with '--all' or provide a list dotted names
of specific tests (eg. legionary.TestLegionary.test_legionary).
"""
# Set up logging. See l... | mhmurray/cloaca | cloaca/test/tests.py | Python | mit | 3,034 |
import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
t = SimpleTable(self, 10,2)
t.pack(side="top", fill="x")
t.set(0,0,"Hello, world")
class SimpleTable(tk.Frame):
def __init__(self, parent, rows=10, columns=2):
# use black background ... | rajarahulray/iDetector | tests_and_ References/table_view_text_box.py | Python | mit | 1,160 |
"""
Franca abstract syntax tree representation.
"""
from abc import ABCMeta
from collections import OrderedDict
class ASTException(Exception):
def __init__(self, message):
super(ASTException, self).__init__()
self.message = message
def __str__(self):
return self.message
class Pack... | zayfod/pyfranca | pyfranca/ast.py | Python | mit | 15,502 |
#!/usr/bin/env python
"""
Test code for blackjack game. Tests can be run with py.test or nosetests
"""
from __future__ import print_function
from unittest import TestCase
from card_games import blackjack
from card_games.blackjack import BlackJack
print(blackjack.__file__)
class TestRule(TestCase):
def setUp(se... | sampathweb/game_app | card_games/test/test_blackjack.py | Python | mit | 917 |
"""Automabot bot for Discord."""
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='automabot',
version='0.0.1.dev20170604', # see PEP... | WyllVern/AutomaBot | setup.py | Python | mit | 1,602 |
"""
Base classes for writing management commands (named commands which can
be executed through ``tipi.py``).
"""
import os
import sys
from ConfigParser import ConfigParser
from optparse import make_option, OptionParser
from virtualenv import resolve_interpreter
class CommandError(Exception):
"""
Exception cl... | unbracketed/tipi | tipi/commands/base.py | Python | mit | 12,932 |
from keras.models import Sequential
from keras.layers import LSTM
import numpy as np
model = Sequential()
ly = LSTM(2, activation='tanh', recurrent_activation='relu',implementation = 1, stateful=False, batch_input_shape=(5, 3, 3))
model.add(ly)
model.compile(optimizer='sgd', loss='mse')
kernel = np.ones((3, 8))
rec_k... | adamtiger/NNSharp | PythonUtils/LSTM.py | Python | mit | 994 |
"""
[2015-04-01] Challenge #208 [Intermediate] ASCII Gradient Generator
https://www.reddit.com/r/dailyprogrammer/comments/3104wu/20150401_challenge_208_intermediate_ascii/
# [](#IntermediateIcon) _(Intermediate)_: ASCII Gradient Generator
A linear colour gradient is where an image transitions through a range of colou... | DayGitH/Python-Challenges | DailyProgrammer/DP20150401B.py | Python | mit | 9,284 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0019_remove_article_ordering_featured'),
]
operations = [
migrations.RemoveField(
model_name='article... | F483/trainlessmagazine.com | article/migrations/0020_remove_article_issue.py | Python | mit | 366 |
" tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... | convexengineering/gplibrary | gpkitmodels/SP/aircraft/tail/tail_boom_flex.py | Python | mit | 1,453 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script can generate automate scripts for open source python project.
Scroll to ``if __name__ == "__main__":`` for more info.
"""
from __future__ import print_function
import sys
import datetime
from os import walk, mkdir
from os.path import join, abspath, dirnam... | MacHu-GWU/elementary_math-project | start-a-project/init_project.py | Python | mit | 3,304 |
"""
WSGI config for mozblog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Django... | renancamm/mozblog | mozblog/wsgi.py | Python | mit | 483 |
from configparser import ConfigParser
import v20
# Create an object config
config = ConfigParser()
# Read the config
config.read("../API_Connection_Oanda/pyalgo.cfg")
ctx = v20.Context(
'api-fxpractice.oanda.com',
443,
True,
application = 'sample_code',
token = config['oanda_v20']['access_token'],... | cgomezfandino/Project_PTX | API_Connection_Oanda/PTX_oandaInfo.py | Python | mit | 972 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Stat',
fields=[
('id', models.AutoField(verbose... | mtskelton/huawei-4g-stats | stats/migrations/0001_initial.py | Python | mit | 718 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# pipe.py
#
# Copyright 2014 Giorgio Gilestro <gg@kozak>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the Licen... | ggilestro/majordomo | listeners/pipe.py | Python | mit | 2,193 |
from jsbuild.attrdict import AttrDict
from time import strftime
class Manifest(AttrDict):
def __init__(self,*args,**kwargs):
super(AttrDict, self).__init__(*args,**kwargs)
self._buffer_ = None
self._parent_ = None
if not self.__contains__('_dict_'):
self['_dict_'] = {}
self['_dict_']... | azer/jsbuild | jsbuild/manifest.py | Python | mit | 673 |
import os
from io import open
from setuptools import setup
about = {}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'stringsheet', '__init__.py'), encoding='utf-8') as f:
for line in f:
if line.startswith('__'):
(key, value) = line.split('=')
about[... | Tunous/StringSheet | setup.py | Python | mit | 977 |
# Copyright (c) 2012 <Jaume Devesa (jaumedevesa@gmail.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 limitation the rights
# to use, copy, modi... | jdevesa/gists | gists/gists.py | Python | mit | 12,061 |
# -*- coding: utf-8 -*-
import unittest
from linked_list import (delete_node, list_cycle, remove_elements,
reverse_list)
from public import ListNode
class TestLinkedList(unittest.TestCase):
def test_delete_node(self):
so = delete_node.Solution()
head = ListNode(1)
... | lycheng/leetcode | tests/test_linked_list.py | Python | mit | 2,549 |
import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... | pascalgutjahr/Praktikum-1 | Fourier/rechteck.py | Python | mit | 1,202 |
# -*- coding: utf-8 -*-
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Job class for FormBruter module
"""
from class... | hack4sec/ws-cli | classes/jobs/FormBruterJob.py | Python | mit | 479 |
# 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-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_gateway_connection_list_entity_py3.py | Python | mit | 7,889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.