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 |
|---|---|---|---|---|---|
# Copyright (c) 2008, 2010 Aldo Cortesi
# Copyright (c) 2009 Ben Duffield
# Copyright (c) 2010 aldo
# Copyright (c) 2010-2012 roger
# Copyright (c) 2011 Florian Mounier
# Copyright (c) 2011 Kenji_Takahashi
# Copyright (c) 2011-2015 Tycho Andersen
# Copyright (c) 2012-2013 dequis
# Copyright (c) 2012 Craig Barnes
# Copy... | soulchainer/qtile | libqtile/widget/groupbox.py | Python | mit | 13,561 |
import datetime
from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template
class TimeTopicPlugin(WillPlugin):
# Disabled for now.
# @periodic(minute='0')
def set_topic_time(self):
now_pst = datetime.datetime.now()
now_bcn ... | skoczen/my-will | plugins/time_topic.py | Python | mit | 799 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from fairseq.utils import new_arange
# -------------- Helper Functions --------------------------------------------------- #
... | pytorch/fairseq | fairseq/models/nat/levenshtein_utils.py | Python | mit | 9,508 |
'''
@author: Sergio Rojas
@contact: rr.sergio@gmail.com
--------------------------
Contenido bajo
Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)
http://creativecommons.org/licenses/by-nc-sa/3.0/ve/
Creado en abril 21, 2016
'''
def fog(g,x):
return ((g(x))**2 + 3)
def g(x):
return (6... | rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador | Programas_Capitulo_05/Cap05_pagina_115.py | Python | mit | 369 |
from office365.runtime.client_value import ClientValue
class SPSiteCreationRequest(ClientValue):
def __init__(self, title, url, owner=None):
super(SPSiteCreationRequest, self).__init__()
self.Title = title
self.Url = url
self.WebTemplate = "SITEPAGEPUBLISHING#0"
self.Owner... | vgrem/Office365-REST-Python-Client | office365/sharepoint/portal/site_creation_request.py | Python | mit | 780 |
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
def ClearLandscape():
# set air layer
# (x1, y1, z1, x2, y2, z2, blockID, blockState)
mc.setBlocks(-248, 1, -248, 248, 248, 248, 0)
# set layer of podzal
mc.setBlocks(-248, 0, 0, 248, -3, 248, 3, 2)
# set layer of mushrooms
# mc.setBl... | cssidy/minecraft-hacks | building/mushroomFields.py | Python | mit | 414 |
#!/usr/bin/python3
import pygame
import os
import random
from Target import *
class Train(pygame.sprite.Sprite, Target):
maxWait = 30 # 30# maximum time we can wait for new train after old one is gone
def __init__(self, FPS):
pygame.sprite.Sprite.__init__(self)
Target.__init__(self, True,'tra... | kubapok/tank-game | Train.py | Python | mit | 8,587 |
from urllib import request
from PyQt5.QtCore import QThread
class Downloader(QThread):
def __init__(self, wrapper, icon, path):
QThread.__init__(self)
self.wrapper = wrapper
self.icon = icon
self.path = path
def run(self):
try:
file_name, headers = request... | raelgc/scudcloud | scudcloud/downloader.py | Python | mit | 429 |
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from htsohm.db import Base
class GasLoading(Base):
__tablename__ = "gas_loadings"
id = Column(Integer, primary_key=True)
# relationship with `materials`
material_id = Column(Integer, ForeignKey("materials.id"))
# simulation input... | akaija/HTSOHM-dev | htsohm/db/gas_loading.py | Python | mit | 1,295 |
import os
ROOT = '/sdcard/realdata/'
SEGMENT_LENGTH = 60
| heidecjj/openpilot | selfdrive/loggerd/config.py | Python | mit | 58 |
from office365.runtime.client_value import ClientValue
class SecondaryAdministratorsInfo(ClientValue):
def __init__(self, email=None, loginName=None, userPrincipalName=None):
"""
:param str email:
:param str loginName:
:param str userPrincipalName:
"""
super(Secon... | vgrem/Office365-REST-Python-Client | office365/sharepoint/tenant/administration/secondary_administrators_info.py | Python | mit | 474 |
"""
Django settings for creativejunkiez project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bu... | anistark/creativejunkiez | creativejunkiez/settings.py | Python | mit | 2,716 |
from account.forms import SignupForm
def signup(request, form_class=SignupForm,
template_name="account/signup.html", success_url=None):
if success_url is None:
success_url = get_default_redirect(request)
if request.method == "POST":
form = form_class(request.POST)
if form.is_va... | ingenieroariel/pinax | apps/signup_codes/views.py | Python | mit | 1,430 |
# -*- coding: utf-8 -*-
try:
from django.urls import get_script_prefix, set_script_prefix
except ImportError:
from django.core.urlresolvers import get_script_prefix, set_script_prefix
class script_prefix(object):
def __init__(self, newpath):
self.newpath = newpath
self.oldprefix = get_scri... | ierror/django-js-reverse | django_js_reverse/tests/utils.py | Python | mit | 489 |
from builtins import map
from builtins import range
from builtins import object
import unittest
import ROOT
import os
from PyAnalysisTools.PlottingUtils import HistTools as ht
from PyAnalysisTools.base import InvalidInputError
cwd = os.path.dirname(__file__)
ROOT.gROOT.SetBatch(True)
class PlotConfig(object):
pa... | morgenst/PyAnalysisTools | tests/unit/TestHistTools.py | Python | mit | 6,722 |
import sys
import argparse
import json
from controllers.TwitterDumpController import *
from controllers.SentiWordNetController import *
import dateutil.parser
def main():
parser = argparse.ArgumentParser(description="Generates sentiment analysis data a")
parser.add_argument("file", type=str, default="", help... | victorpopescu/TwitterStockAnalyzer | main.py | Python | mit | 3,882 |
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.jit.backend.llsupport.codemap import CodemapStorage, \
CodemapBuilder, unpack_traceback, find_codemap_at_addr
NULL = lltype.nullptr(rffi.CArray(lltype.Signed))
def test_register_codemap():
codemap = CodemapStorage()
codemap.setup()
... | oblique-labs/pyVM | rpython/jit/backend/llsupport/test/test_codemap.py | Python | mit | 1,455 |
digits = [0 for i in range(10)]
for c in input():
digits[int(c)] += 1
sum = 0
for i in range(10):
sum += i * digits[i]
if sum % 3 != 0:
for i in range(10):
if digits[i] > 0 and (sum - i) % 3 == 0:
digits[i] -= 1
sum -= i
break
for step in range(2):
if sum %... | dluschan/school | olymp/divisible.py | Python | mit | 554 |
#!/usr/bin/env python
import os
from setuptools import setup
import versioneer
from pip.download import PipSession
from pip.req import parse_requirements
def get_requirements(filename):
''' Parse a pip-style requirements.txt file to setuptools format '''
install_reqs = parse_requirements(filename, session=P... | codetry/django_namespaced | setup.py | Python | mit | 1,442 |
import gc
import inspect
exclude = [
"function",
"type",
"list",
"dict",
"tuple",
"wrapper_descriptor",
"module",
"method_descriptor",
"member_descriptor",
"instancemethod",
"builtin_function_or_method",
"frame",
"classmethod",
"classmethod_descriptor",
"_Env... | ActiveState/code | recipes/Python/457665_Debug_runtime_objects_using/recipe-457665.py | Python | mit | 952 |
import pytest
import sentlex.sentanalysis_potts as sentdoc
import sentlex
TESTDOC_ADJ = 'good/JJ good/JJ good/JJ good/JJ good/JJ good/JJ good/JJ good/JJ good/JJ good/JJ'
TESTDOC_UNTAGGED = 'this cookie is good. it is very good indeed'
TESTDOC_BADADJ = 'bad_JJ Bad_JJ bAd_JJ'
TESTDOC_NEGATED = 'not/DT bad/JJ movie/NN ... | bohana/sentlex | tests/test_potts.py | Python | mit | 2,316 |
# django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
import logging
from django.conf import settings
from django import template, shortcuts, http
from salesforce.testrunner.example import models, forms
log = logging.getLogger(... | chromakey/django-salesforce | salesforce/testrunner/example/views.py | Python | mit | 1,070 |
#! /usr/bin/python2
import json
import pycurl
from io import BytesIO
import time
import calendar
import datetime
import sys
import getopt
import socket
base_url = "http://" + socket.getfqdn() + ":19888"
begin_rel = 24 * 3600
end_rel = 0
utc = 0
debug = 0
try:
opts, args = getopt.getopt(sys.argv[1:], "hm:b:e:ud", [... | MetaCenterCloudPuppet/cesnet-site_hadoop | files/accounting/jobs.py | Python | mit | 3,427 |
import numpy as np
import matplotlib.pyplot as plt
import kernels
import random
import utils
class Regression(object):
def __init__(self, Ytrain, kernel=kernels.RBF(), add_noise=0.001, print_jit=False, Ytest=None, Xtest=None, Xtrain=None, cent_threshold=None):
self.Xtest = Xtest
self.Xtrain = Xtrain
self.Ytest... | nafisa1/Gaussian_processes | regression.py | Python | mit | 6,505 |
import factory
import factory.fuzzy
import pytz
from conferences.models import AudienceLevel, Conference, Deadline, Duration, Topic
from django.utils import timezone
from factory.django import DjangoModelFactory
from i18n.helpers.tests import LanguageFactory
from languages.models import Language
from pytest_factoryboy ... | patrick91/pycon | backend/conferences/tests/factories.py | Python | mit | 5,673 |
#/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from collections import OrderedDict
def slack_post(token, channel, blind=False):
'''Post a slack message possibly with a picture. Prepare a function that
will be called later by the main script.'''
slack_api_url = 'https://slack.com/api/{}'
... | nobe4/mini-sentry | slack.py | Python | mit | 1,345 |
import rq
from rq_retry_scheduler import Queue, Worker
def noop_target_function(*args, **kwargs):
pass
def fail_target_function(*args, **kwargs):
raise Exception("I am a failure of a function")
def test_init(worker):
assert worker.exc_handler in worker._exc_handlers
assert issubclass(worker.queue... | mikemill/rq_retry_scheduler | tests/test_worker.py | Python | mit | 2,523 |
# coding: utf-8
import flask
from apps.auth import helpers
from apps.user import models
from .import CONFIG
provider = helpers.make_provider(CONFIG)
bp = helpers.make_provider_bp(provider.name, __name__)
@bp.route('/authorized/')
def authorized():
resp = provider.authorized_response()
if resp is None:
retu... | gmist/3dhero2 | main/apps/auth/providers/instagram/views.py | Python | mit | 1,175 |
"""
Django settings for easter_egg project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | tavern-consulting/easter-egg | easter_egg/settings.py | Python | mit | 2,306 |
XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX XXXXXXX X XXXXX XXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXX... | dnaextrim/django_adminlte_x | adminlte/static/plugins/datatables/extensions/AutoFill/examples/simple.html.py | Python | mit | 16,348 |
# -*- coding: utf-8 -*-
from deliver.tests.test_base import BaseTest, load_msg, load_all_msg
class ConverterTest(BaseTest):
'''Tests for the UnicodeMessage class'''
def setUp(self):
super(ConverterTest,self).setUp()
self.msg = load_msg('sample3')
def get_text(self, decode=False):
... | sirech/deliver | deliver/tests/converter/test_converter.py | Python | mit | 5,147 |
"""Create Common Workflow Language (CWL) runnable files and tools from a world object.
"""
import copy
import functools
import json
import math
import operator
import os
import tarfile
import toolz as tz
import yaml
from bcbio import utils
from bcbio.cwl import defs, workflow
from bcbio.distributed import objectstore... | biocyberman/bcbio-nextgen | bcbio/cwl/create.py | Python | mit | 29,386 |
#!/usr/bin/env python
from random import randrange, choice
from string import ascii_lowercase as lc
# from sys import maxint
# 64 bit has a longer maxint
from time import ctime
tlds = ('com', 'edu', 'net', 'org', 'gov')
for i in xrange(randrange(5, 11)):
dtint = randrange(2**32) # pick date
dtstr = ctime... | MarsBighead/mustang | Python/gendata.py | Python | mit | 658 |
import json
import pika
class Consumer(object):
"""This class connects to RabbitMQ, binds an 'exchange' then begins receiving \
messages. It does not respond to the sender of the message, it only sends an \
acknowledgement."""
def __init__(self, rabbit_url, exchange, exchange_type, queue, routing_key... | projectweekend/Pika-Pack | pika_pack/async.py | Python | mit | 4,801 |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='pysnap',
version='0.1.1',
description='Snapchat API client in Python',
long_description=open('README.md').read(),
author='Martin Polden',
author_email='martin.polde... | martinp/pysnap | setup.py | Python | mit | 610 |
# -*- coding: utf-8 -*-
import scrapy
class NamedayItem(scrapy.Item):
day = scrapy.Field()
month = scrapy.Field()
official_names = scrapy.Field()
swedish_names = scrapy.Field()
same_names = scrapy.Field()
orthodox_names = scrapy.Field()
unofficial_names = scrapy.Field()
| spedepekka/finnish-namedays | extractor/items.py | Python | mit | 301 |
# -*- coding: utf-8 -*-
#
# statistical physics documentation build configuration file, created by
# sphinx-quickstart on Tue May 27 11:24:59 2014.
#
# 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... | emptymalei/statisticalphysics | conf.py | Python | mit | 18,471 |
"""Auto-generated file, do not edit by hand. BN metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BN = PhoneMetadata(id='BN', country_code=673, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[2-578]\\d{6}', possible_number_pattern=... | ayushgoel/FixGoogleContacts | phonenumbers/data/region_BN.py | Python | mit | 1,815 |
from django.conf.urls import re_path
from .views import (
proposal_submit,
proposal_submit_kind,
proposal_detail,
proposal_edit,
proposal_speaker_manage,
proposal_cancel,
proposal_pending_join,
proposal_pending_decline,
document_create,
document_delete,
document_download,
)
... | pydata/conf_site | symposion/proposals/urls.py | Python | mit | 1,453 |
# coding: utf-8
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter):
resource_mapping = RESOURCE_MAPPING
api_root = 'ht... | vintasoftware/tapioca-harvest | tapioca_harvest/tapioca_harvest.py | Python | mit | 1,269 |
# coding: utf-8
import datetime
import pytz
from django.test import TestCase
from ditto.core.utils import datetime_from_str
from ditto.pinboard.factories import AccountFactory, BookmarkFactory
from ditto.pinboard.templatetags import ditto_pinboard
class TemplatetagsRecentBookmarksTestCase(TestCase):
def setUp(s... | philgyford/django-ditto | tests/pinboard/test_templatetags.py | Python | mit | 7,579 |
import os
import testinfra
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
"build-essential",
"bzip2",
"curl",
"libssl-dev",
"locales"... | MSA-Argentina/ansible-roles | server-bootstrap/molecule/default/tests/test_default.py | Python | mit | 768 |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import Join, MapCompose, TakeFirst
import datetime
DATE_OUTPUT_FORMAT = '%m/%d/%Y %H:%M:%S %Z'
BOOKING_DATE_INPUT_FORMAT = '%m/%d/%Y %H:%M:%S'
class GwinnettInmate(scrapy.Item):
county_name = scrapy.Field()... | lahoffm/aclu-bail-reform | src/webscraper/gwinnett/gwinnett/items.py | Python | mit | 3,640 |
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from vanilla import CreateView, DetailView
from arcade.games.forms import NewGameForm
from arcade.games.models import Game
class CreateNewGameView(LoginRequiredMixin, CreateView):
model = Game
form_class = NewGameForm
temp... | Osmose/arcade | arcade/games/views.py | Python | mit | 735 |
import numpy as np
import pandas as pd
from collections import defaultdict
def predict(trees, examples):
n_rows, _ = examples.shape
results = pd.DataFrame(index=range(n_rows), columns=trees.keys())
results["prediction"] = pd.Series(index=range(n_rows))
for column in results.columns:
results[co... | MLNotWar/decision-trees-algorithm | src/predictor.py | Python | mit | 972 |
"""
Django settings for wtf_proj project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
from os.... | TimelyToga/wtf_is | wtf_proj/wtf_proj/settings.py | Python | mit | 3,721 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserTestCase(IntegrationT... | tysonholub/twilio-python | tests/integration/chat/v1/service/test_user.py | Python | mit | 10,034 |
def middle_way(a, b):
return [a[1],b[1]]
print(middle_way([1, 2, 3], [4, 5, 6])) # [2, 5]
print(middle_way([7, 7, 7], [3, 8, 0])) # [7, 8]
print(middle_way([5, 2, 9], [1, 4, 5])) # [2, 4] | frainfreeze/studying | projects/practice/other/022.py | Python | mit | 190 |
# coding=utf-8
import pickle
from petsc4py import PETSc
import numpy as np
from scipy.io import savemat
# filename = 'sphere'
# with open(filename + '_pick.bin', 'rb') as input:
# unpick = pickle.Unpickler(input)
#
# viewer = PETSc.Viewer().createBinary(filename + '_M.bin', 'r')
# M = PETSc.Mat().create(comm=PETSc... | pcmagic/stokes_flow | try_code/try_pickle.py | Python | mit | 1,266 |
from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
low = 0
high = len(nums) - 1
while high - low > 1:
mid = (low + high) // 2
left_ele = nums[mid-1]
mid_ele = nums[mid]
right_ele = nums[mid+1]
... | daicang/Leetcode-solutions | 162-find-peak-element.py | Python | mit | 977 |
# -*- encoding: utf-8 -*-
from supriya.tools.ugentools.InfoUGenBase import InfoUGenBase
class BlockSize(InfoUGenBase):
r'''A block size info unit generator.
::
>>> ugentools.BlockSize.ir()
BlockSize.ir()
'''
### CLASS VARIABLES ###
__documentation_section__ = 'Info UGens'
... | andrewyoung1991/supriya | supriya/tools/ugentools/BlockSize.py | Python | mit | 545 |
from datahandle import Vault
if __name__ == '__main__':
print('This program cannot be run in DOS mode')
| CleyFaye/FOS_View | fosfile/__init__.py | Python | mit | 110 |
import numpy as np
import random
from matplotlib import pyplot as plt
from matplotlib import animation
from collections import deque
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization ... | meclav/whistle | src/playground/plottingworks.py | Python | mit | 1,444 |
def baseurl(url):
return url[:url.rfind('/')]
def is_installed(settings):
"""
Check Django settings and verify that tinymce application is included
in INSTALLED_APPS to be sure that staticfiles will work properly and
serve required files.
"""
if not hasattr(settings, 'INSTALLED_APPS'):
... | dani0805/django-tinymce4 | tinymce/utils.py | Python | mit | 5,268 |
"""Get optimal contraction sequence using netcon algorithm
Reference:
R. N. C. Pfeifer, et al.: Phys. Rev. E 90, 033315 (2014)
"""
__author__ = "Satoshi MORITA <morita@issp.u-tokyo.ac.jp>"
__date__ = "24 March 2016"
import sys
import logging
import time
import config
import itertools
class TensorFrame:
"""... | smorita/Tensordot | netcon.py | Python | mit | 5,072 |
"""Tests for DecisionTree.py on data sets."""
import importlib.util
import DecisionTree
spec = importlib.util.spec_from_file_location("tester", "../common/Tester.py")
tester = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tester)
def __train(training_set):
tree = DecisionTree.ClassificationTree()... | FelixOpolka/Statistical-Learning-Algorithms | decision tree/DecisionTreeTests.py | Python | mit | 885 |
#encoding:utf-8
subreddit = 'Texans'
t_channel = '@r_texans'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100, check_dups=True)
| Fillll/reddit2telegram | reddit2telegram/channels/r_texans/app.py | Python | mit | 175 |
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
'''
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
... | gavinfish/leetcode-share | python/153 Find Minimum in Rotated Sorted Array.py | Python | mit | 899 |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
def posts():
print "Reading posts..."
data = pd.read_csv("data/posts.csv", dtype={'cooked': np.str}, na_values=[],
keep_default_na=False, encoding="utf-8")
return data | rux-pizza/discourse-analysis | data.py | Python | mit | 267 |
from collections import deque
class AhoCorasick(object):
def __init__(self, keywords):
self.adj_list = []
self.adj_list.append({
"value" : "",
"next_states" : [],
"fail_state" : 0,
"output" : []
})
self.add_keywords(keyword... | shams-sam/logic-lab | AhoCorasick/aho_corasick.py | Python | mit | 3,132 |
#!/usr/bin/env python
# coding=utf-8
import logging
import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.httpclient
import tornado.escape
import tornado.locale
import tornado.websocket
import tornado.httpserver
import tornado.options
from tornado.options import define, options
options.logging =... | tao12345666333/Talk-Is-Cheap | python/tornado/web/base.py | Python | mit | 2,228 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Parsing FARS vehicle CSV files and putting them into DB
"""
import csv
import sys
import os
from db_api import person
from db_api import accident
from db_api import vehicle
from fars_person_mapper import FARSPersonMapper
from fars_accident_mapper import FARSAccidentMappe... | lopiola/integracja_wypadki | scripts/fars_per_year_parser.py | Python | mit | 5,825 |
"""ethdeveloper URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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')
Clas... | ethdeveloper/ethdeveloper | ethdeveloper/urls.py | Python | mit | 1,296 |
import databench
import math
import random
class Angular(databench.Analysis):
@databench.on
def connected(self):
"""Run as soon as a browser connects to this."""
inside = 0
for draws in range(1, 10000):
# generate points and check whether they are inside the unit circle
... | svenkreiss/databench_examples | analyses/angular/analysis.py | Python | mit | 1,068 |
from ansiblelint import AnsibleLintRule
class SudoRule(AnsibleLintRule):
id = 'ANSIBLE0008'
shortdesc = 'Deprecated sudo'
description = 'Instead of sudo/sudo_user, use become/become_user.'
tags = ['deprecated']
def _check_value(self, play_frag):
results = []
if isinstance(play_fr... | dataxu/ansible-lint | lib/ansiblelint/rules/SudoRule.py | Python | mit | 1,047 |
import pygame
#pickle is necessary to load our pickled frame values
import pickle
#Player extends the pygame.sprite.Sprite class
class Player(pygame.sprite.Sprite):
#In the main program, we will pass a spritesheet and x-y position values to the constructor
def __init__(self, position, spritesheet):
py... | xorobabel/pygame-2d-jrpg-demo | player.py | Python | mit | 4,622 |
"""
This module holds all view functions for the authentication module.
These functions include the following:
"""
from flask import Blueprint, flash, redirect, render_template, request, session, url_for
from app import logger
from app.mod_auth.form import LoginForm, RegistrationForm
from app.mod_auth.helper import ... | Zillolo/mana-vault | app/mod_auth/controller.py | Python | mit | 3,639 |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'name': 'StegaTonic',
'description': 'StegaTonic',
'author': 'Michael Dubell',
'url': 'https://github.com/mjdubell/stegatonic',
'download_url': 'https://github.com/mjdube... | mjdubell/stegatonic | setup.py | Python | mit | 524 |
# vim:ts=4:sts=4:sw=4:expandtab
"""The core of the system. Manages the database and operational logic. Functionality is
exposed over Thrift.
"""
import sys
import os
def manage():
from django.core.management import execute_manager
settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sator... | zielmicha/satori | satori.core/satori/core/__init__.py | Python | mit | 876 |
from ..errors import ImproperResponseError
import ipdb
class CrowdResponse(object):
crowd_request = None
method = None
status = None
task = None
response = None
path = None
def __init__(self, response, crowd_request, task):
try:
self.task = task
self.crowd_r... | Project-EPIC/crowdrouter | crowdrouter/context/crowdresponse.py | Python | mit | 749 |
# Generated by Django 2.2 on 2020-03-10 19:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('huntserver', '0052_remove_puzzle_num_pages'),
]
operations = [
migrations.AlterField(
model_name='team',
name='playtes... | dlareau/puzzlehunt_server | huntserver/migrations/0053_auto_20200310_1503.py | Python | mit | 749 |
import AppKit
from vanilla import VanillaBaseObject
columnPlacements = dict(
leading=AppKit.NSGridCellPlacementLeading,
center=AppKit.NSGridCellPlacementCenter,
trailing=AppKit.NSGridCellPlacementTrailing,
fill=AppKit.NSGridCellPlacementFill
)
rowPlacements = dict(
top=AppKit.NSGridCellPlacementTop... | typesupply/vanilla | Lib/vanilla/vanillaGridView.py | Python | mit | 17,625 |
import matplotlib
matplotlib.use('Agg')
import numpy as np
import scipy.stats
import matplotlib.pylab as plt
from .context import aep, ep
np.random.seed(42)
import pdb
def plot_model_no_control(model, plot_title='', name_suffix=''):
# plot function
mx, vx = model.get_posterior_x()
mins = np.min(mx, axis=0... | thangbui/geepee | examples/gpssm_hodgkin_huxley.py | Python | mit | 14,316 |
##################################################
#
# test_dev_parse.py - development tests
#
##################################################
import sys, unittest, re
sys.path.append("/home/gwatson/Work/GP4/src")
try:
from GP4.GP4_CompilerHelp import compile_string
import GP4.GP4_Exceptions
except ImportEr... | GregWatson/GP4 | UnitTests/test_dev_parse.py | Python | mit | 19,708 |
name = " "
while name != "nimesi":
print("Kirjoita nimesi.")
name =raw_input()
print ("Kiitos!")
| GenericUser666/Hienot_skriptit | your_name.py | Python | mit | 101 |
#!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 10/19/14
###Function: OR of incidence in adults to incidence in children vs. week number normalized by the first 'gp_normweeks' of the season. Incidence in children and adults is normalized by the size... | eclee25/flu-SDI-exploratory-age | scripts/create_fluseverity_figs_v4/F_zRR_time_v4.py | Python | mit | 3,552 |
"""
Udacity CS253 - Lesson 4 - Homework 1
"""
import webapp2, jinja2, os, handlers
app = webapp2.WSGIApplication([
('/signup', handlers.SignupPage),
('/welcome', handlers.WelcomePage),
('/login', handlers.LoginPage),
('/logout', handlers.LogoutPage)
], debug=True) | vcelis/cs253 | lesson4/homework1-3/login.py | Python | mit | 277 |
# Generated by Django 2.1.2 on 2019-01-28 07:07
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Account",
fields=[
... | MicroPyramid/Django-CRM | accounts/migrations/0001_initial.py | Python | mit | 3,797 |
import _plotly_utils.basevalidators
class HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator):
def __init__(self, plotly_name="hoverinfo", parent_name="scattercarpet", **kwargs):
super(HoverinfoValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_na... | plotly/plotly.py | packages/python/plotly/plotly/validators/scattercarpet/_hoverinfo.py | Python | mit | 594 |
#!/usr/bin/env python3
from zipstream import ZipStream
files = [
{'stream': [b'this\n', b'is\n', b'stream\n', b'of\n',b'data\n'],
'name': 'a.txt',
'compression':'deflate'},
{'file': '/tmp/z/car.jpeg'},
{'file': '/tmp/z/aaa.mp3',
'name': 'music.mp3'},
]
zs = ZipStream(files)
with open("exam... | m2ozg/zipstream | examples/simple.py | Python | mit | 399 |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""),... | stankovski/AutoRest | AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py | Python | mit | 5,390 |
#!/usr/local/bin/python3.5
import time
import math
import os
import shutil
import tempfile
from six.moves import configparser
from yattag import Doc
import asyncio
import aiohttp
import async_timeout
import json
# Read config file in
mydir = os.path.dirname(os.path.realpath(__file__))
configReader = configparser.RawCo... | AlucardZero/python-rift-event-tracker | events.py | Python | mit | 4,983 |
#!/usr/bin/env python
# SMTP transmission with authentication - Chapter 13 - login.py
import sys, smtplib, socket
from getpass import getpass
if len(sys.argv) < 4:
print "Syntax: %s server fromaddr toaddr [toaddr...]" % sys.argv[0]
sys.exit(2)
server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:... | jac2130/BayesGame | foundations-of-python-network-programming/python2/13/login.py | Python | mit | 1,130 |
"""Model based on VGG16:
# Reference
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
Code based on the original Keras library implementation source code
"""
import warnings
import tensorflow as tf
from keras.models import Model
from keras.layers import Flatt... | kaykanloo/msc-project | Code/Models/VGGLowPool4.py | Python | mit | 3,160 |
'''
The MIT License (MIT)
Copyright (c) 2013-2017 Robert H Chase
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,... | Shatnerz/rhc | rhc/resthandler.py | Python | mit | 17,999 |
import sys
import yaml
import os
import imp
import logging
from src import annotation_dispatcher, annotation_worker
from src import generation_dispatcher, generation_worker
from src import classification_dispatcher, classification_worker
__name__ = "bayzee"
def __loadConfig(configFilePath):
config = None
if not o... | pandastrike/bayzee | __init__.py | Python | mit | 5,154 |
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2015 by Openname.org
:license: MIT, see LICENSE for more details.
"""
from functools import wraps
from flask import request, Response
from .config import API_USERNAME, API_PASSWORD
# -------------------------------------
def check_auth(username, password):
"""T... | jetbox/resolver | server/helper.py | Python | mit | 1,104 |
from __future__ import unicode_literals
from rest_framework import pagination
from rest_framework import serializers
class BongoPagination(pagination.PageNumberPagination):
page_size = 20
page_size_query_param = 'limit'
max_page_size = 100
| BowdoinOrient/bongo | bongo/apps/api/pagination.py | Python | mit | 255 |
#!/usr/bin/env python3
import asyncio
from threading import Thread
from bottle import static_file, route, run
from app import Server
def serve_web():
while True:
@route('/')
def index():
static_file('index.css', root='./app')
static_file('client.js', root='./app')
... | mikoim/funstuff | codecheck/codecheck-2160/run.py | Python | mit | 793 |
from django.conf.urls import url
from . import views, api
app_name = 'event'
urlpatterns = [
# event/
url(r'^$',
views.EventIndexView.as_view(),
name='index'),
# event/1/detail
url(r'^(?P<pk>[0-9]+)/$',
views.EventDetailView.as_view(),
name='detail'),
# event/1/d... | internship2016/sovolo | app/event/urls.py | Python | mit | 2,784 |
#!/usr/bin/env python
import argparse
import sys
from lxml import etree
sys.path.append('./lib')
from jnpr.junos import Device
from pypeer.ConfigDictionary import ConfigDictionary
from pypeer.BgpData import BgpData
from pypeer.Exchange import Exchange
from pypeer.PeeringDBClient import PeeringDBClient
from pypeer.Pe... | andydavidson/pypeer | bin/get_myexchanges_connected.py | Python | mit | 2,290 |
import re
from pyinfra import logger
from pyinfra.api import FactBase
from .util.packaging import parse_packages
BREW_REGEX = r'^([^\s]+)\s([0-9\._+a-z\-]+)'
def new_cask_cli(version):
'''
Returns true if brew is version 2.6.0 or later and thus has the new CLI for casks.
i.e. we need to use bre... | Fizzadar/pyinfra | pyinfra/facts/brew.py | Python | mit | 2,296 |
import argparse
import os
from fontTools.ttLib import TTFont
from fontTools import subset
def makeWeb(args):
""" Generate TTF/WOFF/WOFF2 fonts """
font = TTFont(args.file)
## TODO: We can remove specialized glyphs, stylistic sets,
## etc. that are not useful on the web in order to minimize the
##... | bateni/qalam-tarash | tools/makeweb.py | Python | mit | 930 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
usage: chcount.py [-u] [file ...]
Lists each character with non-zero count along with count. Non-printable
characters have ASCII labels or meta-char escapes, as per python
curses.ascii.
The -u option reports only unused byte codes.
Usual read of files from command line a... | evanvliet/vw | tools/chcount.py | Python | mit | 1,512 |
import socket
import selectors
import types
import os
import sys
import imp
import json
import logging
from urllib.parse import splitnport as parse_addr
from threading import Thread
from thinrpc.message import RpcMessage
from thinrpc.client import RpcRemote
from thinrpc import logger, RECV_SIZE, ENC, OK
############... | anrosent/thinrpc | thinrpc/server.py | Python | mit | 6,073 |
# 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/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2018_01_22/operations/_iot_hub_resource_operations.py | Python | mit | 99,409 |
'''This module implements a factory pattern to licenses
'''
import pkgutil
import importlib
import os
class LicenseFactory:
@staticmethod
def get(name='gpl'):
license = GeneralLicense
pack, factory_file = os.path.split(__file__)
modnames = [m for _,m,_ in pkgutil.iter_modules([pack])... | nullhack/python-template | licenses/util.py | Python | mit | 1,153 |
def permute(sequence):
"Given an input sequence, generate all permutations of that sequence."
if not sequence:
return []
perms = [tuple()]
for elem in sequence:
next_perms = []
for perm in perms:
for next_perm in _add_element(perm, elem):
next_perms.ap... | calebperkins/algorithms | algorithms/permutations.py | Python | mit | 565 |
import datetime
from bson import ObjectId
from pymongo import MongoClient, DESCENDING, ASCENDING
__author__ = 'Peipei YI'
# connect on the default host and port
client = MongoClient()
# connect on a specific host and port
# client = MongoClient('localhost', 27017)
# connect by the MongoDB URI format
# client = Mo... | yipeipei/peppy | _tryout/try_mongo.py | Python | mit | 4,344 |
import telebot
import logging
from apscheduler.schedulers.background import BackgroundScheduler
from plugins.bot import BotBot
from plugins.bug import BugBot
from plugins.zao import ZaoBot
from plugins.help import HelpBot
from plugins.event import EventBot
telebot.logger.setLevel(logging.DEBUG)
def readfile(filename... | huiyiqun/zaobot | start.py | Python | mit | 630 |