code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
#!/usr/bin/python3
# Copyright (c) 2015 Davide Gessa
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from libcontractvm import Wallet, WalletExplorer, ConsensusManager
from forum import ForumManager
import sys
import time
consMan ... | andreasscalas/dappforum | samples/vote.py | Python | mit | 734 |
# -*- coding: utf-8 -*-
"""
Production Configurations
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis for cache
- Use sentry for error logging
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
fro... | bhanduroshan/fbstats-docker | config/settings/production.py | Python | mit | 8,125 |
from path import Path
import zipfile
import urllib2
Path('tmp').mkdir_p()
for model_name in ('seq2seq','seq2tree'):
for data_name in ('jobqueries','geoqueries','atis'):
fn = '%s_%s.zip' % (model_name, data_name)
link = 'http://dong.li/lang2logic/' + fn
with open('tmp/' + fn, 'wb') as f_out:
f_out.... | donglixp/lang2logic | pull_data.py | Python | mit | 486 |
# encoding: utf-8
# pylint: disable=too-few-public-methods,invalid-name,bad-continuation
"""
RESTful API Auth resources
--------------------------
"""
import logging
from flask_login import current_user
from flask_restplus_patched import Resource
from flask_restplus._http import HTTPStatus
from werkzeug import securi... | frol/flask-restplus-server-example | app/modules/auth/resources.py | Python | mit | 2,283 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "InBrowserEditor.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| PaulFlorea/InBrowserPreviewer | manage.py | Python | mit | 258 |
"""
Copyright (C) 2012 Alan J Lockett
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, distribute,... | hypernicon/pyec | pyec/distribution/pso.py | Python | mit | 4,812 |
__all__ = ['chatcommand', 'execute_chat_command', 'save_matchsettings', '_register_chat_command']
import functools
import inspect
from .events import eventhandler, send_event
from .log import logger
from .asyncio_loop import loop
_registered_chat_commands = {} # dict of all registered chat commands
async def exe... | juergenz/pie | src/pie/chat_commands.py | Python | mit | 3,649 |
#! /usr/bin/python3
"""Callback a callable asset."""
import struct
import decimal
D = decimal.Decimal
from . import (util, config, exceptions, litecoin, util)
from . import order
FORMAT = '>dQ'
LENGTH = 8 + 8
ID = 21
def validate (db, source, fraction, asset, block_time, block_index, parse):
cursor = db.curso... | Paytokens/paytokensd | lib/callback.py | Python | mit | 6,281 |
from __future__ import unicode_literals
import logging
# Logging configuration
log = logging.getLogger(__name__) # noqa
log.addHandler(logging.NullHandler()) # noqa
from netmiko.ssh_dispatcher import ConnectHandler
from netmiko.ssh_dispatcher import ssh_dispatcher
from netmiko.ssh_dispatcher import redispatch
from ne... | fooelisa/netmiko | netmiko/__init__.py | Python | mit | 1,198 |
from django.conf.urls import patterns, url
from .views import FeedList, ImportView, AddView
from .ajax import mark_as_read
urlpatterns = patterns(
'',
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(),
name='feedme-feed-list-by-... | gotlium/django-feedme | feedme/urls.py | Python | mit | 686 |
from modules.chart_module import ChartModule
import tornado.web
import logging
class LineChartModule(ChartModule):
def render(self, raw_data, keys, chart_id="linechart"):
self.chart_id = chart_id
self.chart_data = self.overtime_linechart_data(raw_data, keys)
return self.render_string('mod... | SFII/cufcq-new | modules/linechart_module.py | Python | mit | 5,898 |
# Copyright 2017 Thomas Sterrenburg
#
# Licensed under the MIT License (the License); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at https://opensource.org/licenses/MIT#
import glob
import re
import sys
import time
from src.io.storage import get_request_i... | thomas-sterrenburg/fingerprinting-python | src/main.py | Python | mit | 16,603 |
class Board(object):
"""This class defines the board"""
def __init__(self, board_size):
"""The initializer for the class"""
self.board_size = board_size
self.board = []
for index in range(0, self.board_size):
self.board.append(['0'] * self.board_size)
def is_on... | jonbrohauge/pySudokuSolver | board.py | Python | mit | 1,589 |
# -*- coding: utf-8 -*-
import os.path
import time
import urllib
import json
import requests
from tencentyun import conf
from .auth import Auth
class ImageProcess(object):
def __init__(self, appid, secret_id, secret_key, bucket):
self.IMAGE_FILE_NOT_EXISTS = -1
self._secret_id,self._secret_key = ... | tencentyun/python-sdk | python2/tencentyun/imageprocess.py | Python | mit | 3,116 |
#!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... | FinalHashLLC/Barnacoin | contrib/devtools/update-translations.py | Python | mit | 6,783 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... | pengzhangdev/slackbot | slackbot/plugins/component/ttsdriver/iflytek.py | Python | mit | 4,519 |
import unittest
from fam.tests.models.test01 import Dog, Cat, Person, JackRussell, Monarch
from fam.mapper import ClassMapper
class MapperTests(unittest.TestCase):
def setUp(self):
self.mapper = ClassMapper([Dog, Cat, Person, JackRussell, Monarch])
def tearDown(self):
pass
def test_... | paulharter/fam | src/fam/tests/test_couchdb/test_mapping.py | Python | mit | 535 |
# coding=utf-8
import random
lista = []
for x in range(10):
numero = random.randint(1, 100)
if x == 0:
maior, menor = numero, numero
elif numero > maior:
maior = numero
elif numero < menor:
menor = numero
lista.append(numero)
lista.sort()
print(lista)
print("Maior: %d" % maio... | renebentes/Python4Zumbis | Exercícios/Lista IV/questao01.py | Python | mit | 350 |
import pyb
import micropython
micropython.alloc_emergency_exception_buf(100)
led1 = pyb.LED(4) # 4 = Blue
led2 = pyb.LED(3) # 3 = Yellow
pin = pyb.Pin('SW', pyb.Pin.IN, pull=pyb.Pin.PULL_UP)
def callback(line):
led1.toggle()
if pin.value(): # 1 = not pressed
led2.off()
else:
led2.on()
... | dhylands/upy-examples | extint_toggle.py | Python | mit | 401 |
from webalchemy import config
FREEZE_OUTPUT = 'webglearth.html'
class Earth:
def __init__(self):
self.width = window.innerWidth
self.height = window.innerHeight
# Earth params
self.radius = 0.5
self.segments = 64
self.rotation = 6
self.scene = new(THREE.... | skariel/webalchemy | examples/three_d_earth/three_d_earth.py | Python | mit | 5,235 |
"""cdbgui.py
Developers: Christina Hammer, Noelle Todd
Last Updated: August 19, 2014
This file contains a class version of the interface, in an effort to
make a program with no global variables.
"""
from datetime import datetime, timedelta, date
from tkinter import *
from tkinter import ttk
from cdbifunc2 import *
i... | ChristinaHammer/Client_Database | cdbgui.py | Python | mit | 60,561 |
"""This module contains functions to :meth:`~reload` the database, load work and
citations from there, and operate BibTeX"""
import importlib
import re
import textwrap
import warnings
import subprocess
from copy import copy
from collections import OrderedDict
from bibtexparser.bwriter import BibTexWriter
from bibtex... | JoaoFelipe/snowballing | snowballing/operations.py | Python | mit | 33,262 |
#!/usr/bin/env python3
import sys
sys.path.insert(0, '/Users/neo/workspace/devops')
from netkiller.docker import *
# from environment.experiment import experiment
# from environment.development import development
# from environment.production import production
from compose.devops import devops
from compose.demo impor... | oscm/devops | docker/docker.py | Python | mit | 942 |
from setuptools import setup
setup(
name='nspawn-api',
packages=['nspawn'],
include_package_data=True,
install_requires=[
'gunicorn',
'nsenter',
'flask',
'pydbus',
'supervisor'
],
)
| dincamihai/nspawn-api | setup.py | Python | mit | 243 |
#coding:utf-8
LIST_NUM = [(1,4),(5,1),(2,3),(6,9),(7,1)]
'''
用max函数获取到元素的最大值,然后用冒泡进行排序
'''
for j in range(len(LIST_NUM) -1):
for i in range(len(LIST_NUM) -1):
if max(LIST_NUM[i]) > max(LIST_NUM[i + 1]):
A = LIST_NUM[i]
LIST_NUM[i] = LIST_NUM[i + 1]
LIST_NUM[i + 1] = ... | 51reboot/actual_09_homework | 04/guantao/list.py | Python | mit | 382 |
from psyrun.backend import DistributeBackend, LoadBalancingBackend
from psyrun.mapper import (
map_pspace,
map_pspace_parallel,
map_pspace_hdd_backed)
from psyrun.pspace import Param
from psyrun.scheduler import ImmediateRun, Sqsub
from psyrun.store import DefaultStore, PickleStore
from psyrun.version impor... | jgosmann/psyrun | psyrun/__init__.py | Python | mit | 345 |
""" discover and run doctests in modules and test files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import platform
import sys
import traceback
from contextlib import contextmanager
import pytest
from _pytest._code.code import Excepti... | hackebrot/pytest | src/_pytest/doctest.py | Python | mit | 18,770 |
# -*- coding: UTF-8 -*-
import ldap
class Connection:
def __init__(self, url='ldap://annuaire.math.univ-paris-diderot.fr:389', \
base='ou=users,dc=chevaleret,dc=univ-paris-diderot,dc=fr'):
self.base = base
self.url = url
self.con = ldap.initialize(self.url)
self.con.bin... | bfontaine/p7ldap | p7ldap/connection.py | Python | mit | 619 |
"""Approximating spectral functions with tensor networks.
"""
import numpy as np
import random
import quimb as qu
from .tensor_gen import MPO_rand, MPO_zeros_like
def construct_lanczos_tridiag_MPO(A, K, v0=None, initial_bond_dim=None,
beta_tol=1e-6, max_bond=None, seed=False,
... | jcmgray/quijy | quimb/tensor/tensor_approx_spectral.py | Python | mit | 1,751 |
import sublime
import sublime_plugin
from ..core import oa_syntax, decorate_pkg_name
from ..core import ReportGenerationThread
from ...lib.packages import PackageList
###----------------------------------------------------------------------------
class PackageReportThread(ReportGenerationThread):
"""
Genera... | OdatNurd/OverrideAudit | src/commands/package_report.py | Python | mit | 2,593 |
import numpy as np
import cv2
from sys import argv
class Test:
def __init__(self, name, image):
self.image = image
self.name = name
self.list = []
def add(self, function):
self.list.append(function)
def run(self):
cv2.imshow(self.name, self.image)
... | JacobMiki/Emotionnaise-python | test.py | Python | mit | 1,452 |
"""
Component that performs TensorFlow classification on images.
For a quick start, pick a pre-trained COCO model from:
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md
For more details about this platform, please refer to the documentation at
https://home-assist... | skalavala/smarthome | custom_components/image_processing/tensorflow.py | Python | mit | 13,028 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-02-17 01:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Client... | fernandolobato/balarco | clients/migrations/0001_initial.py | Python | mit | 614 |
import subprocess
import sys
import os
# This code is meant to manage running multiple instances of my KMCLib codes at the same time,
# in the name of time efficiency
numLambda = 512
numStepsEquilib = 1600000
numStepsAnal = 16000
numStepsSnapshot = 1000
numStepsReq = 16000
sysWidth = 32
sysLength = 32
analInterval = 1... | joshuahellier/PhDStuff | codes/kmc/2Dim/general2d/lambdaFluc2dCreator.py | Python | mit | 1,068 |
# -*- coding:utf8 -*-
from __future__ import division
import codecs
import re
def calWordProbability(infile, outfile):
'''
计算词概率,源语言词翻译成目标语言词的概率
一个源语言可能对应多个目标语言,这里计算平均值
infile: 输入文件 格式:source word \t target word
outfile: source word \t target word \t probability
'''
with codecs.open(infil... | kfeiWang/pythonUtils | wordProbability.py | Python | mit | 1,782 |
#Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Lets first write one line of text
my_name = "Frastlin"
#now lets write a number
my_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest ... | frastlin/PyAudioGame | examples/basic_tutorial/ex1.py | Python | mit | 712 |
import numpy as np
import pandas as pd
from scipy.optimize import least_squares
import re
import lmfit
class Calibrate:
def __init__(self, model):
"""initialize Calibration class
Parameters
----------
model : ttim.Model
model to calibrate
"... | mbakker7/ttim | ttim/fit.py | Python | mit | 10,043 |
from app import db, GenericRecord
class Case(GenericRecord):
__collection__ = 'cases'
db.register([Case])
| michaelnetbiz/mistt-solution | app/models/cases.py | Python | mit | 114 |
from __future__ import absolute_import
from __future__ import print_function
import argparse
import distutils.spawn
import subprocess
import sys
import virtualenv
def main(argv=None):
parser = argparse.ArgumentParser(description=(
'A wrapper around virtualenv that avoids sys.path sadness. '
'Any... | asottile/virtualenv-hax | virtualenv_hax.py | Python | mit | 2,216 |
def run():
import sys, os
try:
uri = sys.argv[1]
except IndexError:
uri = os.getcwd()
import gtk
from .app import App
from uxie.utils import idle
application = App()
idle(application.open, uri)
gtk.main()
| baverman/fmd | fmd/run.py | Python | mit | 262 |
#!/usr/bin/env python
# coding: utf-8
from django.shortcuts import render
from table.views import FeedDataView
from app.tables import (
ModelTable, AjaxTable, AjaxSourceTable,
CalendarColumnTable, SequenceColumnTable,
LinkColumnTable, CheckboxColumnTable,
ButtonsExtensionTable
)
def base(request):
... | shymonk/django-datatable | example/app/views.py | Python | mit | 2,085 |
from . import common
import hglib
class test_branches(common.basetest):
def test_empty(self):
self.assertEquals(self.client.branches(), [])
def test_basic(self):
self.append('a', 'a')
rev0 = self.client.commit('first', addremove=True)
self.client.branch('foo')
self.appe... | beckjake/python3-hglib | tests/test-branches.py | Python | mit | 674 |
from .utils import Serialize
###{standalone
class Symbol(Serialize):
__slots__ = ('name',)
is_term = NotImplemented
def __init__(self, name):
self.name = name
def __eq__(self, other):
assert isinstance(other, Symbol), other
return self.is_term == other.is_term and self.name ... | python-poetry/poetry-core | src/poetry/core/_vendor/lark/grammar.py | Python | mit | 2,918 |
from datetime import datetime
from flask import Blueprint, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_ser... | alphagov/notifications-api | app/performance_dashboard/rest.py | Python | mit | 3,531 |
#!/usr/bin/python3
import os
import requests
import sys
structure_template = 'src/{}/kotlin/solutions/day{}'
solver_template = """
package solutions.{package}
import solutions.Solver
class {clazz}: Solver {{
override fun solve(input: List<String>, partTwo: Boolean): String {{
TODO("not implemented")
... | Dr-Horv/Advent-of-Code-2017 | setup.py | Python | mit | 1,971 |
import logging
from sanic.signals import RESERVED_NAMESPACES
from sanic.touchup import TouchUp
def test_touchup_methods(app):
assert len(TouchUp._registry) == 9
async def test_ode_removes_dispatch_events(app, caplog):
with caplog.at_level(logging.DEBUG, logger="sanic.root"):
await app._startup()
... | channelcat/sanic | tests/test_touchup.py | Python | mit | 528 |
# by amounra 0216 : http://www.aumhaa.com
"""
Codec_Map.py
Created by amounra on 2010-10-05.
Copyright (c) 2010 __artisia__. All rights reserved.
This file allows the reassignment of the controls from their default arrangement. The order is from left to right;
Buttons are Note #'s and Faders/Rotaries are Controlle... | LividInstruments/LiveRemoteScripts | Codec_v2/Map.py | Python | mit | 3,024 |
#!/usr/bin/env python3
from __future__ import print_function
import datetime
import calendar
import logging
import time
import re
import os
import os.path
from abc import ABCMeta
from abc import abstractmethod
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui ... | josecolella/Dynatrace-Resources | portal/Portal.py | Python | mit | 17,063 |
import os
from cauldron.test import support
from cauldron.test.support import scaffolds
class TestAlias(scaffolds.ResultsTest):
"""..."""
def test_unknown_command(self):
"""Should fail if the command is not recognized."""
r = support.run_command('alias fake')
self.assertTrue(r.faile... | sernst/cauldron | cauldron/test/cli/commands/test_alias.py | Python | mit | 2,067 |
def test1():
SINK(SOURCE)
def test2():
s = SOURCE
SINK(s)
def source():
return SOURCE
def sink(arg):
SINK(arg)
def test3():
t = source()
SINK(t)
def test4():
t = SOURCE
sink(t)
def test5():
t = source()
sink(t)
def test6(cond):
if cond:
t = "Safe"
else... | github/codeql | python/ql/test/library-tests/taint/dataflow/test.py | Python | mit | 2,191 |
"""
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... | hmcc/price-search | scraper/scraper.py | Python | mit | 3,591 |
from django.contrib.sites import models as site_models
from django.db import models
def _get_current_site(request):
# Attempts to use monodjango.middleware.SiteProviderMiddleware
try:
return Site.objects.get_current(request)
except TypeError:
pass
return Site.objects.get_current()
c... | LimpidTech/django-themes | themes/managers.py | Python | mit | 1,188 |
# AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class LoaderTests(BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=... | pilliq/balance | tests/test_loaders.py | Python | mit | 1,764 |
# -*- coding: utf-8 -*-
GENDER = ((u'男',u'男'),(u'女',u'女'))
| youtaya/knight | fuzzybee/utils/constant.py | Python | mit | 67 |
#!/usr/bin/python
"""
Package constants
"""
## MIT License
##
## Copyright (c) 2017, krishna bhogaonker
## 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 wit... | krishnab-datakind/mining-data-acquisition | data_gather/PackageConstants.py | Python | mit | 4,082 |
from Models.Submission import Submission
from Core.Database import Database
from Core.Scorer import Score
from sqlalchemy import func, desc
class Ranking():
@staticmethod
def get_all():
session = Database.session()
scores = session.query(Score).order_by(desc(Score.score)).all()
retur... | brnomendes/grader-edx | Core/Ranking.py | Python | mit | 564 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from gaegraph.model import Node, Arc
class Escravo(Node):
name = ndb.StringProperty(required=True)
age = ndb.IntegerProperty()
birth = ndb.DateProperty(auto_now=True)
price = ndb.Float... | renzon/fatec-script-2 | backend/apps/escravo_app/modelos.py | Python | mit | 446 |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 09 14:51:02 2015
@author: Methinee
"""
import pandas as pd
import numpy as np
from collections import defaultdict
from astropy.table import Table, Column
df = pd.read_csv('../data/CS_table_No2_No4_new.csv',delimiter=";", skip_blank_lines = True,
error_... | wasit7/book_pae | pae/forcast/src/csv/CS_table_No2_No4.py | Python | mit | 1,865 |
import os
import json
from subprocess import check_output, CalledProcessError
#Constants
_TREE_PATH="data/graph/"
def renderGraph(query):
"""
Returns the path to a svg file that
contains the graph render of the query.
Creates the svg file itself if it
does not already exist.
"... | texit/texit | graph.py | Python | mit | 2,827 |
quicksort(A, lo, hi):
if lo < hi:
p := partition(A, lo, hi)
quicksort(A, lo, p - 1)
quicksort(A, p + 1, hi)
| Chasego/codi | util/basic/quicksort.py | Python | mit | 120 |
# Basic command-line interface to manage docker containers which will use an
# image stored in a dockerhub registry - 'pokeybill/bftest'
import click
from click.testing import CliRunner
import docker
import sys
import time
import requests
this = sys.modules[__name__]
BASE_URL = 'unix://var/run/docker.sock'
REGISTRY =... | wnormandin/bftest_cli | cli/dockcli.py | Python | mit | 4,675 |
# Author:
# Ross Sbriscia, April 2016
import random
import sys
import traceback
import os
import math
import argparse
import time
import random_connected_graph
# Parses Arguments
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='Simulat... | rsbrisci/Math455RandomWalkProject | Python Solution v1.0/SimulateP2PNetwork.py | Python | mit | 9,332 |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | plaid/plaid-python | plaid/model/numbers_international.py | Python | mit | 7,184 |
import pendulum
locale = "nb"
def test_diff_for_humans():
with pendulum.test(pendulum.datetime(2016, 8, 29)):
diff_for_humans()
def diff_for_humans():
d = pendulum.now().subtract(seconds=1)
assert d.diff_for_humans(locale=locale) == "for 1 sekund siden"
d = pendulum.now().subtract(seconds... | sdispater/pendulum | tests/localization/test_nb.py | Python | mit | 3,021 |
import django
django.setup()
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from customers.models import Customer, Email
class CustomersTest(APITestCase, TestCase):
def test_api_should_accept_multiple_emails... | guilatrova/customercontrol-api | customers/tests.py | Python | mit | 1,951 |
import os
import sys
import fnmatch
directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
print(files)
for filename in files:
if fnmatch.fnmatch(filename,'mpsdk_*') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #ge... | mercadopago/px-android | scripts/rename_resources.py | Python | mit | 559 |
import asyncio
import inspect
import itertools
import string
import typing
from .. import helpers, utils, hints
from ..requestiter import RequestIter
from ..tl import types, functions, custom
if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient
_MAX_PARTICIPANTS_CHUNK_SIZE = 200
_MAX_ADMIN_LOG_CHU... | expectocode/Telethon | telethon/client/chats.py | Python | mit | 42,127 |
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^profiles/', include('easy_profiles.urls')),
(r'^admin/', include(admin.site.urls)),
)
| pydanny/django-easy-profiles | test_project/urls.py | Python | mit | 223 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... | SaintlyVi/DLR_DB | evaluation/calibration.py | Python | mit | 5,511 |
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^img1x1$', 'ses_analytics.views.img1x1', name='img1x1'), # used to trace email opening
# TODO: unsubscription and SNS feedback notifications
)
| startup-guide/django-ses-analytics | ses_analytics/urls.py | Python | mit | 228 |
import pickle
import pytest
from doit.cmdparse import DefaultUpdate, CmdParseError, CmdOption, CmdParse
class TestDefaultUpdate(object):
def test(self):
du = DefaultUpdate()
du.set_default('a', 0)
du.set_default('b', 0)
assert 0 == du['a']
assert 0 == du['b']
... | lelit/doit | tests/test_cmdparse.py | Python | mit | 5,264 |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Created on Jan 24, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Jan 24, 2... | materialsproject/pymatgen | pymatgen/io/tests/test_cssr.py | Python | mit | 1,796 |
#encoding:utf-8
subreddit = 'comedynecrophilia'
t_channel = '@comedynecrophilia'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| Fillll/reddit2telegram | reddit2telegram/channels/~inactive/comedynecrophilia/app.py | Python | mit | 155 |
#!/usr/bin/env python
# −*− coding: UTF−8 −*−
# Topological Sorting
from collections import defaultdict
def topsort(graph):
if not graph:
return []
# 1. Count every node's dependencies
count = defaultdict(int)
for node in graph:
for dependency in graph[node]:
count[depende... | pgularski/snippets | python/algorithms/topsort.py | Python | mit | 1,733 |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from acq4.util.DataManager import *
#import acq4.Manager as Manager
import acq4.pyqtgraph as pg
#from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget
#from acq4.pyqtgraph.ImageView import ImageView
from acq4.util.DictView import *
import acq4.util.metaarray... | mgraupe/acq4 | acq4/modules/DataManager/FileDataView.py | Python | mit | 3,567 |
# coding=utf-8
"""
CritSend test proyect urls.
Copyright (C) 2013 Nicolas Valcárcel Scerpella
Authors:
Nicolas Valcárcel Scerpella <nvalcarcel@gmail.com>
"""
# Standard library imports
# Framework imports
from django.conf.urls import patterns, include, url
from django.contrib import admin
# 3rd party imports
#... | nxvl/critsend_test | test_proyect/urls.py | Python | mit | 482 |
"""The IPython kernel implementation"""
import getpass
import sys
import traceback
from IPython.core import release
from IPython.html.widgets import Widget
from IPython.utils.py3compat import builtin_mod, PY3
from IPython.utils.tokenutil import token_at_cursor, line_at_cursor
from IPython.utils.traitlets import Insta... | mattvonrocketstein/smash | smashlib/ipy3x/kernel/zmq/ipkernel.py | Python | mit | 13,151 |
"""Test cases for JSON lws_logger module, assumes Pytest."""
from jsonutils.lws import lws_logger
class TestDictToTreeHelpers:
"""Test the helper functions for dict_to_tree."""
def test_flatten_list(self):
"""Test flattening of nested lists."""
f = lws_logger.flatten_list
nested = [1... | tkuriyama/jsonutils | jsonutils/lws/test/test_lws_logger.py | Python | mit | 3,990 |
import os
import unittest
import random
import xmlrunner
host = os.environ['FALKONRY_HOST_URL'] # host url
token = os.environ['FALKONRY_TOKEN'] # auth token
class TestDatastream(unittest.TestCase):
def setUp(self):
self.created_datastreams = []
self.fclient = FClient(host=host, token=token... | Falkonry/falkonry-python-client | test/TestDatastream.py | Python | mit | 35,686 |
# Zadání:
#########
#
# Úkolem je implementovat kompresi textu Huffmanovým kódováním.
#
# Vstup:
# * dva argumenty na příkazové řádce: jméno vstupního souboru a jméno
# výstupního souboru
#
# Vstupní soubor je textový soubor, který obsahuje různě dlouhé řádky textu,
# text obsahuje pouze písmena abecedy (malá a ... | malja/cvut-python | cviceni11/huffman.py | Python | mit | 7,419 |
# 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/InfERPSupport/ErpInventory.py | Python | mit | 2,914 |
#!/usr/bin/python
from TimeWorked import *
import os
files = [TIME_WORKED]
print get_total_time_by_day_files(files)
raw_input()
| JasonGross/time-worked | pastWeekTime.py | Python | mit | 128 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, os, re
from frappe.utils import touch_file, encode, cstr
def make_boilerplate(dest, app_name):
if not os.path.exists(dest):
print "Destination directory does n... | rohitwaghchaure/frappe | frappe/utils/boilerplate.py | Python | mit | 9,035 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script adds a missing references section to pages.
It goes over multiple pages, searches for pages where <references />
is missing although a <ref> tag is present, and in that case adds a new
references section.
These command line parameters can be used to specify w... | icyflame/batman | scripts/noreferences.py | Python | mit | 25,133 |
import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... | elc1798/chessley-tan | app.py | Python | mit | 5,117 |
"""
* Created by Synerty Pty Ltd
*
* This software is open source, the MIT license applies.
*
* Website : http://www.synerty.com
* Support : support@synerty.com
"""
RPC_PRIORITY = 10
DEFAULT_PRIORITY = 100
| Synerty/vortexpy | vortex/PayloadPriority.py | Python | mit | 213 |
from collections.abc import Sequence
from numbers import Number
from . import Validator, Length, Range, Instance
from .compound import All
class Latitude(All):
"""Validate the given value as a number between -90 and +90 in decimal degrees, representing latitude."""
validators = [
Instance(Number),
Range(-9... | marrow/schema | marrow/schema/validate/geo.py | Python | mit | 1,013 |
import _plotly_utils.basevalidators
class LegendrankValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="legendrank", parent_name="scatter", **kwargs):
super(LegendrankValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/_legendrank.py | Python | mit | 406 |
from havocbot.common import catch_exceptions
from havocbot.plugin import HavocBotPlugin
import imp
import logging
import os
logger = logging.getLogger(__name__)
class StatefulPlugin:
def __init__(self, havocbot, name, path):
self.path = path
self.name = name
self.handler = None
se... | markperdue/havocbot | src/havocbot/pluginmanager.py | Python | mit | 8,630 |
from django.core.management.base import BaseCommand
from stream_analysis.utils import cleanup
class Command(BaseCommand):
"""
Removes streaming data we no longer need.
"""
help = "Removes streaming data we no longer need."
def handle(self, *args, **options):
cleanup()
| michaelbrooks/django-stream-analysis | stream_analysis/management/commands/cleanup_streams.py | Python | mit | 300 |
# -*- coding: utf8 -*-
"""
@author: Matthias Feys (matthiasfeys@gmail.com)
@date: %(date)
"""
import theano
class Layer(object):
def __init__(self,name, params=None):
self.name=name
self.input = input
self.params = []
if params!=None:
self.setParams(params=params... | codeAshu/nn_ner | nn/interfaces.py | Python | mit | 939 |
# MIT License
#
# Copyright (c) 2017, Stefan Webb. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | stefanwebb/tensorflow-models | tensorflow_models/initializations.py | Python | mit | 1,768 |
"""Basic contact management functions.
Contacts are linked to monitors and are used to determine where to send
alerts for monitors.
Contacts are basic name/email/phone sets.
Contacts are only stored in the database and not in memory, they are loaded
from the database each time an alert is sent.
"""
from typing impo... | beebyte/irisett | irisett/contact.py | Python | mit | 17,565 |
#!/usr/bin/env python
# bootstrap.py
#
# Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
# Licensed under MIT
# Version 1.0.0-alpha6
from app import db
# create all databases and tables included in the application
db.create_all()
| ecsnavarretemit/sarai-interactive-maps-backend | bootstrap.py | Python | mit | 251 |
#!/usr/bin/env python
import os
import numpy as np
from cereal import car
from common.numpy_fast import clip, interp
from common.realtime import sec_since_boot
from selfdrive.swaglog import cloudlog
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import create_event, EventTypes ... | TheMutley/openpilot | selfdrive/car/honda/interface.py | Python | mit | 23,054 |
#!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file con... | emkailu/PAT3DEM | bin/p3starscreen.py | Python | mit | 3,906 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
total = 0
def dfs(root, p, gp):
if root is None:
r... | jiadaizhao/LeetCode | 1301-1400/1315-Sum of Nodes with Even-Valued Grandparent/1315-Sum of Nodes with Even-Valued Grandparent.py | Python | mit | 565 |
__author__ = 'xubinggui'
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print(self.score)
bart = Student('Bart Simpson', 59)
bart.print_score() | xu6148152/Binea_Python_Project | oop/student/student.py | Python | mit | 246 |
import _plotly_utils.basevalidators
class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="heatmap", **kwargs):
super(UirevisionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/heatmap/_uirevision.py | Python | mit | 447 |
import time
class RecordAccumulator(object):
def __init__(self, buffer_class, config):
self.config = config
self.buffer_time_limit = config['buffer_time_limit']
self._buffer_class = buffer_class
self._reset_buffer()
def _reset_buffer(self):
self._buffer = self._buffer... | ludia/kinesis_producer | kinesis_producer/accumulator.py | Python | mit | 1,297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.