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
# -*- coding: utf-8 -*- # # This file is part of the python-chess library. # Copyright (C) 2015 Jean-Noël Avila <jn.avila@free.fr> # Copyright (C) 2015-2016 Niklas Fiekas <niklas.fiekas@backscattering.de> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu...
Bojanovski/ChessANN
Code/dependencies/chess/gaviota.py
Python
mit
63,321
from django.test import TestCase from countries import factories class ModelsTests(TestCase): def test_models_continent_str(self): continent = factories.ContinentFactory() self.assertEqual(str(continent), continent.code) def test_models_countries_str(self): country = factories.Count...
flavors/countries
tests/test_models.py
Python
mit
1,302
from flask import Flask, render_template app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('index.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=9876)
austintrose/easy-graphs
application.py
Python
mit
227
import mbuild as mb from mbuild.lib.moieties import CH3 class Ethane(mb.Compound): """An ethane molecule. """ def __init__(self): """Connect two methyl groups to form an ethane. """ super(Ethane, self).__init__() self.add(CH3(), "methyl1") self.add(CH3(), "methyl2") m...
Jonestj1/mbuild
mbuild/examples/ethane/ethane.py
Python
mit
652
import os import sys import stat import subprocess import shutil import click import requests import time from configparser import ConfigParser import getpass APP_DIR = click.get_app_dir('juantap') CONFIG_PATH = os.path.join(APP_DIR, 'config.ini') click.echo(CONFIG_PATH) CFG = ConfigParser() def write_config(): ...
mathiassmichno/juantap
juantap/__init__.py
Python
mit
1,304
class Error(Exception): def __init__(self, message): super(Error, self).__init__(message) self.message = message class PathError(Error, ValueError): pass class NotFoundError(Error, IOError): pass
grow/grow
grow/storage/errors.py
Python
mit
229
# -*- coding: utf-8 -*- import re import hashlib import logging from tornado.web import RequestHandler import tornado.web from common.settings import DEBUG, MEMCACHE_ENABLED from common.query_settings import APIdict if MEMCACHE_ENABLED: from api.db_selectors import mc _asciire = re.compile('([\x00-\x7f]+)') d...
clearspending/api.clearspending.ru
api/handler.py
Python
mit
5,904
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="mesh3d.colorbar.tickfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=p...
plotly/plotly.py
packages/python/plotly/plotly/validators/mesh3d/colorbar/tickfont/_size.py
Python
mit
461
from django.contrib.gis.db import models class Friend(models.Model): '''A friend''' # Custom GeoDjango manager objects = models.GeoManager() first_name = models.CharField(max_length=16, blank=False) last_name = models.CharField(max_length=16) # Where does your friend live? street_address = models.Ch...
johnwoltman/geotest
geotest/models.py
Python
mit
486
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) from django.contrib import admin from snisi_core.admin import ReportAdmin from snisi_cataract.models import (CATMissionR, ...
yeleman/snisi
snisi_cataract/admin.py
Python
mit
453
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Editable Table import django_tables2 as tables import json from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from django.urls import reve...
vithd/vithd.github.io
django/mysite/polls/views.py
Python
mit
2,771
# -*- coding: utf-8 -*- import unittest from logging import getLogger from calmjs.parse.testing.util import build_equality_testcase from calmjs.parse.testing.util import build_exception_testcase from calmjs.parse.testing.util import setup_logger from calmjs.parse.tests.parser import format_repr_program_type def ru...
calmjs/calmjs.parse
src/calmjs/parse/tests/test_testing.py
Python
mit
3,879
import requests_unixsocket import json from utils.utils import Utils u = Utils() #https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/ class Events(): def __init__(self): self.base = "http+unix://%2Fvar%2Frun%2Fdocker.sock" self.url = "/events" self.sessi...
eon01/DoMonit
domonit/events.py
Python
mit
816
import os import subprocess from flask import Flask, url_for, redirect, request, jsonify cmd_folder = os.path.dirname(os.path.abspath(__file__)) f2f_path = os.path.join(cmd_folder, 'lib', 'f2f.pl') app = Flask(__name__, static_url_path='') #2. Define needed routes here @app.route('/') def index(): return redire...
mgaitan/f2f_online
app.py
Python
mit
1,408
import engine import pytest VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49...
EyuelAbebe/gamer
test_engine.py
Python
mit
6,871
OUTPUT = 'ko{}-{}ntti'.format VOWELS = frozenset('aeiouyAEIOUY') def kontti(s): result = [] for word in s.split(): dex = next((i for i, a in enumerate(word) if a in VOWELS), -1) + 1 result.append(OUTPUT(word[dex:], word[:dex]) if dex else word) return ' '.join(result)
the-zebulan/CodeWars
katas/beta/kontti_language.py
Python
mit
299
import _plotly_utils.basevalidators class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="colorsrc", parent_name="histogram.marker", **kwargs ): super(ColorsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=...
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram/marker/_colorsrc.py
Python
mit
419
#! /bin/sh """:" exec python $0 ${1+"$@"} """ import fileinput import os import platform import re import sys import argparse all_files = { # Proxy files for Ubuntu. 'ubuntu': { '/etc/environment': [ 'http_proxy=":proxy.http:"', 'https_proxy=":proxy.https:"', 'ftp_pr...
znck/setproxy
setproxy.py
Python
mit
10,757
from player_class import Player, randint """ Dealer Class """ class Dealer(Player): house_rule_names =[ "Dealer stand on all 17", "Dealer hit on soft 17" ] def __init__(self, n, c, t, h): Player.__init__(self, n, c, t, 0, 0) self._house = h self._house_rule_name = Dealer.house_rule_names[self.house-1] ...
pasquantonio/blackjack_terminal
src/dealer_class.py
Python
mit
1,678
from __future__ import unicode_literals 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.encoding import python_2_unicode_compatible from ..orders.models import Order @python_2_unicode_c...
ad-m/taravel
taravel/payments/models.py
Python
mit
1,444
"""Abstract base class for programs. """ import os from . import limit import resource import signal import logging from .errors import ProgramError class Program(object): """Abstract base class for programs. """ runtime = 0 def run(self, infile='/dev/null', outfile='/dev/null', errfile='/dev/null', ...
Kattis/problemtools
problemtools/run/program.py
Python
mit
4,904
""" __init__ file """ from .status import Status from .atcab import *
PhillyNJ/SAMD21
cryptoauthlib/python/cryptoauthlib/__init__.py
Python
mit
71
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, absolute_import import frappe import json from email.utils import formataddr, parseaddr from frappe.utils import get_url, get_formatted_email, cstr from frappe.utils.file_manager...
gangadharkadam/vlinkfrappe
frappe/core/doctype/communication/communication.py
Python
mit
9,355
'''Trains a stacked what-where autoencoder built on residual blocks on the FASHION MNIST dataset. It exemplifies two influential methods that have been developed in the past few years. The first is the idea of properly 'unpooling.' During any max pool, the exact location (the 'where') of the maximal value in a p...
asaleh/Fashion-MNIST-Keras
fashion_mnist_swwae.py
Python
mit
7,773
import unittest from clickatell import Transport import json class TransportTest(unittest.TestCase): def test_parseLegacyFailure(self): response = {'body': 'ERR: Some exception'} transport = Transport() self.assertRaises(ClickatellError, lambda: transport.parseLegacy(response)) def te...
clickatell/clickatell-python
test/test_transport.py
Python
mit
1,677
from setuptools import setup, find_packages import os version = '1.2~dev' base = os.path.dirname(__file__) readme = open(os.path.join(base, 'README.rst')).read() changelog = open(os.path.join(base, 'CHANGELOG.rst')).read() setup(name='restdns', version=version, description='Rest API for DNS', long...
NaPs/restdns
setup.py
Python
mit
817
import copy import json import re from urllib.parse import urlparse from svtplay_dl.error import ServiceError from svtplay_dl.fetcher.hds import hdsparse from svtplay_dl.fetcher.hls import hlsparse from svtplay_dl.fetcher.http import HTTP from svtplay_dl.service import OpenGraphThumbMixin from svtplay_dl.service impor...
olof/debian-svtplay-dl
lib/svtplay_dl/service/vg.py
Python
mit
1,907
""" CS256 ISA Assembler Author: Mark Liffiton """ import collections import configparser import re import sys from pathlib import PurePath class AssemblerException(Exception): def __init__(self, msg, data=None, lineno=None, instruction=None): self.msg = msg self.data = data self.lineno = l...
liffiton/256asm
assembler.py
Python
mit
14,120
# -*- coding: utf-8 -*- """Module for constructing <head> tag.""" from __future__ import absolute_import from ...templates.html.tags import head class Head(object): """Class for constructing <head> tag. Args: text (str): Specifies the head text. (As in <head>{text}</head>) .. versionadded:: 0....
bharadwajyarlagadda/korona
korona/html/tags/head.py
Python
mit
645
""" EventWall Development Server Script """ from os import environ from eventwall import app if __name__ == '__main__': HOST = environ.get('SERVER_HOST', 'localhost') try: PORT = int(environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT)
stevenmirabito/eventwall
runserver.py
Python
mit
304
from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels']...
dashmoment/moxa_ai_training
tutorial/01_DNN/dnn_SGD.py
Python
mit
4,015
from . import app from flask import Markup import mistune as md @app.template_filter() def markdown(text): return Markup(md.markdown(text,escape=True)) @app.template_filter() def dateformat(date, format): if not date: return None return date.strftime(format).lstrip('0') @app.template_filter()...
j10sanders/crossword
crossword/filters.py
Python
mit
406
class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.word_dict={} for word in dictionary: key=self.create_key(word) self.word_dict[key]=self.word_dict.get(key...
Tanych/CodeTracking
288-Unique-Word-Abbreviation/solution.py
Python
mit
1,176
import logging import numpy from OpenGL.GL import * from PIL import Image from mgl2d.math.vector2 import Vector2 logger = logging.getLogger(__name__) class Texture(object): @classmethod def load_from_file(cls, filename, mode=GL_RGBA): image = Image.open(filename) logger.debug(f'Loading \'{f...
maxfish/mgl2d
mgl2d/graphics/texture.py
Python
mit
3,207
#! /usr/bin/env python # -*- coding: utf-8 -*- import xlsxwriter from mongodb import db, conn def export_to_xlsx(skip_num, limit_num): # create a workbook book_name = u'百灵威数据采集_' + str(skip_num//limit_num+1) + '.xlsx' workbook = xlsxwriter.Workbook(book_name) # create a worksheet and export data work...
mutoulbj/chem_spider
chem_spider/blw_export_xlsx.py
Python
mit
1,905
from django.contrib import admin from bootcamp.articles.models import Article @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ("title", "user", "status") list_filter = ("user", "status", "timestamp")
vitorfs/bootcamp
bootcamp/articles/admin.py
Python
mit
240
#!/usr/bin/env python3 from copy import deepcopy from datetime import datetime import urllib.request import urllib.error import urllib.parse from urllib.parse import urljoin import json import re from html.parser import HTMLParser class GenericParser(HTMLParser): """Basic tools to collect information from a si...
chris34/HTML2RSS
lib/Parser.py
Python
mit
8,841
from intent.alignment.Alignment import Alignment import json def aln_to_json(aln, reverse=False): """ :type aln: Alignment """ ret_dir = {} if not reverse: for tgt in aln.all_tgt(): ret_dir[tgt] = aln.tgt_to_src(tgt) else: for src in aln.all_src(): ret_di...
xigt/yggdrasil
yggdrasil/utils.py
Python
mit
367
import collections from pymongo import MongoClient, ReturnDocument from pymongo.errors import ConfigurationError from thingy import classproperty, DatabaseThingy, registry from mongo_thingy.cursor import Cursor class Thingy(DatabaseThingy): """Represents a document in a collection""" _client = None _col...
numberly/mongo-thingy
mongo_thingy/__init__.py
Python
mit
4,532
''' @author: Jeremy Bayley @email : TheEnvironmentGuy@gmail.com @websight : TheEnvironmentGuy.com Friday March 25 2016 Blender 2.77 -*- coding: utf-8 -*- ''' import bpy import ImperialPrimitives as ip inch = 0.0254 foot = 0.3048 stud_length = foot*8 ceiling_height = foot*8 wall_length = foot*6 drywall_size = [foot...
TheEnvironmentGuy/teg-inhouse
blenderWallBuilder/WallBuilder.py
Python
mit
537
import random import maya.cmds as m FILENAMES = [ '', '%FXPT_LOCATION%/src/dirA/testTex_exit.png', '%INVALID_ENV_VAR%/fxpt/fx_texture_manager/icons/copy.png', '//BLACK/C$/__testTextureManager__/src/dirB/dirB1/retarget.png', 'C:/__testTextureManagerExternal__/AAA/testTex_exit.png', 'C:/__testTe...
theetcher/fxpt
fxpt/fx_texture_manager/tests/create_test_scene.py
Python
mit
4,062
# 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 ...
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-language-textanalytics/azure/cognitiveservices/language/textanalytics/models/entities_batch_result_item_py3.py
Python
mit
1,684
import random from numpy import zeros, sign from math import exp, log from collections import defaultdict import argparse kSEED = 1701 kBIAS = "BIAS_CONSTANT" random.seed(kSEED) def sigmoid(score, threshold=20.0): """ Note: Prevents overflow of exp by capping activation at 20. :param score: A real val...
Pinafore/ds-hw
logreg/logreg.py
Python
mit
5,137
from fnmatch import fnmatch from os import listdir from unittest import TestCase from pylegos.core import FileUtils class TestFileUtils(TestCase): Sut = FileUtils() def test_pathUtils(self): pd = self.Sut.getParentDir(filePath=__file__) self.assertEqual('/Users/gchristiansen/projects/pyLeg...
velexio/pyLegos
tests/test_FileUtils.py
Python
mit
2,450
# -*- coding: utf-8 -*- import numpy import time import os import magdynlab.instruments import magdynlab.controllers import magdynlab.data_types import threading_decorators as ThD import matplotlib.pyplot as plt @ThD.gui_safe def Plot_ColorMap(Data): f = plt.figure('ZxH', (5, 4)) extent = numpy.array([Data['...
Vrekrer/magdynlab
experiments/ZxH.py
Python
mit
7,857
# Try to find vacancy defects: detects vacant places of host atoms # Author: Evgeny Blokhin from math import gcd from functools import reduce # hierarchy API: __order__ to apply classifier __order__ = 20 def classify(tilde_obj): if len(tilde_obj.info['elements']) < 2: return tilde_obj elif tilde_obj.struct...
tilde-lab/tilde
tilde/classifiers/defects.py
Python
mit
2,112
# flake8: noqa # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: # Django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() ...
bitmazk/django-document-library
document_library/south_migrations/0008_auto.py
Python
mit
11,252
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import wagtail.wagtailcore.fields class Migration(migrations.Migration): dependencies = [ ('cms_pages', '0009_auto_20151025_0116'), ] operations = [ migrations.AddField( ...
dchaplinsky/pep.org.ua
pepdb/cms_pages/migrations/0010_auto_20160223_0142.py
Python
mit
2,769
from django import forms from django.contrib.auth.models import User from captcha.fields import CaptchaField from models import UserProfile class UserForm(forms.ModelForm): password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={'class':'form-control', ...
vollov/sm
django/account/forms.py
Python
mit
1,248
def loopArray(l, r): global nr, value dif = (r - l) + 1 for x in range(l, r + 1): nr.append(x) for x in range(0, dif): for i in range(0, dif): if nr[x] == nr[i]: value += "0" else: value += "1" return nr, value value = "" n...
alphazilla/HR_challenges
python/basic-data-types/loop-array.py
Python
mit
357
#!/usr/bin/env python3 """ The relabeler reads data files and outputs new data files with different information. The input files must contain one word per line, with sentences separated by blank lines. Each word is annotated with the following tab-separated fields: 1. token offset within sentence 2. word 3. lowercase...
pdarragh/MinSem
relabel.py
Python
mit
2,712
"""Files pipeline back-ported to python 2.6""" # Copy pasted from # https://github.com/scrapy/scrapy/blob/master/scrapy/contrib/pipeline/files.py import hashlib import os import os.path import rfc822 import time import urlparse from collections import defaultdict from cStringIO import StringIO from twisted.internet ...
BlogForever/crawler
bibcrawl/pipelines/files.py
Python
mit
10,181
# -*- coding: utf-8 -*- __version__ = '0.0.1' def version(): return __version__ # adapted from: # http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge/7205107#7205107 def dict_merge(a, b, path=None): """merges b into a""" if path is None: path = [] for key in b: ...
finklabs/aws-deploy
botodeploy/utils.py
Python
mit
627
# parse and plot output from LibPaxos3 and LibFPaxos import csv import numpy as np # parse csv output def read(filename): latency = [] throughput = [] with open(filename, newline='') as csvfile: for row in csv.reader(csvfile): if len(row) == 3: thr = row[0].rsplit(" ") ...
fpaxos/fpaxos-test
plotter.py
Python
mit
5,226
# -*- coding: utf-8 -*- from __future__ import print_function from setuptools import setup try: from jupyterpip import cmdclass except: import pip, importlib pip.main(['install', 'jupyter-pip']); cmdclass = importlib.import_module('jupyterpip').cmdclass setup( name='d3networkx_psctb', version='0.2'...
exe0cdc/ipython-d3networkx
setup.py
Python
mit
956
#!/usr/bin/python import traceback from scipy.io import wavfile import tensorflow as tf import numpy as np import random import json import itertools import math import time import pyaudio import matplotlib.pyplot as plt import scipy.io as sio import params import model import train import export_to_octave import o...
keskival/wavenet_synth
generate.py
Python
mit
3,480
""" Utility functions. """ import asyncio import collections import functools import inspect import io import logging import os from typing import Set # noqa import libnacl import logbook import logbook.compat import logbook.more # noinspection PyPackageRequirements import lru import wrapt from .key import Key __al...
threema-ch/threema-msgapi-sdk-python
threema/gateway/util.py
Python
mit
16,977
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
jeremiedecock/snippets
python/tempfile_make_temporary_directory_with_prefix_suffix_and_dirpath.py
Python
mit
1,597
#!/usr/bin/env python import rospy from std_msgs.msg import Float32 import numpy as np # publish command def publisher(data): pub = rospy.Publisher('pid/cmd',Float32, queue_size=10) rospy.init_node('pid_node', anonymous=True) rate = rospy.Rate(10) #10hz msg = data[1] while not rospy.is_shutdown(...
Projet-Guerledan/ROSonPi
glider_dir/src/reg_pkg/src/reg.py
Python
mit
1,068
from django.shortcuts import render # Create your views here. from django.core.serializers import serialize from django.http import HttpResponseRedirect,HttpResponse from django.core.urlresolvers import reverse from .forms import LocationForm from django.shortcuts import render_to_response from .models import * from d...
bird50/birdproj
mapservice/views.py
Python
mit
1,889
try: from collections import OrderedDict except ImportError: OrderedDict = dict from collections import namedtuple from inspect import isclass import re from peewee import * from peewee import _StringField from peewee import _query_val_transform from peewee import CommaNodeList from peewee import SCOPE_VALUES ...
gennaios/alfred-gnosis
src/playhouse/reflection.py
Python
mit
28,321
"""Simple MQTT wrapper for subscriber and publisher. Usage: from mqttclient import MqttPublisher, MqttSubscriber # --- init subscriber # msg: MQTTMessage class, which has members topic, payload, qos, retain and mid. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload)) ...
manylabs/flow
flow/mqttclient.py
Python
mit
2,237
# -*- coding: utf-8 -*- """ Created on Sat Apr 2 16:03:30 2016 @author: Manojkumar Parmar VirKrupa @Github Repo : MITx_Python Modified on : 02/04/2016 Version : 1.0 Remarks: """ # pylint: disable=invalid-name import random import pylab # You are given this function def getMeanAndStd(X): """ returns calcu...
parmarmanojkumar/MITx_Python
6002x/quiz/p6.py
Python
mit
3,326
# -*- coding: utf-8 -*- from __future__ import unicode_literals import inspect import logging import os from . import Benchmark from .report import BaseReporter from ._compat import load_module, string_types log = logging.getLogger(__name__) class BenchmarkRunner(object): '''Collect all benchmarks and run the...
noirbizarre/minibench
minibench/runner.py
Python
mit
3,606
class Solution(object): def titleToNumber(self, s): """ :type s: str :rtype: int """ ret = 0 for i in s: ret *= 26 ret += ord(i)-ord('A')+1 return ret
xingjian-f/Leetcode-solution
171. Excel Sheet Column Number.py
Python
mit
238
NOT_PROVIDED = object() class ConfigurationProvider: def get(self, key): raise NotImplementedError() class DictConfig(ConfigurationProvider): """ Loads configuration values from the passed dictionary. """ def __init__(self, conf_dict, prefix=''): self._conf_dict = conf_dict ...
GaretJax/storm-erp
storm/config/providers.py
Python
mit
495
""" grey Test Utils for Motor """ import unittest from tornado.ioloop import IOLoop from grey.tests.utils import GreyTest class GreyAsyncTest(GreyTest): # Ensure IOLoop stops to prevent blocking tests def callback(self, func): def wrapper(*args, **kwargs): IOLoop.instance().stop() ...
GreyCorp/GreyServer
grey/tests/utils/mongo.py
Python
mit
731
from sqlalchemy import * from sqlalchemy.orm import * class User(object): def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.email) # Create engine # engine = create_engine('sqlite:///:memory:') # echo=True for debug information # engine = create_engine('sqlite:///./sqla...
quchunguang/test
testpy/testsqlalchemy.py
Python
mit
1,310
#!/usr/bin/env python import json import urllib2 import requests import time from datetime import datetime # url = # 'http://ec2-54-187-18-145.us-west-2.compute.amazonaws.com/node/postdata/' url = 'http://localhost:8000/node/postdata/' # url = 'http://clairity.mit.edu/node/postdata/' def send(url, values): try:...
clairityproject/backend
sample_post.py
Python
mit
2,486
"""jsConfirm URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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-b...
chrissmejia/jsConfirm
djangodemo/jsConfirm/urls.py
Python
mit
872
from evostream.default import api from evostream.management.base import BaseEvoStreamCommand class Command(BaseEvoStreamCommand): help = 'Get a list of IDs for every active stream.' requires_system_checks = False def get_results(self, *args, **options): return api.list_streams_ids()
tomi77/django-evostream
evostream/management/commands/liststreamsids.py
Python
mit
308
N, S = int(input()), input() ans = N for i in range(1, N): s1, s2 = S[:i], S[i:] dp = [[0]*(len(s2)+1) for _ in range(len(s1)+1)] for j in range(len(s1)): for k in range(len(s2)): if (s1[j] == s2[k]): dp[j+1][k+1] = max([dp[j][k] + 1, dp[j][k+1], dp[j+1][k]]) ...
knuu/competitive-programming
atcoder/corp/codefes2015_asa_b.py
Python
mit
445
""" Django settings for django-ddp-meteor-todo project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BA...
cxhandley/django-ddp-meteor-todo
django-ddp-meteor-todo/settings.py
Python
mit
2,138
# -*- coding: utf-8 -*- # # Copyright (c), 2016-2019, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author ...
brunato/xmlschema
xmlschema/validators/globals_.py
Python
mit
22,118
import superimport import daft # Colors. p_color = {"ec": "#46a546"} s_color = {"ec": "#f89406"} r_color = {"ec": "#dc143c"} SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") pgm = daft.PGM(shape=(12, 5), origin=(-1,0)) pgm.add_node("Ax", r"$\theta^h$", 2.5, 3, observed=False) for i in range(4): pgm.add_node("x{...
probml/pyprobml
scripts/visual_spelling_hmm_daft.py
Python
mit
1,434
#!/usr/bin/env python from numpy import loadtxt from pylab import * from scipy import * from scipy.optimize import leastsq #import sys filename = 'data_CW.txt' g2 = ['%g' %(0.5*200*(i+1)) for i in range(5)] print g2 def fit(line): filename = 'CW_g2_20_LW_0.7_dt_0.01_%s_uWcm2_1e-10_conS_10_O=12.txt' %line print f...
imrehg/bloch
fit_CW.py
Python
mit
1,314
#Credits - https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/3 import torch batch_size = 5 nb_digits = 10 # Dummy input that HAS to be 2D for the scatter (you can use view(-1,1) if needed) y = torch.LongTensor(batch_size,1).random_() % nb_digits # One hot encoding buffer that you create out of the loo...
skrish13/pytorch-snippets
one-hot.py
Python
mit
486
def get_class(obj): return obj.__class__ def get_class_name(obj): return obj.__class__.__name__ def get_methods_on_class(cls): """ Returns a list of tuples containing of all the method names and methods in a class i.e [(method_name1, method1), (method_name2, method2), ...] """ methods = [] methods_to_...
crispycret/crispys_webkit
crispys_webkit/objprope.py
Python
mit
614
# -*- encoding: utf-8 -*- # JN 2016-02-16 """ Plot a spectrum from the first 1000 records of data """ import sys import scipy.signal as sig import matplotlib.pyplot as mpl from combinato import NcsFile, DefaultFilter def plot_spectrum(fname): fid = NcsFile(fname) rawdata = fid.read(0, 1000) data = rawda...
jniediek/combinato
tools/mini_spectrum.py
Python
mit
970
#!/usr/bin/env python from pylab import * from scipy.io import mmread A = mmread('poisson3Db.mtx') fig, (ax1, ax2) = subplots(2, 1, sharex=True, figsize=(8,10), gridspec_kw=dict(height_ratios=[4,1])) ax1.spy(A, marker='.', markersize=0.25, alpha=0.2) ax2.semilogy(A.diagonal()) ax2.set_ylabel('Diagonal') tight_layout(...
ddemidov/amgcl
tutorial/1.poisson3Db/plot.py
Python
mit
348
# 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/compute/azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/_configuration.py
Python
mit
3,341
from .base import PInstruction from ..ptypes import PType class Ixa(PInstruction): """Indexed address computation: STORE[SP - 1] := STORE[SP - 1] + STORE[SP] * q SP := SP - 1 """ def __init__(self, q: int) -> None: self.q = q def emit(self) -> str: return 'ixa...
Sibert-Aerts/c2p
src/c2p/instructions/array.py
Python
mit
1,343
from __future__ import print_function import logging class ShutItSendSpec(object): """Specification for arguments to send to shutit functions. """ def __init__(self, shutit_pexpect_child, send=None, send_dict=None, expect=None, timeout=None, ...
ianmiell/shutit
shutit_sendspec.py
Python
mit
15,169
from os.path import join import sh from pythonforandroid.recipe import NDKRecipe from pythonforandroid.util import current_directory from pythonforandroid.logger import shprint from multiprocessing import cpu_count class OpenCVRecipe(NDKRecipe): ''' .. versionchanged:: 0.7.1 rewrote recipe to support ...
kronenpj/python-for-android
pythonforandroid/recipes/opencv/__init__.py
Python
mit
6,295
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "iriot.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
j-windsor/iRiot-WebApp
manage.py
Python
mit
248
"""This module defines the core CLF spidering API. For example, a spider author creates a spider by creating a new class which derives from :py:class:`Spider`. Next the spider author implements a :py:meth:`Spider.crawl` which returns an instance of :py:class:`CrawlResponse`. Both :py:class:`Spider` and :py:class:`Crawl...
simonsdave/cloudfeaster
cloudfeaster/spider.py
Python
mit
40,751
import os import pytest from pre_commit_hooks.check_symlinks import check_symlinks from testing.util import get_resource_path @pytest.mark.xfail(os.name == 'nt', reason='No symlink support on windows') @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('broken_symlink', 1), ('working_symlink', 0),...
Coverfox/pre-commit-hooks
tests/check_symlinks_test.py
Python
mit
466
import requests from requests.auth import AuthBase from requests.auth import HTTPBasicAuth auth = HTTPBasicAuth('ryan', 'password') r = requests.post(url="http://pythonscraping.com/pages/auth/login.php", auth=auth) print(r.text)
sunrin92/LearnPython
2-WebScrapingWithPython/auth.py
Python
mit
232
import numpy as np import cv2 from matplotlib import pyplot as plt imgL=cv2.imread('left.png',0) imgR=cv2.imread('right.png',0) stereo=cv2.StereoBM_create(numDisparities=16, blockSize=15) disparity=stereo.compute(imgL,imgR) plt.imshow(disparity,'gray') plt.show()
arpan-bhowmick9/Image-Processing
Disparity Map/Disparity_Map.py
Python
mit
265
import os # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from model import CRNN, CtcCriterion from dataset import DatasetLmdb, SynthLmdb import tensorflow as tf import numpy as np import signal import utility import sys import time class Conf: def __init__(self): self.nClasses = 36 self.trainBatchSize = 64 self.eva...
wcy940418/CRNN-end-to-end
src/training.py
Python
mit
5,128
print(" # db_api.py") # from abc import ABCMeta, abstractmethod from sqlalchemy.exc import IntegrityError from basic_wms.model import db_model class CRUDsAbstractBase: """ Kinda abstract base class. """ @classmethod def create(cls, *args, **kwargs): raise NotImplementedEr...
pawelswiecki/basic-wms
basic_wms/model/db_api.py
Python
mit
12,060
""" ha_test.test_component_group ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests the group compoments. """ # pylint: disable=protected-access,too-many-public-methods import unittest from datetime import datetime, timedelta import logging import os import homeassistant as ha import homeassistant.loader as loader from homeassistant...
loghound/home-assistant
ha_test/test_component_device_scanner.py
Python
mit
7,036
#!/usr/bin/env python3 def main(): nx = 200 ny = 100 print("P3\n",nx," ",ny,"\n255") for j in reversed(range(ny)): for i in range(nx): r = i / nx g = j / ny b = 0.2 ir = int(255.99*r) ig = int(255.99*g) ib = int(255.99*b) print(ir," ",ig," ",ib) if __name__ == '_...
fernandomv3/raytracing_in_one_week
ch01/raytracer.py
Python
mit
338
import serial import io import win32gui import win32api import win32con import sys import time from math import atan2,cos def LeftClick(): pos = get_curpos() handle = get_win_handle(pos) client_pos = win32gui.ScreenToClient(handle, pos) tmp = win32api.MAKELONG(client_pos[0], client_pos[1]...
MandarGogate/AM-AIR-MOUSE
Mouse-Driver.py
Python
cc0-1.0
5,379
#coding:utf-8 from threading import Thread from queue import Queue import paramiko import time class Thread_Paramiko(Thread): ''' paramiko 多线程实现命令分发 ''' def __init__(self,UserInfo): super(Thread_Paramiko,self).__init__()#初始化父类 '''__CmdQueue是C...
HuangeHei/ThreadParamiko
_Thread_Distribution/model/Thread_Paramiko.py
Python
gpl-2.0
4,584
import pymongo __author__ = 'jslvtr' class Database(object): URI = "mongodb://127.0.0.1:27017" DATABASE = None @staticmethod def initialize(): client = pymongo.MongoClient(Database.URI) Database.DATABASE = client['fullstack'] @staticmethod def insert(collection, data): ...
brunotougeiro/python
udemy-python-web-apps/terminal_blog/database.py
Python
gpl-2.0
591
"""datatable.py """ import json, logging, pytz from flask import current_app, g from datetime import datetime, time, date, timedelta from app import get_keys from app.lib.timer import Timer log = logging.getLogger(__name__) #------------------------------------------------------------------------------- def get_data(...
SeanEstey/Bravo
app/main/datatable.py
Python
gpl-2.0
1,043
# Generated by Django 2.0 on 2018-05-16 02:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180515_1458'), ('falta', '0004_auto_20180515_2221'), ] operations = [ ...
diaspa-nds/cfar
falta/migrations/0005_auto_20180515_2309.py
Python
gpl-2.0
823
"""Django URL configuration for unrecognized neighbors system.""" from django.conf.urls import patterns, url urlpatterns = patterns( 'nav.web.neighbors.views', url(r'^$', 'index', name='neighbors-index'), url(r'neighbor-state/', 'set_ignored_state', name='neighbors-set-state'), )
sigmunau/nav
python/nav/web/neighbors/urls.py
Python
gpl-2.0
294
# -*- coding: utf-8 -*- from __future__ import absolute_import from builtins import range import os from qgis.PyQt import QtGui, uic from qgis.PyQt.QtCore import pyqtSignal, pyqtSlot, Qt import math from qgis.PyQt import QtCore, QtGui from qgis.PyQt.QtWidgets import QShortcut from qgis.PyQt.QtGui import QKeySequence ...
lcoandrade/DsgTools
gui/ProductionTools/MapTools/Acquisition/circle.py
Python
gpl-2.0
2,590