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
import sys import re import numpy as np from keras.models import Sequential from keras.layers import Dense, TimeDistributed, Dropout, Activation, LSTM, BatchNormalization from keras.optimizers import RMSprop, Adam from keras.layers.advanced_activations import LeakyReLU from keras.utils import np_utils #from seq2seq.mod...
b29308188/Deep-Generative-Model-for-Text-Data
src/basic_sentiment.py
Python
mit
8,591
#!/usr/bin/env python # -*- coding: utf-8 -*- """""" import tkinter as tk from tkinter import ttk # link __title__ = "BoundButton" __version__ = "1.0.3" __author__ = "DeflatedPickle" class BoundButton(ttk.Button): """ -----DESCRIPTION----- A ttk Button that can be bound to any key to run any fu...
DeflatedPickle/pkinter
pkinter/boundbutton.py
Python
mit
1,967
XXXXXXXXX XXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXX X XXXXXX XXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX...
dnaextrim/django_adminlte_x
adminlte/static/plugins/datatables/extensions/ColVis/examples/button_order.html.py
Python
mit
16,631
# -*- coding: utf-8 -*- # from .common import * class SignalCatchException(Exception): pass def raise_on_enter(**kwargs): raise SignalCatchException(kwargs) class SignalsTest(TestCase): def tearDown(self): signals.interpret_enter.disconnect(raise_on_enter) signals.interpret_leave.dis...
dgk/django-business-logic
tests/test_signals.py
Python
mit
1,402
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-09 12:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djangocms_tonicdev', '0002_tonicnotebookpluginmodel_name'), ] operations = [ ...
TigerND/djangocms-tonicdev
djangocms_tonicdev/migrations/0003_auto_20160509_1538.py
Python
mit
546
''' dsift.py: this function implements some basic functions that does dense sift feature extraction. The descriptors are defined in a similar way to the one used in Svetlana Lazebnik's Matlab implementation, which could be found at: http://www.cs.unc.edu/~lazebnik/ Yangqing Jia, jiayq@eecs.berkeley.edu ''' import num...
NicoRahm/CGvsPhoto
Textures/dsift.py
Python
mit
7,772
#!/usr/bin/env python # Encoding: UTF-8 """Part of qdex: a Pokédex using PySide and veekun's pokedex library. A query models for pokémon """ from PySide import QtGui, QtCore Qt = QtCore.Qt class PokemonDelegate(QtGui.QStyledItemDelegate): """Delegate for a Pokémon Shows summary information when the group o...
encukou/qdex
qdex/delegate.py
Python
mit
2,413
import smtplib from decimal import Decimal from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group as DjangoGroup, GroupManager as _GroupManager, Permission, PermissionsMixin, ) from...
jwinzer/OpenSlides
server/openslides/users/models.py
Python
mit
12,597
""" utilities for testing """ def setup_environ(**kwargs): """ setup basic wsgi environ""" environ = {} from wsgiref.util import setup_testing_defaults setup_testing_defaults(environ) environ.update(kwargs) return environ def make_env(path_info, script_name): """ set up basic wsgi enviro...
aodag/WebDispatch
webdispatch/testing.py
Python
mit
523
def sequence_results(): return None
ActiveLearningLab/funtool-ipro-processes
funtool_ipro_processes/reporters/sequence_reporter.py
Python
mit
41
""" Summary: Ief file data holder. Contains the functionality for loading ISIS .ief files from disk. Author: Duncan Runnacles Created: 01 Apr 2016 Copyright: Duncan Runnacles 2016 TODO: Updates: """ import os from ship.utils import utilfunctions as uf from ship.utils i...
duncan-r/SHIP
ship/fmp/ief.py
Python
mit
11,467
"""Views for the monitoring app.""" from django.contrib.auth.decorators import login_required from django.db.models import Count from django.http import Http404 from django.utils.decorators import method_decorator from django.views.generic import ListView, TemplateView from .register import monitor class MonitoringV...
bitmazk/django-monitoring
monitoring/views.py
Python
mit
2,525
# -*- coding: utf-8 -*- import numpy as np import numpy.random as random # 设置随机数种子 random.seed(42) # 产生一个1x3,[0,1)之间的浮点型随机数 # array([[ 0.37454012, 0.95071431, 0.73199394]]) # 后面的例子就不在注释中给出具体结果了 random.rand(1, 3) # 产生一个[0,1)之间的浮点型随机数 random.random() # 下边4个没有区别,都是按照指定大小产生[0,1)之间的浮点型随机数array random...
qiudebo/13learn
code/stat/stat_random.py
Python
mit
1,303
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" " MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline") def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(m...
aurzenligl/prophy
prophyc/generators/prophy.py
Python
mit
5,118
from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.utils.timezone import now from shelf.models import BookItem # Create your models here. class Rental(models.Model): who = models.ForeignKey(User) what = models.ForeignKey(BookItem) when = models...
KredekPth/Kurs_django
rental/models.py
Python
mit
564
import aiohttp def example_processor(): # extends processor from gen_scraperV2 async def route(scrape_bundle): pass return route
puddl3glum/gen_scraper
example/example_processor.py
Python
mit
158
from collections import namedtuple import numpy as np def get_energybins(config='IC86.2012'): """Function to return analysis energy bin information Parameters ---------- config : str, optional Detector configuration (default is 'IC86.2012'). Returns ------- energybins : namedtup...
jrbourbeau/cr-composition
comptools/binning.py
Python
mit
5,322
import pygame import sys from psistatsrd.app import App def create_queue_row(data, config): mem_graph = create_mem_graph(config) cpu_graph = create_cpu_graph(config) scroll_text = [] title = [] if type(data['ipaddr']).__name__ == "list": scroll_text = scroll_text + data['ipaddr'] el...
alex-dow/psistatsrd
psistatsrd/utils/drawable.py
Python
mit
2,757
"""Morphological filters. The following work on 2D arrays. They wrap the relevant scipy functions. The ones provided by skimage are not well documented for now. """ from scipy.ndimage import morphology def closing(parameters): """Calculates morphological closing of a greyscale image. This is equal to perfo...
cpsaltis/pythogram-core
src/gramcore/filters/morphology.py
Python
mit
3,722
import json import copy formtable = {"name":[u'name'], "gender":[u'gender'], "contact":[u'contact'], "address":[u'address']} def is_reserved_layer(dict,reserved_word): for key in dict: if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]: ...
Reimilia/Privacy_Server
resources/common/json_parser.py
Python
mit
8,021
import os import aiofiles async def get_line(name, offset=0, sep=b'\r\n', chunk_size=4096): name = os.path.abspath(name) async with aiofiles.open(name, 'r+b') as f: await f.seek(offset) tmp_line = b"" chunk = await f.read(chunk_size) while chunk: if len(tmp_line): ...
stavinsky/lsshipper
lsshipper/reader_aio.py
Python
mit
777
# encoding: utf-8 '''XML support. ''' import logging from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError from smisk.core import Application try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: ...
rsms/smisk
lib/smisk/serialization/xmlbase.py
Python
mit
4,263
""" Advanced Examples ================= In this section, we demonstrate how to go from the inner product to the discrete approximation for some special cases. We also show how all necessary operators are constructed for each case. """ #################################################### # # Import Packages # -...
simpeg/discretize
tutorials/inner_products/4_advanced.py
Python
mit
6,674
import numpy as np from subprocess import call #this readies the data for svm data_folder_path = '../data/' file_names = ['test'] word_embedding_size = 50 # read the vectors.bin file and create a map vec_dict = {} # vec_file = open ('vectors.bin', 'r') # create vectors and counts for f in file_names: with open (...
mawri/sswe-team9
src/prepare_svm_data.py
Python
mit
3,249
import PyQt4.QtGui as QG import PyQt4.QtCore as QC def chunk(seq, size): for i in xrange(0, len(seq), size): yield seq[i:i+size] class TextSysTray(object): def __init__(self, parent, text, ntray=2, **kwargs): self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)] self._curr_...
knowitnothing/btcx
gui/qt/systray.py
Python
mit
1,337
def fac(n): if n == 0: return 1 else: return n * fac(n-1) def smallfacs(T): for t in xrange(T): print fac(int(raw_input())) if __name__ == "__main__": smallfacs(int(raw_input()))
jamtot/HackerEarth
Problems/Small Factorials/smlfc.py
Python
mit
213
BLACKLISTS_MAPPING = { 'blacklists_add': { 'resource': 'blacklists/add.json', 'docs': 'https://disqus.com/api/docs/blacklists/add/', 'methods': ['POST'], }, 'blacklists_list': { 'resource': 'blacklists/list.json', 'docs': 'https://disqus.com/api/docs/blacklists/list/'...
marctc/tapioca-disqus
tapioca_disqus/resource_mapping/blacklists.py
Python
mit
533
import sys from antZoo.gossip import GossipServiceHandler server = GossipServiceHandler.Server( sys.argv[1] ) server.serve()
streed/antZoo
test_server.py
Python
mit
126
#!/usr/bin/python # Load required modules import sys, os, json, re, time, comet as C, multiprocessing as mp, random from math import exp import run_comet_simple as RC def get_parser(): # Parse arguments import argparse description = 'Runs CoMEt on permuted matrices.' parser = argparse.ArgumentParser(d...
raphael-group/comet
run_comet_full.py
Python
mit
10,224
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Exercise the wallet backup code. Ported from walletbackup.sh. Test case is: 4 nodes. 1 2 and 3 send...
navcoindev/navcoin-core
qa/rpc-tests/walletbackup.py
Python
mit
7,262
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
timj/scons
test/SConscript/Return.py
Python
mit
2,480
import simpy import datetime import random from datetime import timedelta end_of_time = 60*60*24*365 def working_hours(current_time): return current_time.hour < 17 and current_time.hour > 8 def linear_increase(now, min_duration, max_duration): time_left = end_of_time - now return min_duration + max_duration * ...
neilb14/featurewise
scripts/generate_usage.py
Python
mit
2,293
# -*- coding: utf-8 -*- __author__ = "Sal Aguinaga" __copyright__ = "Copyright 2015, The Phoenix Project" __credits__ = ["Sal Aguinaga", "Rodrigo Palacios", "Tim Weninger"] __license__ = "GPL" __version__ = "0.1.0" __maintainer__ = "Sal Aguinaga" __email__ = "saguinag (at) nd dot edu" import json import argparse,trac...
abitofalchemy/ScientificImpactPrediction
analyze_altmetric.py
Python
mit
1,802
import os import numpy as np def get_last_folder_id(folder_path): t = 0 for fn in os.listdir(folder_path): t = max(t, int(fn)) return t def movingaverage(values, window): weights = np.repeat(1.0, window)/window sma = np.convolve(values, weights, 'valid') return sma ...
avalcarce/gym-learn
utils.py
Python
mit
2,550
'''Sorry, I never got around to writing tests.''' from nose.tools import * from zombiescript import main
aspic2/ZombieScript
tests/main_tests.py
Python
mit
110
#!/usr/bin/env python # coding: utf8 import sys; import struct; def do_convert(filename): fid_in = open(filename, 'rb') fid_out = open('sound_conv.out','w') data = fid_in.read(4) # read 4 bytes = 32 Bit Sample while data: ser = str(struct.unpack('<i', data)[0]) + '\n' fid_out....
EPiCS/soundgates
hardware/tools/to_samples.py
Python
mit
505
import pdb import traceback import random from copy import deepcopy from collections import defaultdict from MTG import mana from MTG import zone from MTG import play from MTG import gamesteps from MTG import cards from MTG import triggers from MTG import token from MTG.exceptions import * class Player(): is_pla...
wanqizhu/mtg-python-engine
MTG/player.py
Python
mit
26,315
import threading import random from pixmodule import PixModule class Pong(PixModule): speed = 0 speedcounter = 0 direction = 1 position = 0 stats = (0,0) startSleep = 0 def render(self): if(self.stats is (0,0) and self.startSleep < 4000): self.startSleep += 1 elif self.stats[0] == 9: if self.leftPre...
stetro/pix-table
pixmodules/pong.py
Python
mit
1,964
# 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
CIM15/IEC61970/Informative/InfOperations/ChangeSet.py
Python
mit
5,204
""" Create metrics for Dataverses. This may be used for APIs, views with visualizations, etc. """ from collections import OrderedDict from django.db import models from dv_apps.utils.date_helper import get_month_name_abbreviation,\ get_month_name from dv_apps.dataverses.models import Dataverse, DATAVERSE_TYPE_UNCA...
IQSS/miniverse
dv_apps/metrics/stats_util_dataverses.py
Python
mit
15,410
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class STARInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing STAR 2.4.0g1 on %s" % (node.alias)) node.ssh.execute('wget -c -P /opt/software/star https://g...
meissnert/StarCluster-Plugins
STAR_2_4_0g1.py
Python
mit
1,005
import base64 import h5py import math import numpy as np import os import os.path as op def array_to_hitile( old_data, filename, zoom_step=8, chunks=(1e6,), agg_function=np.sum ): """ Downsample a dataset so that it's compatible with HiGlass (filetype: hitile, datatype: vector) Parameters -------...
hms-dbmi/clodius
clodius/tiles/hitile.py
Python
mit
10,847
from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'komsukomsuhuu.settings') from django.conf import settings app = Celery('komsukomsuhuu', broker='amqp://', ...
fabteam1/komsukomsuhuhu
komsukomsuhuu/komsukomsuhuu/celery.py
Python
mit
655
import time import os from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() testdir = os.path.dirname(os.path.abspath(__file__)) chrome_options.add_argument('nwapp=' + testdir) driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_optio...
nwjs/nw.js
test/sanity/issue5730-add-node-in-permissions/test.py
Python
mit
1,183
import os.path from fabric.api import env from fabsetup.fabutils import checkup_git_repo_legacy, needs_packages from fabsetup.fabutils import needs_repo_fabsetup_custom, suggest_localhost from fabsetup.fabutils import install_file_legacy, run, subtask, subsubtask, task from fabsetup.utils import flo, update_or_append...
theno/fabsetup
fabsetup/fabfile/setup/powerline.py
Python
mit
5,053
from polyphony import testbench class C: def __init__(self): self.v1 = 0 self.v2 = 0 def set_v(self, i, v): if i == 0: pass elif i == 1: self.v1 = v elif i == 2: self.v2 = v else: return def if23(): c = C() ...
ktok07b6/polyphony
tests/if/if23.py
Python
mit
439
""" A simple script for downloading user data. """ import argparse import csv import json import os from dataclasses import dataclass from shutil import move import requests as r from common import convert, limit_rate, max_request_per_hour, pid_run users_file_name = "users" users_data_file_name = "users.data.csv" te...
szymonlipinski/hackernews_dowloader
hnusers.py
Python
mit
5,013
from django.conf.urls import patterns, url urlpatterns = patterns('cityproblems.accounts.views', url(r'^register/$', 'register', name="accounts_register"), url(r'^profile/edit/$', 'accounts_profile_edit', name="accounts_profile_edit"), url(r'^profil...
SimplyCo/cityproblems
cityproblems/accounts/urls.py
Python
mit
1,489
from django import template from django.template.defaultfilters import stringfilter import locale register = template.Library() #-----------\ # FILTERS | #-----------/ @register.filter @stringfilter def num_format(value, places = 2, min_places = 2): return format(value, '.', int(places), 3, ',', int(min_places))...
fxdemolisher/frano
frano/templatetags/frano_filters.py
Python
mit
2,315
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "roboarm_config" PROJECT_SPACE_DIR = "...
4ndreas/ROSCoffeButler
build/roboarm_config/catkin_generated/pkg.develspace.context.pc.py
Python
mit
374
# -*- coding: utf-8 -*- import scrapy import logging from scrapy.utils.project import get_project_settings from time import sleep from AcgnzSpider.items import AcgnzItem class AcgnzSpider(scrapy.Spider): name = 'acgnz.cc' start_urls = ['http://www.acgnz.cc/sign'] allowed_domains = ['acgnz.cc'] def...
Nymphet/acgnz-spider
AcgnzSpider/spiders/AcgnzSpider01.py
Python
mit
3,584
import utils import pandas as pd import numpy as np import scipy.optimize as spo def get_data(): return utils.get_data(['SPY', 'MSFT', 'GOOG', 'AMD', 'TSLA', 'GLD'], pd.date_range('2011-01-01', '2017-01-01')) def optimizer_error(allocs, data): return 0 def test(): data = get_data() n...
gietal/Stocker
sandbox/udacity/1-9.py
Python
mit
472
import os, platform, re, shutil def get_tree_size(path = '.'): """ get_tree_size will return the total size of a directory tree """ if not os.path.exists(path): raise OSError("Path " + str(path) + " does not exist!") total_size = 0 for dirpath, dirnames, filenames in os.walk(str(path))...
Signiant/maestro-core
maestro/tools/path.py
Python
mit
3,383
#encoding:utf-8 subreddit = 'ikeahacks' t_channel = '@r_IKEAhacks' def send_post(submission, r2t): return r2t.send_simple(submission)
Fillll/reddit2telegram
reddit2telegram/channels/~inactive/r_ikeahacks/app.py
Python
mit
141
"""Redis Semaphore lock.""" import os import time SYSTEM_LOCK_ID = 'SYSTEM_LOCK' class Semaphore(object): """Semaphore lock using Redis ZSET.""" def __init__(self, redis, name, lock_id, timeout, max_locks=1): """ Semaphore lock. Semaphore logic is implemented in the lua/semaphore.l...
closeio/tasktiger
tasktiger/redis_semaphore.py
Python
mit
3,150
from room import Room r = Room() r.roomname = 'testroom2' r.exits = {'up': 'testroom'} r.roomdesc = """ As you look around, you notice there seems to be not much here. it appears you can go up and get back to where you came from there is a pile of gold and a large monster looking at you strangely. """ r.looktargets ...
elstupido/rpg
rooms/testrooms/testroom2.room.py
Python
mit
539
import numpy as np from pystella.rf import band from pystella.rf.ts import TimeSeries, SetTimeSeries __author__ = 'bakl' class LightCurve(TimeSeries): def __init__(self, b, time, mags, errs=None, tshift=0., mshift=0.): """Creates a Light Curve instance. Required parameters: b (band), time, mags.""" ...
baklanovp/pystella
pystella/rf/lc.py
Python
mit
8,633
import json import os, sys, traceback script_dir = os.path.dirname(__file__) config_file = os.path.join(script_dir, './config/application.json') defaults = os.path.join(script_dir, './config/reference.json') def loadConfig(f): print "[INFO] Loading configuration from " + f + "..." with open(f, 'r') as opened:...
Xarxa6/hackathon
src/config.py
Python
mit
1,937
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ __all__ = ['HTTP', 'redirect'] defined_status = { 200: 'OK', 201: 'CREATED', 202: 'ACCEPTE...
stryder199/RyarkAssignments
Assignment2/web2py/gluon/http.py
Python
mit
3,669
from unittest import TestCase, main, skip from mock import patch, call, MagicMock from SolarSensors import SolarSensors import os class SolarSensors_test(TestCase): def setUp(self): pass def tearDown(self): pass def get_default_config(self): config = [ { ...
weidnerm/solar_data_monitor
SolarSensors_test.py
Python
mit
3,665
from past.builtins import basestring import os.path import simplejson as json from django.shortcuts import render as django_render from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect from django.utils.decorators import available_attrs from functools import wraps def render(requ...
zeraien/odb_shared_django
http_shortcuts.py
Python
mit
2,641
# Copyright (c) 2016 Matthew Earl # # 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, distr...
matthewearl/photo-a-day-aligner
pada/landmarks.py
Python
mit
2,163
"""Win animation frames for Mystery Mansion. Animation from: http://www.angelfire.com/ca/mathcool/fireworks.html """ win_animation = [ """ .| | | |'| ._____ ___ | | |. |' .---"| _ .-' ...
corbanmailloux/MysteryMansion
win_animation.py
Python
mit
12,458
import glob import subprocess from threading import Timer import logging import distutils.dir_util import sys import multiprocessing import os from shutil import copy2 import eyetype import shutil logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def runWithTimeOutByDaemon(cmd...
PublicShawn/eye
util.py
Python
mit
2,148
#!/usr/bin/env python # coding: utf-8 from rosalind import binom def pbinom(n, p, r): return binom(n, r) * pow(p, r) * pow(1 - p, n - r) def dbinom(n, p, r): return sum(pbinom(n, p, i) for i in range(r + 1)) def lia(k, N): t = 1 << k return 1 - dbinom(t, .25, N - 1) if __name__ == "__main__": ...
genos/online_problems
rosalind/lia.py
Python
mit
431
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0010_product_design_format'), ] operations = [ migrations.AlterField( model_name='product', ...
GETLIMS/LIMS-Backend
lims/projects/migrations/0011_auto_20160822_1527.py
Python
mit
415
from enum import Enum class EventType(Enum): """Enum containing the various types of events that can occur.""" CLIENT_READY = "CLIENT_READY" CLIENT_RESUMED = "CLIENT_RESUMED" MESSAGE_RECEIVED = "MESSAGE_RECEIVED" SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED" PRIVATE_MESSAGE_RECEIVED = "...
nint8835/NintbotForDiscordV2
NintbotForDiscord/Enums.py
Python
mit
1,656
#!/usr/bin/python3 # -*- coding: utf-8 -*- import serpscrap keywords = ['stellar'] config = serpscrap.Config() config.set('scrape_urls', False) scrap = serpscrap.SerpScrap() scrap.init(config=config.get(), keywords=keywords) results = scrap.as_csv('/tmp/output')
ecoron/SerpScrap
examples/example_csv.py
Python
mit
266
def countingsort(sortablelist): maxval = max(sortablelist) m = maxval + 1 count = [0] * m # init with zeros for a in sortablelist: count[a] += 1 # count occurences i = 0 for a in range(m): # emit for c in range(count[a]): # - emit 'count[a]' c...
NendoTaka/CodeForReference
Python/Sort/CountingSort.py
Python
mit
511
import collections from supriya import CalculationRate from supriya.synthdefs import PureUGen, UGen class AllpassC(PureUGen): """ A cubic-interpolating allpass delay line unit generator. :: >>> source = supriya.ugens.In.ar(bus=0) >>> allpass_c = supriya.ugens.AllpassC.ar(source=source) ...
josiah-wolf-oberholtzer/supriya
supriya/ugens/delay.py
Python
mit
13,124
from django.db import models from django.db.models.fields.related import ManyToOneRel, ForeignObjectRel from elasticsearch_dsl.mapping import Mapping from elasticsearch_dsl.field import Field from djes.conf import settings FIELD_MAPPINGS = { "AutoField": {"type": "long"}, "BigIntegerField": {"type": "long"},...
theonion/djes
djes/mapping.py
Python
mit
5,823
# -*- coding: utf-8 -*- import unittest from ..colorharmonies import Color, complementaryColor, triadicColor, splitComplementaryColor, tetradicColor, analogousColor, monochromaticColor class colorsHarmonies(unittest.TestCase): # Obtain the complementary color of a color def test_complementaryColor(self): MagentaCo...
baptistemanteau/colorharmonies
colorharmonies/tests/test_colorharmonies.py
Python
mit
6,249
from typing import List, Any import json import logging import threading from pathlib import Path log = logging.getLogger("pajbot") class WebSocketServer: clients: List[Any] = [] def __init__(self, manager, port, secure=False, key_path=None, crt_path=None, unix_socket_path=None): self.manager = mana...
pajlada/pajbot
pajbot/managers/websocket.py
Python
mit
4,650
#encoding:utf-8 n = 1111101010 while n > 1: if n % 2 == 0: n /= 2 else: n = n * 3 + 1 print 'current >>>>', n
Flowerowl/Projects
solutions/algorithms/collatz_conjecture.py
Python
mit
140
# 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 ...
AutorestCI/azure-sdk-for-python
azure-mgmt-datafactory/azure/mgmt/datafactory/models/sap_hana_linked_service.py
Python
mit
3,345
#!/usr/bin/env python #Copyright (C) 2011 by Benedict Paten (benedictpaten@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 rig...
harvardinformatics/jobTree
batchSystems/parasol.py
Python
mit
11,029
from graphql.core.type.definition import GraphQLEnumType from epoxy.registry import TypeRegistry from enum import Enum def test_register_builtin_enum(): R = TypeRegistry() @R class MyEnum(Enum): FOO = 1 BAR = 2 BAZ = 3 enum = R.type('MyEnum') assert isinstance(enum, Graph...
graphql-python/graphql-epoxy
tests/test_register_enum.py
Python
mit
519
# -*- coding: utf-8 -*- import os import unittest from helpers.config import load_config, ConfigurationError class LoadConfigTest(unittest.TestCase): def test_development_config(self): os.environ['SERVER_SOFTWARE'] = 'Dev-XXX' config = load_config() self.assertIsInstance(config, dict) ...
opendatapress/open_data_press
tests/test_helpers/test_config.py
Python
mit
730
import logging import sys from os import path import click from clickclick import AliasedGroup, fatal_error import connexion from connexion.mock import MockResolver logger = logging.getLogger('connexion.cli') CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) def validate_wsgi_server_requirements(ctx, par...
NeostreamTechnology/Microservices
venv/lib/python2.7/site-packages/connexion/cli.py
Python
mit
5,463
# -*- coding: utf-8 -*- import django from django.contrib.auth.models import User from django.test import TestCase, Client # compat thing! if django.VERSION[:2] < (1, 10): from django.core.urlresolvers import reverse else: from django.urls import reverse class FilerUtilsTests(TestCase): def setUp(self): ...
rouxcode/django-filer-addons
filer_addons/tests/test_utils.py
Python
mit
793
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Widget to display simulation data of a CSDF graph. author: Sander Giesselink """ from PyQt5.QtWidgets import QGraphicsItem, QInputDialog, QMessageBox from PyQt5.QtCore import Qt, QRectF, QPointF from PyQt5.QtGui import QColor, QPen, QBrush, QPainterPath, QF...
rinsewester/SchemaViz
edge.py
Python
mit
15,908
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
carboncointrust/CarboncoinCore
contrib/linearize/linearize.py
Python
mit
3,360
class Node(): def __init__(self, name): self.name = name def __str__(self): if self.name is not None: return self.name else: return "internal_{}".format(id(self)) class Edge(): def __init__(self, node1, node2): self.nodes = [node1, node2] def __...
crf1111/Bio-Informatics-Learning
Bio-StrongHold/src/Enumerating_Unrooted_Binary_Trees.py
Python
mit
3,854
from __future__ import unicode_literals, print_function, absolute_import from setuptools import setup, find_packages import giles setup( author="Anthony Almarza", name="giles", version=giles.__version__, packages=find_packages(exclude=["test*", ]), url="https://github.com/anthonyalmarza/giles", ...
anthonyalmarza/giles
setup.py
Python
mit
941
from interpreter.heap import stringify from interpreter.interpret import DTREE, CTREE class execute(): def __init__( self, program ): self.len = 0 self.heap = {} self.stack = [] H = "H" + str( self.len ) self.heap[H] = { "$": "nil" } self.len = self.len + 1 ...
brian-joseph-petersen/oply
interpreter/execute.py
Python
mit
503
from sklearn import cluster import numpy as np import datetime #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt class Location: vehicle_data = None @staticmethod def get_data(): if Location.vehicle_data is not None: return Location.vehicle_data.tolist() else: return None @sta...
axelniklasson/adalyzer
backend/location_optimisation.py
Python
mit
1,650
from distutils.version import LooseVersion from django.core.management.base import BaseCommand from django.utils.version import get_version from django_rq import get_queue class Command(BaseCommand): """ Queue a function with the given arguments. """ help = __doc__ args = '<function arg arg ...>...
1024inc/django-rq
django_rq/management/commands/rqenqueue.py
Python
mit
1,223
#!/usr/bin/python # coding: utf-8 import copy import json from lcg import LCG class Game(object): def __init__(self, json_file): super(Game, self).__init__() with open(json_file) as f: json_data = json.load(f) self.ID = json_data["id"] self.units = [Unit(json_u...
ooz/ICFP2015
src/game.py
Python
mit
8,981
''' we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input...
DayGitH/Python-Challenges
DailyProgrammer/20120209C.py
Python
mit
1,271
import taglib import os TEMP_FILENAME = "temp.mp3" class TagWrapper: def __init__(self, fileName): self.fileName = fileName try: self.tag = taglib.MP3(fileName) except: self.tag = None def __enter__(self): return self def __exit__(self, type, value, traceback): ...
marco-lilek/musiClr
src/utils/modifyTag.py
Python
mit
835
import socket import asyncore import pickle from minissl.AbstractConnection import AbstractConnection class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection): """Buffers a stream until it contains valid data serialized by pickle. That is a big of an ugly glue code I had to come up with i...
vsaw/miniSSL
minissl/TcpDispatcher.py
Python
mit
3,729
import numpy as np import pandas as pd import seaborn as sns import wordcloud from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.manifold import TSNE from sklearn.preprocessing import Normalizer from sklearn.pipeline import make_pipeline def sample...
joshloyal/pydata-amazon-products
amazon_products/text_plots.py
Python
mit
5,332
print("TEA5767 FM Radio project") print("dipto@linuxcircle.com") print("Excellent codes will be uploaded here!")
LinuxCircle/tea5767
hello.py
Python
mit
114
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA...
comicxmz001/LeetCode
Python/160 Intersection of Two Linked Lists.py
Python
mit
982
import unittest from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distance from alfpy.utils import distmatrix from . import utils class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*a...
aziele/alfpy
tests/test_distance.py
Python
mit
3,659
def intent(func): """ This is used inside the intent parser in `lessons.base.plugin._intent_dictionary()` :param func: :return: """ func.decorator = intent return func
androbwebb/JenniferVirtualAssistant
lessons/base/decorators.py
Python
mit
196
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import ConfigParser import unicodecsv import json import sys import re ### FUNCTIONS FOR COUNTING CLUSTER STATISTICS ### def text_statistics(texts): lencount = 0 minlen = sys.maxint maxlen = 0 for t in texts: l = len(t.split()) ...
X455u/SNLP
bin/python/sortclusters.py
Python
mit
3,748
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class MagicWordManagerAI(DistributedObjectAI): notify = Direc...
ToonTownInfiniteRepo/ToontownInfinite
otp/ai/MagicWordManagerAI.py
Python
mit
1,950
import re import os def get_emoji_content(filename): full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename) with open(full_filename, 'r') as fp: return fp.read() def fix_emoji(value): """ Replace some text emojis with pictures """ emojis = { '(+)': get_em...
vv-p/jira-reports
filters/filters.py
Python
mit
977
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class instaLogger: def __init__(self, logfile): self.logfile = logfile d...
VerstandInvictus/Spidergram
spidergram.py
Python
mit
4,748