code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^project/', include('project.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
... | na/django-metatags | project/urls.py | Python | mit | 533 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blogg', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
... | ishahid/django-blogg | source/blogg/migrations/0002_comment.py | Python | mit | 1,206 |
from .path import Path
class Morphism(object):
def __init__(self, arrows):
self.arrows = arrows
def __call__(self, domain):
codomain = {}
for arrow in self.arrows:
codomain = arrow.apply(domain, codomain)
return codomain
@classmethod
def compile(cls, *exp... | cieplak/morf | morf/morphism.py | Python | mit | 2,478 |
import gamerocket
from flask import Flask, request, render_template
app = Flask(__name__)
gamerocket.Configuration.configure(gamerocket.Environment.Development,
apiKey = "your_apiKey",
secretKey = "your_secretKey")
... | workbandits/gamerocket-python-guide | 1_create_player/src/app.py | Python | mit | 837 |
#-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit... | bjorncooley/rainforest_makers | spirit/models/topic_notification.py | Python | mit | 4,847 |
user_input = raw_input()
class Taowa:
def __init__(self):
return
def setSize(self, m1, m2):
self.width = m1
self.height = m2
self.area = m1 * m2
class Sorter:
def __init__(self):
self.taowas = []
self.lastWidth = 0
self.lastHeight = 0
return... | zxgaoray/calculate_play | calculator/Taowa.py | Python | mit | 1,409 |
from django.views.generic.detail import DetailView
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.views.generic.edit import DeleteView, CreateView, UpdateView
fr... | acdh-oeaw/vhioe | entities/views.py | Python | mit | 5,608 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0004_make_focal_point_key_not_nullable'),
('wagtailcore', '0008_populate_latest_revision_created_at'),
]
op... | morgan-county/site | morgan/apps/cms/migrations/0001_initial.py | Python | mit | 2,452 |
"""
Methods to get certain kinds of data from the Github API.
Writes each repo's data to a separate file in a given directory
"""
import json
from mimetools import Message
from StringIO import StringIO
from github_util import *
import time
import sys, os
#####
# CONSTANTS
#####
#constants to specify parameters when ... | IanOlin/github-research | Scraping/repo_info.py | Python | mit | 6,716 |
#!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
... | lightningwolf/Flask-JqueryUiBootstrap | SAMPLE_PROJECT/wtf-app.py | Python | mit | 1,192 |
"""
Edge/Node Weighted Watersheds
====================================
Compare edge weighted watersheds
and node weighted on a grid graph.
"""
####################################
# sphinx_gallery_thumbnail_number = 5
from __future__ import print_function
import nifty.graph
import skimage.data
import skimage.segmen... | DerThorsten/nifty | src/python/examples/graph/plot_undirected_grid_graph_watersheds.py | Python | mit | 3,725 |
"""Contributed 'recipes'"""
| alisaifee/flask-limiter | flask_limiter/contrib/__init__.py | Python | mit | 28 |
import re
from versions.software.utils import get_command_stdout, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return '7-Zip'
def installed_version():
"""Return the installed version of 7-Zip, or None if not installed."""
try:
version_string =... | mchung94/latest-versions | versions/software/sevenzip.py | Python | mit | 718 |
#sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing ... | mwweinberg/NYC-MTA-Next-Train | archive/nycmta.py | Python | mit | 5,929 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nukebox2000 documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... | k1nk33/NukeBox2000 | docs/conf.py | Python | mit | 8,447 |
import platform
import socket
import sys
import os
from mule_local.JobGeneration import *
from mule.JobPlatformResources import *
from . import JobPlatformAutodetect
# Underscore defines symbols to be private
_job_id = None
def get_platform_autodetect():
"""
Returns
-------
bool
True if curren... | schreiberx/sweet | mule/platforms/50_himmuc/JobPlatform.py | Python | mit | 4,801 |
from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def curve(data, name="", smooth=True, trid=True):
"""
... | geoscript/geoscript-py | geoscript/plot/curve.py | Python | mit | 991 |
# -*- coding: utf-8 -*-
"""
syslog2irc.main
~~~~~~~~~~~~~~~
:Copyright: 2007-2015 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from itertools import chain
from .announcer import create_announcer
from .processor import Processor
from .router import replace_channels_with_channel_names, Router
from... | Emantor/syslog2irc | syslog2irc/main.py | Python | mit | 2,540 |
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import re
import poetryutils2
# this is all for use within ipython
def sample_words():
lines = poetryutils2.utils.debug_lines()
words = list()
for l in lines:
words.extend(w.lower() for w in l.split())
... | cmyr/poetryutils2 | tests/realness_tests.py | Python | mit | 1,555 |
from __future__ import unicode_literals
from collections import OrderedDict
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.text import slugify
from django.db import models
from decimal import Decimal
# Create your models here.
@python_2_unicode_compati... | IQSS/miniverse | dv_apps/installations/models.py | Python | mit | 3,541 |
#
# Package analogous to 'threading.py' but using processes
#
# multiprocessing/__init__.py
#
# This package is intended to duplicate the functionality (and much of
# the API) of threading.py but uses processes instead of threads. A
# subpackage 'multiprocessing.dummy' has the same API but is a simple
# wrapper for 't... | perkinslr/pypyjs | addedLibraries/multiprocessing/__init__.py | Python | mit | 7,835 |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | EmanueleCannizzaro/scons | test/toolpath/VariantDir.py | Python | mit | 2,582 |
# (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... | jonhadfield/ansible-lookups | aws_rds_endpoint_port_from_instance_name.py | Python | mit | 1,218 |
from pylons_common.lib.log import create_logger
from pylons_common.lib.utils import pluralize
logger = create_logger('pylons_common.lib.datetime')
from datetime import datetime, timedelta
DATE_FORMAT_ACCEPT = [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%SZ', u'%Y-%m-%d', u'%m-%d-%Y', u'%m/%d/%Y', u'%m.%d.%Y', u'%b %d, %... | benogle/pylons_common | pylons_common/lib/date.py | Python | mit | 3,799 |
from etvnet_service import EtvnetService
from plex_config import PlexConfig
class PlexVideoService(EtvnetService):
def __init__(self):
config_name = Core.storage.abs_path(Core.storage.join_path(Core.bundle_path, 'Contents', 'etvnet.config'))
config = PlexConfig(config_name)
EtvnetService._... | shvets/Etvnet.bundle | Contents/Code/plex_video_service.py | Python | mit | 342 |
#!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l)... | isi-nlp/bolinas | common/hgraph/amr_corpus_reader.py | Python | mit | 4,973 |
import hypertrack
hypertrack.secret_key = 'c237rtyfeo9893u2t4ghoevslsd'
customer = hypertrack.Customer.create(
name='John Doe',
email='john@customer.com',
phone='+15555555555',
)
print(customer)
| hypertrack/hypertrack-python | example.py | Python | mit | 211 |
from datetime import date, datetime, timedelta
from itertools import chain
from operator import attrgetter
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.db.models import Q, get_app
from django.http i... | hbussell/pinax-tracker | apps/milestones/views.py | Python | mit | 10,170 |
"""
__MT_post__Par.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: gehan
Modified: Sun Feb 15 10:31:27 2015
______________________________________________________________________
"""
from ASGNode import *
from ATOM3Type import *
... | levilucio/SyVOLT | UMLRT2Kiltera_MM/MT_post__Par.py | Python | mit | 9,121 |
"""DICOM Upper Layer Protocol Data Units (PDUs).
There are seven different PDUs:
- A_ASSOCIATE_RQ
- A_ASSOCIATE_AC
- A_ASSOCIATE_RJ
- P_DATA_TF
- A_RELEASE_RQ
- A_RELEASE_RP
- A_ABORT_RQ
::
from_primitive encode
+----------------+ ------> +------------+ -----> +-------------+
... | scaramallion/pynetdicom3 | pynetdicom/pdu.py | Python | mit | 68,107 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib import script
import random
rand = random.randint
def warp_uptown_east(pc):
result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp")
if result == 1:
script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン
elif result == 2:
... | twinpa/virtualeco | script/site_packages/warp_event.py | Python | mit | 6,364 |
#!/usr/bin/env python
#coding: utf-8
"""
This module simply sends request to the Digital Ocean API,
and returns their response as a dict.
"""
import requests
API_ENDPOINT = 'https://api.digitalocean.com'
class DoError(RuntimeError):
pass
class DoManager(object):
def __init__(self, client_id, api_key):
... | chuwy/dopy | dopy/manager.py | Python | mit | 9,514 |
# coding: utf8
from prov.model import ProvBundle, Namespace, Literal, PROV, XSD, Identifier
import datetime
def primer_example():
# https://github.com/lucmoreau/ProvToolbox/blob/master/prov-n/src/test/resources/prov/primer.pn
#===========================================================================
# d... | pymonger/prov-0.5.4 | prov/model/test/examples.py | Python | mit | 17,487 |
# 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/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/models/_models.py | Python | mit | 848,302 |
raise NotImplementedError("markupbase is not yet implemented in Skulpt")
| ArcherSys/ArcherSys | skulpt/src/lib/markupbase.py | Python | mit | 73 |
# -*- coding: utf-8 -*-
"""
:Copyright: 2007-2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
from __future__ import unicode_literals
from unittest import TestCase
from nose2.tools import params
from syslog2irc.irc import Channel
class IrcChannelTestCase(TestCa... | Emantor/syslog2irc | tests/test_irc_channel.py | Python | mit | 791 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: omi
# @Date: 2014-08-24 21:51:57
# @Last Modified by: omi
# @Last Modified time: 2015-08-02 20:57:35
'''
网易云音乐 Ui
'''
import hashlib
import re
import curses
import terminalsize
from api import NetEase
from scrollstring import scrollstring, truelen
from stora... | Catofes/musicbox | NEMbox/ui.py | Python | mit | 23,861 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "iamhhb.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | graycarl/iamhhb | manage.py | Python | mit | 812 |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from smserver import models
from smserver import smutils
from smserver.chathelper import with_color
from smserver.chatplugin import ChatPlugin
from smserver.models import ranked_chart
from smserver.models.ranked_chart import Diffs
class ChatHelp(ChatPlugin):
command... | Nickito12/stepmania-server | smserver/chat_commands/general.py | Python | mit | 14,861 |
__author__ = 'brandon.corfman'
# Global constants used across the application.
AVERAGED_OVER_ALL_AZIMUTHS = -1
AVERAGED_ON_NON_ZERO_AVS = 0
BY_AZIMUTH = 1
GYPSY_PINK = (0.6745, 0.196, 0.3882) # color coveted by JJS; used for blast volumes
WHITE = (1.0, 1.0, 1.0)
CMPID, R1, R2, R3, Z1, Z2 = range(6)
| bcorfman/stage | const.py | Python | mit | 301 |
# --------------------------------------------------------------------------------- #
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
... | ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/agw/rulerctrl.py | Python | mit | 57,819 |
from __future__ import absolute_import
from __future__ import division
from builtins import object
from past.utils import old_div
from proteus import *
from proteus.default_p import *
import os
try:
from .parameters_for_poisson import *
except:
from parameters_for_poisson import *
name = "poisson"
assert ct.nd... | erdc/proteus | proteus/tests/BernsteinPolynomials/poisson_eqn/poisson_p.py | Python | mit | 3,313 |
# Generated by Django 3.0.7 on 2020-09-27 13:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('edegal', '0025_photographer_flickr_handle'),
]
operations = [
migrations.CreateModel(
... | conikuvat/edegal | backend/larppikuvat/migrations/0001_initial.py | Python | mit | 1,162 |
# -*- coding: utf-8 -*-
import pickle
import sqlite3
import threading
from abc import ABCMeta, abstractmethod
from collections import namedtuple
InternalEvent = namedtuple(
'InternalEvent',
('identifier', 'state_change_id', 'block_number', 'event_object'),
)
# TODO:
# - snapshots should be used to reduce the... | tomashaber/raiden | raiden/transfer/log.py | Python | mit | 9,715 |
import contextlib
from uuss.server import model
from lolapps.common import uums
from lolapps.util import json
import os
import simplejson
import struct
import time
try:
# Try importing the C++ extension version
import uuss_pb
except:
# The dynamic python version will automatically be used
pass
from uus... | brianr/uuss | proto.py | Python | mit | 17,229 |
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
import profiles.urls
import accounts.urls
from . import views
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^users/', include(profile... | Zedmor/powerball | src/powerball/urls.py | Python | mit | 852 |
import graph
from depth_first_search import depth_first_search
from breadth_first_search import breadth_first_search
edges = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (2, 6),
(2, 7), (3, 8), (3, 9), (4, 10), (4, 11)]
G, _ = graph.create_graph(edges)
start_vertex = G.get_vertex(0)
breadth = breadth_fi... | Sorrop/py-graph-algorithms | traversal_tests.py | Python | mit | 1,800 |
import pdb
class TimingDiagram:
def print_diagram(self, xtsm_object):
pdb.set_trace()
seq = xtsm_object.XTSM.getActiveSequence()
cMap=seq.getOwnerXTSM().getDescendentsByType("ChannelMap")[0]
#channelHeir=cMap.createTimingGroupHeirarchy()
#channelRes=cMap.findTiming... | gemelkelabs/timing_system_software | server_py_files/utilities/timing_diagram.py | Python | mit | 5,170 |
from rest_framework import status
from rest_framework.authtoken.models import Token
from django.utils.translation import ugettext_lazy as _
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAUL... | aaronn/django-rest-framework-passwordless | tests/test_verification.py | Python | mit | 8,084 |
# -*- coding: utf-8 -*-
from __future__ import division
import matplotlib.pyplot as plt
import random
import numpy as np
class Player:
def __init__(self, state, q):
self.state = state
self.gain_matrix = np.array([[q, 0], [0, 1-q]])
def action_distribution(self, N, m, players)... | TanaPanda/contagion | circle_network_0.py | Python | mit | 2,084 |
#!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... | litecoinz-project/litecoinz | qa/rpc-tests/keypool.py | Python | mit | 4,852 |
import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = ra... | kevinwuhoo/randomcolor-py | tests/test_randomcolor_visual.py | Python | mit | 2,617 |
from utils import instrument
from azove.utils import recursive_int_to_big_endian
import mock
@given(u'a packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_packet('this is a test packet')
@when(u'peer.send_packet is called') # noqa
def step_impl(context):
context.peer.send_packe... | elkingtowa/azove | features/steps/peer.py | Python | mit | 12,702 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smarturl.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the... | ioiogoo/SmartUrl | manage.py | Python | mit | 806 |
'''
Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import pandas as pd
import pylab as plt
import matplotlib as mpl
from matplotlib.cm import *
import os,sys;home=os.path.expanduser('~') +'/'
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']... | airanmehr/bio | Scripts/TimeSeriesPaper/Plot/DirectvsRNN.py | Python | mit | 1,198 |
"""
The MIT License (MIT)
Copyright (c)2013 Rich Friedel
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, ... | rf3Studios/anatomy_calc_python | anatomy_calc/lec_func.py | Python | mit | 4,209 |
# Copyright 2015 David Wang. All rights reserved.
# Use of this source code is governed by MIT license.
# Please see LICENSE file
# WebSpark
# Spark web service demo
# version 0.2
# use REPL or define sc SparkContext
import urllib2, urllib
import math
import time
import traceback
# Spark Web Application demo wi... | mdavid8/WebSpark | spark_webservice_demo.py | Python | mit | 1,997 |
import types
from sikwidgets.region_group import RegionGroup
from sikwidgets.util import to_snakecase
from sikwidgets.widgets import *
def gen_widget_method(widget_class):
def widget(self, *args, **kwargs):
return self.create_widget(widget_class, *args, **kwargs)
return widget
class Window(RegionGroup... | griffy/sikwidgets | sikwidgets/window.py | Python | mit | 3,281 |
def b():
print("hooora!")
dic1 = {1: 2, 1: 4}
for i in dic1.items():
if 'a' == i:
b()
else:
break
print ":(" | amiraliakbari/sharif-mabani-python | by-session/ta-922/j6/a1.py | Python | mit | 136 |
#!/usr/bin/env python
# pylint: disable=invalid-name
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import sys
from problembaseclass import ProblemBaseCl... | jakubczaplicki/projecteuler | problem005.py | Python | mit | 1,000 |
import quickfix
import copy
import uuid
import random
import datetime
import yaml
from twisted.internet import task
from sim import (FixSimError, FixSimApplication, create_fix_version,
instance_safe_call, create_logger, IncrementID, load_yaml)
class Subscription(object):
def __init__(self, symbo... | gloryofrobots/fixsim | fixsim/client.py | Python | mit | 9,845 |
#-*- coding: utf-8 -*-
#既存のフロールールを全て一旦削除
#それらのフロールールで指定していたMatchにIPアドレス情報(サブネット)を追加
#mitigate時はなんでもPacket-Inするルールは不要なので削除したまま
#mitigate後はなんでもPacket-Inするルールから突っ込んでいく
import logging
import socket
import struct
import ipaddress
#packet_in_handlerにて、受け取ったパケットのipv4がsubnetに属するか調べるのに必要
def is_ipv4_belongs_to_network(ipv4, n... | tukeJonny/NTPAmpMitigator | infra/utils.py | Python | mit | 960 |
from sklearn.utils import resample
from darts.api.dataset import Subset
def dummy_indices(dataset):
""" Get indexes for the dataset """
return [x for x in range(len(dataset))]
def sample(dataset, num_samples, replace=True):
""" Sample the dataset """
data_idx = dummy_indices(dataset)
sample_idx ... | ECP-CANDLE/Benchmarks | common/darts/datasets/sample.py | Python | mit | 420 |
__author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in... | Meemaw/Eulers-Project | Problem_37.py | Python | mit | 888 |
import subprocess
from pkg_resources import resource_filename
def playit(file):
"""
Function used to play a sound file
"""
filepath = resource_filename(__name__, 'sound/' + file)
subprocess.Popen(["paplay", filepath])
| lapisdecor/bzoinq | bzoinq/playit.py | Python | mit | 240 |
from os import getenv
from time import time, sleep
from core import Platform, Instance
from SoftLayer import Client
from SoftLayer.CCI import CCIManager
from paramiko import SSHClient
class _SuppressPolicy(object):
def missing_host_key(self, client, hostname, key):
pass
class CCIPlatform(Platform):
... | softlayer/stack-dev-tools | platforms/softlayer.py | Python | mit | 4,908 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "news_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that... | julienawilson/news-project | news_project/manage.py | Python | mit | 810 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) The University of Strathclyde 2019
# Author: Leighton Pritchard
#
# Contact:
# leighton.pritchard@strath.ac.uk
#
# Leighton Pritchard,
# Strathclyde Institute of Pharmaceutical and Biomedical Sciences
# The University of Strathclyde
# Cathedral Street
# Glasgow
# G1 1... | widdowquinn/pyani | pyani/pyani_graphics/sns/__init__.py | Python | mit | 9,274 |
"""goto_cloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | jdepoix/goto_cloud | goto_cloud/urls.py | Python | mit | 767 |
from __future__ import with_statement
import sys
from collections import deque
from charpos import CharposStream
from bindings import bindings
import printervars
__all__ = ["PrettyPrinter", "pprint"]
class PrintLevelExceeded(StopIteration):
pass
class Token(object):
"""Base class for prettyprinter tokens.
... | plotnick/prettyprinter | prettyprinter.py | Python | mit | 13,549 |
from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Course.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_POST
def addCourseCurriculum(request):
respon... | IEEEDTU/CMS | Course/views/CourseCurriculum.py | Python | mit | 2,775 |
import logging
import requests
import slacksocket.errors as errors
log = logging.getLogger('slacksocket')
class WebClient(requests.Session):
""" Minimal client for connecting to Slack web API """
def __init__(self, token):
self._token = token
super(WebClient, self).__init__()
def get(sel... | graywizardx/slacksocket | slacksocket/webclient.py | Python | mit | 1,363 |
'''Tests for the ValidateHash object'''
from __future__ import absolute_import
import unittest
from nose.tools import assert_true, assert_false
from hashit.core.hash_data import HashData
from hashit.core.hash_type import HashType
from hashit.service.validate_hash import ValidateHash
from hashit.utils.data_encap impo... | art-of-dom/hash-it | test/test_validate_hash.py | Python | mit | 4,257 |
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# -*- mode: python; indent-tabs-mode nil; tab-width 4; python-indent 4; -*-
"""
usage: gidget add data <filename>
gidget add reference <filename>
"""
from docopt import docopt
if __name__ == '__main__':
print(docopt(__doc__))
| cancerregulome/gidget | gidget/gidget_add.py | Python | mit | 300 |
# coding=utf-8
from re import match
from mapi.exceptions import (
MapiNetworkException,
MapiNotFoundException,
MapiProviderException,
)
from mapi.utils import clean_dict, request_json
__all__ = [
"omdb_search",
"omdb_title",
"tmdb_find",
"tmdb_movies",
"tmdb_search_movies",
"tvdb_... | jkwill87/mapi | mapi/endpoints.py | Python | mit | 13,575 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'CustomUser.email_on_new_foller'
db.delete_column('auth_user', 'email_on_new_foller')
... | reverie/jotleaf.com | jotleaf/main/migrations/0003_auto__del_field_customuser_email_on_new_foller__add_field_customuser_e.py | Python | mit | 16,495 |
"""Add user table to support doorman and oauth authentication.
Revision ID: 0bc0a93ac867
Revises: fd28e46e46a6
Create Date: 2016-05-11 11:01:40.472139
"""
# revision identifiers, used by Alembic.
revision = '0bc0a93ac867'
down_revision = 'fd28e46e46a6'
from alembic import op
import sqlalchemy as sa
import doorman.d... | mwielgoszewski/doorman | migrations/versions/0bc0a93ac867_.py | Python | mit | 1,141 |
"""This module contains the ``list_user`` command."""
import click
from ovmm.handlers.postgres import PostgreSQLDatabaseHandler
@click.command()
def list_user():
"""List users managed by ovmm."""
click.echo('\n{:-^60}'.format(' Process: List Users '))
postgres = PostgreSQLDatabaseHandler()
user_lis... | tobiasraabe/otree_virtual_machine_manager | ovmm/commands/list_user.py | Python | mit | 484 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. module:: ellipse_fitting
:platform: Unix, Windows
:synopsis: Ellipse fitting algorithms and handling of ellipse information.
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2013-05-05, 23:22
"""
from __future__ import division
from __future_... | hbldh/b2ac | b2ac/fit/reference.py | Python | mit | 7,871 |
#!/usr/bin/env python
#
# eppy documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | santoshphilip/eppy | docs/conf.py | Python | mit | 4,834 |
#!/usr/bin/env python
"""
This script sends confirmation messages to recently registered users.
It should be run periodically so that users receive a registration
confirmation link soon after they have registered.
rbp@isnomore.net
"""
import smtplib
from email.message import Message
from . db import Connection
fr... | rbp/auth | mailer.py | Python | mit | 1,655 |
# -*- coding: utf-8 -*-
# Release information about mse
version = '1.0'
# description = "Your plan to rule the world"
# long_description = "More description about your plan"
# author = "Your Name Here"
# email = "YourEmail@YourDomain"
# copyright = "Copyright 2011 - the year of the Rabbit"
# Of it's open source, you... | jinmingda/MicroorganismSearchEngine | mse/release.py | Python | mit | 449 |
a = "python"
print(a*2)
try:
print(a[-10])
except IndexError as e:
print("인덱스 범위를 초과 했습니다.")
print(e)
print(a[0:4])
print(a[1:-2])
# -10은 hi뒤로 10칸
print("%-10sjane." % "hi")
b = "Python is best choice."
print(b.find("b"))
print(b.find("B"))
try:
print(b.index("B"))
except ValueError as e:
prin... | JaeGyu/PythonEx_1 | 20170106.py | Python | mit | 455 |
from unittest import TestCase
# from unittest import mock
from mwclient import Site
from bookhelper import ExistingBook
from . import PageMock, SiteMock, TESTBOOK1_TXT
#Site.login=mock.MagicMock(return_value=True)
class TestInit(TestCase):
def setUp(self):
self.site = SiteMock()
def test_book(self... | theithec/bookhelper | bookhelper/tests/test_init.py | Python | mit | 741 |
"""All forms for the extension."""
from django.forms import ModelForm
from .models import WebResource
class WebResourceForm(ModelForm):
"""Form for a single web resource."""
class Meta:
"""Form meta."""
model = WebResource
fields = ('name', 'description', 'url', 'colour', 'symbol')... | ExCiteS/geokey-webresources | geokey_webresources/forms.py | Python | mit | 321 |
import logging
from django.conf import settings
from mock_api.http_utils import make_request
logger = logging.getLogger(__name__)
def run_api_endpoint_callbacks(api_endpoint):
responses = []
for api_callback in api_endpoint.callbacks.all():
logger.debug("Make callback: %s", api_callback)
re... | marcin-bakowski-dev/rest-api-mock-server | mock_rest_app/mock_api/callbacks.py | Python | mit | 710 |
"""
Classes::
VASPData -- A collection of functions that wrap bash code to extract
data from VASP output into managable .dat (.txt) files.
"""
import numpy as np
from subprocess import call, check_output
from ast import literal_eval
class VASPData(object):
"""
A collection of functions that wrap bash c... | mmb90/dftintegrate | dftintegrate/fourier/vaspdata.py | Python | mit | 3,878 |
import unittest
from GUI.PopUps.FileHandlerPopUp import FileHandlerPopUp
from Constants.FileHandlingMode import *
class TestFileHandlingPopUp(unittest.TestCase):
def setUp(self):
self.title = "test"
self.callbackbuttontext = "button"
self.path = "test_path"
self.filters = ["*.jpg", ... | RemuTeam/Remu | project/tests/GUI/PopUps/test_file_handling_popup.py | Python | mit | 4,820 |
# Generated by Django 2.2.1 on 2019-06-10 19:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registration', '0003_limbomember_mother_tongue'),
]
operations = [
migrations.RenameModel(
old_name='LimboMember',
new_name=... | Teknologforeningen/teknologr.io | teknologr/registration/migrations/0004_auto_20190610_2250.py | Python | mit | 350 |
import os
import pytest
@pytest.fixture(scope='session')
def testdata():
"""
Simple fixture to return reference data
:return:
"""
class TestData():
def __init__(self):
self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
def fn(self, fn):
... | miroag/mfs | tests/conftest.py | Python | mit | 516 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_protein_motif_encoder
----------------------------------
Tests for `protein_motif_encoder` module.
"""
import pandas as pd
import pytest
from click.testing import CliRunner
import cli
def test_command_line_interface():
runner = CliRunner()
result = runn... | tbrittoborges/protein_motif_encoder | tests/test_protein_motif_encoder.py | Python | mit | 597 |
from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging ... | isidroamv/netmiko | netmiko/linux/linux_ssh.py | Python | mit | 3,207 |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="scatter.unselected.textfont", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_n... | plotly/python-api | packages/python/plotly/plotly/validators/scatter/unselected/textfont/_color.py | Python | mit | 470 |
from flask import (Blueprint, current_app as app,
g, request, make_response,
jsonify, session)
from ..models import ModelError, Session
from ..models.post import Post, Draft, PostOperator
from .helpers import (require_int, JumpDirectly)
api_bp = Blueprint('api', __name__)
post_o... | ptpt/taoblog | taoblog/views/api.py | Python | mit | 7,738 |
"""
Represents protected content
"""
from django.conf.urls import url
from django.http import HttpResponse
def testview(request):
return HttpResponse()
urlpatterns = [url(r"^$", testview, name="test_url_content")]
| kavdev/dj-stripe | tests/apps/testapp_content/urls.py | Python | mit | 220 |
from flask import current_app, redirect, url_for, request, session, flash, send_file
from flask.ext import restful
from flask.ext.login import login_required, current_user, login_user, logout_user
import twitter
from request_parsers import *
from datetime import datetime
from models import *
from rauth.service import O... | airwoot/timeline-hack-core | app/resources.py | Python | mit | 7,302 |
#!/usr/bin/python
""" README
This script is deprecated. Please use https://github.com/device42/servicenow_device42_mapping
This script reads CIs from Servicenow and uploads them to Device42.
It has 2 modes:
1. Full migration - when the TIMEFRAME is set to 0
2. Synchronization - when the TIMEFRAME... | device42/servicenow_to_device42_sync | starter.py | Python | mit | 2,360 |
# -*- coding: utf-8 -*-
import os
import ntpath
import glob
from pyhammer.tasks.taskbase import TaskBase
from pyhammer.utils import execProg
class MakeNugetPackageTask(TaskBase):
"""Make Nuget Package Task"""
def __init__( self, csProjectPath, solutionDir, tempDir, publishDir, visualStudioVersion = "12.0" ):
... | webbers/pyhammer | pyhammer/tasks/helpers/makenugetpackagetask.py | Python | mit | 1,540 |
"""add-hikes
Revision ID: f7888bd46c75
Revises: 820bb005f2c5
Create Date: 2017-02-16 07:36:06.108806
"""
# revision identifiers, used by Alembic.
revision = 'f7888bd46c75'
down_revision = 'fc92ba2ffd7f'
from alembic import op
import sqlalchemy as sa
import geoalchemy2
def upgrade():
### commands auto generate... | thusoy/blag | blag/migrations/versions/f7888bd46c75_add_hikes.py | Python | mit | 1,664 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import unittest
class OpenCCTest(unittest.TestCase):
def setUp(self):
self.openCC = OpenCC()
def test_hk2s(self):
self.openCC.set_conversion('hk2s')
words = '香煙(英語:Cigarette),為煙草製品的一種。滑鼠是一種很常見及常用的電腦輸入設備。'
sel... | jokerYellow/TranslateFiles | test/conversion_test.py | Python | mit | 4,082 |