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 |
|---|---|---|---|---|---|
from unittest import skipIf
from django import forms
from django.db import connection, models
from django.test import TestCase
from .models import Post
class TextFieldTests(TestCase):
def test_max_length_passed_to_formfield(self):
"""
TextField passes its max_length attribute to form fields cre... | EmadMokhtar/Django | tests/model_fields/test_textfield.py | Python | mit | 1,367 |
try:
a = 1
exce<caret> | caot/intellij-community | python/testData/keywordCompletion/exceptNotIndented.py | Python | apache-2.0 | 26 |
def foo():
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
<selection>length = len(f.readlines()) #<---extract something from here
print("hi from else")</selection>
#anything else you... | smmribeiro/intellij-community | python/testData/refactoring/extractmethod/ElseBody.before.py | Python | apache-2.0 | 325 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2015 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from io import BytesIO
import logging
import os
import re
import struct
import sys
from .compat import sysconfig, detect_encoding, ZipFi... | zwChan/VATEC | ~/eb-virt/Lib/site-packages/pip/_vendor/distlib/scripts.py | Python | apache-2.0 | 15,223 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | jaggu303619/asylum | openerp/addons/crm/report/__init__.py | Python | agpl-3.0 | 1,107 |
SUCCESS = 0
ERROR = 1
UNKNOWN_ERROR = 2
VIRTUALENV_NOT_FOUND = 3
PREVIOUS_BUILD_DIR_ERROR = 4
NO_MATCHES_FOUND = 23
| cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/pip/status_codes.py | Python | mit | 116 |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | google/yapf | yapftests/__init__.py | Python | apache-2.0 | 596 |
# This code was mostly based on ipaddr-py
# Copyright 2007 Google Inc. http://code.google.com/p/ipaddr-py/
# Licensed under the Apache License, Version 2.0 (the "License").
from django.core.exceptions import ValidationError
from django.utils.six.moves import range
from django.utils.translation import ugettext_lazy as _... | BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/utils/ipv6.py | Python | mit | 7,971 |
# -*- coding: utf-8 -*-
from twisted.web.resource import Resource
from bouser.helpers.plugin_helpers import Dependency
__author__ = 'viruzzz-kun'
class SimarglResource(Resource):
web = Dependency('bouser.web')
es = Dependency('bouser.ezekiel.eventsource', optional=True)
rpc = Dependency('bouser.ezekiel.... | hitsl/bouser_simargl | bouser_simargl/web.py | Python | isc | 577 |
# flgLib is needed for StateMachine
from flgLib import *
# common superclass for flg and fpg drivers to implement the expression
# handling functions
class commonLib(object):
# exprXYZ() functions return ExprXYZ() objects invoked with the same
# arguments.
def exprOper(self, *args):
__ret = tuple(args)... | darkfoxprime/foxCAT | src/commonLib.py | Python | isc | 2,350 |
#!/usr/bin/env python
# CREATED:2013-03-08 15:25:18 by Brian McFee <brm2132@columbia.edu>
# unit tests for librosa core (__init__.py)
#
from __future__ import print_function
# Disable cache
import os
try:
os.environ.pop("LIBROSA_CACHE_DIR")
except:
pass
import librosa
import glob
import numpy as np
import ... | bmcfee/librosa | tests/test_core.py | Python | isc | 61,375 |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
from django.conf.urls.defaults import *
urlpatterns = patterns('treeio.core.api.auth.views',
url(r'^get_request_token$', 'get_request_token', name="api_get_request_token"),
url(r'^authorize_request... | rogeriofalcone/treeio | core/api/auth/urls.py | Python | mit | 477 |
#! /usr/bin/env python
import gspread
import argparse
from format import *
import sys
from stats import getMean
import pdb
import json
from oauth2client.client import SignedJwtAssertionCredentials
from gsheets import openSS, Table, putRawTable
p = argparse.ArgumentParser(description=\
"Given a set of runs for severa... | d1m0/browser_bench | build_worksheet.py | Python | mit | 4,846 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Sends email via outgoing server specified in "Control Panel"
Allows easy adding of Attachments of "File" objects
"""
import webnotes
import conf
from webnotes import msgprint
from webnot... | rohitw1991/latestadbwnf | webnotes/utils/email_lib/smtp.py | Python | mit | 10,111 |
def catch_all(data):
print(data)
| PythonSanSebastian/python-rtmbot | plugins/ep_volunteer/catch_all.py | Python | mit | 38 |
class User():
def __init__(self, first_name, last_name, birthday, sex):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.sex = sex
self.login_attempts = 0
def describe_user(self):
print('first name: ' + self.first_name +
... | nakednamor/naked-python | Python Crash Course/chapter 9/e5.py | Python | mit | 1,031 |
# $Id: debug.py,v 1.3 2010/10/23 12:43:55 ceballos Exp $
import FWCore.ParameterSet.Config as cms
process = cms.Process('FILLER')
# import of standard configurations
process.load('Configuration/StandardSequences/Services_cff')
process.load('FWCore/MessageService/MessageLogger_cfi')
process.load('Configuration/Standa... | cpausmit/Kraken | filefi/014/debug.py | Python | mit | 1,936 |
from .meta import BaseModelDependent
import warnings
import numpy as np
import scipy.sparse as sp
from scipy.special import i0 as bessi0
class BaseSource(BaseModelDependent):
pass
class FakeSource(BaseSource):
def __call__(self, loc):
return loc
class SimpleSource(BaseSourc... | uwoseis/anemoi | anemoi/source.py | Python | mit | 8,029 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import serial
import time
import sys
#-------------------------------------------------------------------
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 38400
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity... | meigrafd/Sample-Code | serial_input.py | Python | mit | 1,579 |
# importing wxPython library, see the reference here :
# http://www.wxpython.org/docs/api/wx-module.html
# and an excelent step by step tutorial there :
# http://zetcode.com/wxpython
import wx
from Controller import *
# main function
def main():
# each wx application must have a wx.App object
app = wx.App()
... | jonathanlurie/BLANK_PY2WX | src/main.py | Python | mit | 492 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('firecares_core', '0008_auto_20161122_1420'),
]
operations = [
migrations.CreateModel(
name='RegistrationWhitelis... | FireCARES/firecares | firecares/firecares_core/migrations/0009_registrationwhitelist.py | Python | mit | 576 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/requests/messages/release_pokemon_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _... | bellowsj/aiopogo | aiopogo/pogoprotos/networking/requests/messages/release_pokemon_message_pb2.py | Python | mit | 2,798 |
#!/usr/bin/env python3
# Questo file visualizza la chiave "lists" redis
#
# Prima verifica che ci sia la chiave nel form
# Serve per la parte di gestione html in python
import cgi
import cgitb
# Abilita gli errori al server web/http
cgitb.enable()
# Le mie librerie mjl (Json, Files), mhl (Html), flt (T w/ Redis)
im... | raspibo/Livello1 | var/www/cgi-bin/writecsvlistsetsredis.py | Python | mit | 1,795 |
from __future__ import unicode_literals
import swapper
from django.db import models
from accelerator_abstract.models.accelerator_model import AcceleratorModel
class BaseApplicationAnswer(AcceleratorModel):
application = models.ForeignKey(to=swapper.get_model_name(
AcceleratorModel.Meta.app_label, "Appli... | masschallenge/django-accelerator | accelerator_abstract/models/base_application_answer.py | Python | mit | 985 |
from __future__ import (absolute_import, division, print_function)
from bcube_owslib.util import nspath_eval
from bcube_owslib.namespaces import Namespaces
from bcube_owslib.util import testXMLAttribute, testXMLValue, InfiniteDateTime, NegativeInfiniteDateTime
from dateutil import parser
from datetime import timedelt... | b-cube/pipeline-demo | demo/bcube_owslib/swe/common.py | Python | mit | 17,850 |
from typing import Any
from collections import OrderedDict
def match_link_id(link_id: str) -> Any:
return {'$match': {'link_id': link_id}}
# daily visits aggregations phases
group_tracking_ids = {'$group': {
'_id': '$tracking_id',
'visits': {
'$addToSet': '$$ROOT',
},
}}
find_first = {'$pro... | oss/shrunk | backend/shrunk/client/aggregations.py | Python | mit | 2,981 |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
from builtins import (bytes, dict, int, list, object, range, str, # noqa
ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
from future import standard_library
from past.builtins im... | totalgood/nlpia | src/nlpia/data_utils.py | Python | mit | 11,738 |
#Milton Orlando Sarria
#filtrado elemental de ruido sinusoidal
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
#disenar el filtro usando una ventana hamming
b = signal.firwin(9, 0.8, window='hamming', pass_zero=True)
#definir la frecuencia de muestreo y generar un vector de tiempo hasta 5... | miltonsarria/dsp-python | filters/FIR/filter_sine1.py | Python | mit | 1,128 |
# Copyright (c) 2013 Azavea, Inc.
# See LICENSE in the project root for copying permission
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from django.core.management.base import BaseCommand
from django.db.models import Count
from vectorformats.Formats import Django, Ge... | smartchicago/chicago-early-learning | python/ecep/portal/management/commands/export_topojson.py | Python | mit | 2,327 |
# -*- coding: utf-8; -*-
#
# @file urls.py
# @brief collgate
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2018-09-20
# @copyright Copyright (c) 2018 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details coll-gate printer module url entry point.
from django.conf.urls import include, url
urlpatterns = [
]
| coll-gate/collgate | server/printer/urls.py | Python | mit | 317 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.newsitem_list, name='newsitem_list'),
]
| HMSBeagle1831/rapidscience | rlp/newsfeed/urls.py | Python | mit | 133 |
from django.contrib import admin
# from models import Agent, ReCa, Accomodation, Beach, Activity, Contact
#
# @admin.register(ReCa, Activity)
# class VenueAdmin(admin.ModelAdmin):
# list_display = ('name', 'internal_rating', 'ready', 'description',)
# list_filter = ('ready', 'internal_rating',)
# search_fields =... | popara/jonny-api | matching/admin.py | Python | mit | 786 |
import random
from BinTree import BinTree
import flask
import flask_login
import forms
import db
app = flask.Flask(__name__)
app.config.from_object('config')
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(flask_login.UserMixin):
def __init__(s... | sandspider2234/Logical | routes.py | Python | mit | 8,750 |
"""
Math Utils.
Bruce Wernick
10 June 2021
"""
import math
import sys
__all__ = ['showvec', 'makemat', 'makevec', 'MAX', 'MIN', 'SIGN',
'SQR', 'pythag', 'is_number', 'odd', 'sum_inv', 'is_close', 'max2',
'liststat', 'ave', 'sum_inv']
# --------------------------------------------------------------... | bru32/magz | magz/umath.py | Python | mit | 3,528 |
# -*- coding: utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
DeclarativeBase = declarative_base()
maker = sessionmaker(autoflush=True, autocommit=False,
extension=Zo... | tongpa/tgext.pylogservice | tgext/pylogservice/models/__init__.py | Python | mit | 623 |
from django.utils import simplejson
from django import template
from django.conf import settings
from ..models import DataLayer, TileLayer
from ..views import _urls_for_js
register = template.Library()
@register.inclusion_tag('leaflet_storage/css2.html')
def leaflet_storage_css():
return {
"STATIC_URL":... | daumann/chronas-application | umap/templates/leaflet_storage/leaflet_storage_tags.py | Python | mit | 2,204 |
__version__ = '0.0.1'
import os
from .base import (get_config_paths, check_output_dir, ComputingEnvironemtError,
get_training_features, partition)
from .cluster import localized
from . import simfunctions
from .simfunctions import level3_sim_file_batches, level3_sim_GCD_file
from . import datafunct... | jrbourbeau/cr-composition | comptools/__init__.py | Python | mit | 1,516 |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: stateless_random_ops.cc
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _cont... | ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/contrib/stateless/gen_stateless_random_ops.py | Python | mit | 13,285 |
#!/usr/bin/env python
# coding: utf-8
import sys
import urllib
import requests
import argparse
URL = "http://localhost"
PORT = 5000
def say(text, lang, engine="google"):
text = urllib.quote(text.encode('utf-8'))
requests.get(u"%s:%s/speak?text=%s&language=%s&engine=%s" % (URL, PORT, text, lang, engine))
parse... | nwlunatic/speaker | say.py | Python | mit | 478 |
#!/usr/bin/env python
from os.path import join
from config import Config
from group import HostGroup, PortGroup
from parser import Parser
from renderers.junos import JunosRenderer
from renderers.ios import IOSRenderer
from deployers.junos import JunosDeployer
from deployers.ios import IOSDeployer
from deployers.iosscp... | favoretti/accessninja | accessninja/device.py | Python | mit | 5,511 |
# -*- coding: utf-8 -*-
"""
How to get input from the user. Note that this is Python 2.7, the Python 3+
version is in the "input3.py" file.
"""
if __name__ == '__main__':
# Get an integer from the user (will error on non-number)
x = int(input("Write an integer: "))
print(x)
# Get a float (will error ... | nightmarebadger/tutorials-python-basic | verybasic/input/input.py | Python | mit | 460 |
import scrapy
import psycopg2
from bs4 import BeautifulSoup
try:
conn = psycopg2.connect(database='my_database', user='user_name', password='password', host='localhost')
print("Connected Foo!!")
except:
print("I am unable to connect to the database.")
cur = conn.cursor()
cur.execute("""SELECT p... | sderenth/Scrapy-Draft-Data | RealGM/PlayerGameLogs.py | Python | mit | 3,667 |
import app_info
import loggers
import plist_editor
__version__ = '1.9.1'
__all__ = ['app_info', 'fs_analysis', 'loggers', 'plist_editor', 'slack']
# This provides the ability to get the version from the command line.
# Do something like:
# $ python -m management_tools.__init__
if __name__ == "__main__":
pri... | univ-of-utah-marriott-library-apple/management_tools | management_tools/__init__.py | Python | mit | 376 |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
class TestNumpyTrain(unittest.TestCase):
""" Numpy の練習 """
@classmethod
def setUpClass(cls):
pass
def test_basic_calc_array(self):
""" 配列の四則演算 """
x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 4.0, 6.0])
... | Arahabica/NNTrain | train/basic/testNumpyTrain.py | Python | mit | 1,817 |
from models import *
def create_ap_data(
router_mac=Mac('11:12:13:14:15:16'),
device_mac=Mac('A1:A2:A3:A4:A5:A6'),
created_at=Time(1),
rssis={ '1': RSSI(-20) },
signal=Signal(channel=2, band='2.4')
):
return APData(
router_mac=router_mac,
device_mac=devi... | maveron58/indiana | test/factory.py | Python | mit | 1,012 |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 u... | jhgg/discord.py | discord/colour.py | Python | mit | 6,401 |
"""
WSGI config for oxygen project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI... | zhaogp/oxygen | oxygen/wsgi.py | Python | mit | 390 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/python/__init__.py | Python | mit | 10,498 |
#------------------------------------ SETUP ----------------------------------------------
import sys
WORKING_DIRECTORY = ''
SPLITTING_CHARACTER = ''
if sys.platform.startswith('win') :
SPLITTING_CHARACTER = '\{}'.format('')
elif sys.platform.startswith('darwin') :
SPLITTING_CHARACTER = '/'
def setup() :
def l... | projectscara2014/scara | working_directory/setup/block_position_setup_main.py | Python | mit | 5,886 |
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm
from django.utils.decorators import method_decorator
from django.utils.http import is_safe_url
from django.views.decorators.debug import sensitive_post_parameters
from django.views import generic
fr... | neuroticnerd/django-demo-app | django_demo/accounts/views.py | Python | mit | 1,886 |
#!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):17792")
for line in lines:
m = patt... | prolifik/cakecoin | contrib/seeds/makeseeds.py | Python | mit | 709 |
class Graph:
def __init__(self, V, adj={}):
self.V = V
self.adj = adj
def add_edge(self, i, j):
if i in self.adj.keys():
self.adj[i].add(j)
else:
self.adj[i] = set([j])
def is_reachable(self, i, j):
if i == j:
return True
visited = [False]*self.V
stack = [i]
while len(stack) > 0:
s ... | asaini/algo-py | algos/graph_reachable.py | Python | mit | 803 |
#By Sam Kreter
#For use by Microsoft and other parties to demo
#Azure Container Service, Azure Container Instances
#and the experimental ACI-connector
import os
from azure.storage.blob import BlockBlobService
import sqlite3
COPY_PICS_NUM = 1
class DbAzureBlob:
def __init__(self):
AZURE_BLOB_ACCOUNT ... | rbitia/aci-demos | vk-burst-demo/aci-worker/app/dbAzureBlob.py | Python | mit | 2,832 |
import numpy as np
from scipy.integrate import odeint
from scipy.integrate import ode
import matplotlib.pylab as plt
import csv
import time
endpoint = 1000000000; # integration range
dx = 10.0; # step size
lam0 = 0.845258; # in unit of omegam, omegam = 3.66619*10^-17
dellam = np.array([0.00003588645221954444, 0.06486... | NeuPhysics/codebase | ipynb/matter/py-server/save-data-on-site.py | Python | mit | 2,819 |
# encoding: utf8
"""
copy from tornado.escape.xhtml_unescape
"""
import re
import htmlentitydefs
if type('') is not type(b''):
def u(s):
return s
bytes_type = bytes
unicode_type = str
basestring_type = str
else:
def u(s):
return s.decode('unicode_escape')
bytes_type = str
un... | CooperLuan/sasoup | sasoup/escape.py | Python | mit | 1,570 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from io import BytesIO
from django.core.files.storage import Storage
class TestStorage(Storage):
def __init__(self, *args, **kwargs):
self.reset()
def _open(self, name, mode='rb'):
if not self.exists(name):
if 'w' i... | jsatt/django-db-email-backend | test_app/storage.py | Python | mit | 1,353 |
#!/usr/local/bin/ipython -i
"""
A scatter graph of grid count vs grid area.
"""
import numpy as np
import matplotlib.pyplot as plt
# extract data from csv
file_name = "../data/tdwgsp_filtered.csv"
# columns (filtered):
# 1 - star_infs
# 2 - tdwgtotals
# 3 - tdwgareas
star_infs = np.genfromtxt(file_name, delimiter=','... | Nodoka/Bioquality | graphing/tdwg_scatter.py | Python | mit | 1,350 |
number = [i for i in range(1, 3001330+1)]
# number = [i for i in range(1, 10)]
number2 = number[:]
last = len(number) % 2 != 0
while len(number) > 1:
next_last = len(number) % 2 != last
number = [j for i, j in enumerate(number) if i % 2 != last]
last = next_last
print('#1', number[0])
number = number2
... | matejm/advent-of-code-2016 | day19.py | Python | mit | 829 |
#!/usr/bin/env python
from os.path import dirname, join
import plyer
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
curdir = dirname(__file__)
packages = [
'plyer',
'plyer.platforms',
'plyer.platforms.linux',
'plyer.platforms.android',
'plyer.platfo... | inclement/plyer | setup.py | Python | mit | 1,374 |
#!/usr/bin/python
from base64 import b64encode
from optparse import make_option
import json
import urllib
import urllib2
import argparse
import time
import sys
import os
import subprocess
#==#
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib', 'cybergis')))
import gs._geoserver_animate... | state-hiu/cybergis-scripts | bin/cybergis-script-ittc-register-snapshot-layer.py | Python | mit | 1,526 |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class ItemQuantityUpdateRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.num_iid = None
self.outer_id = None
self.quantity = None
self.sku_id = None
... | CooperLuan/devops.notes | taobao/top/api/rest/ItemQuantityUpdateRequest.py | Python | mit | 406 |
import unittest
class Tester(unittest.TestCase):
def test_list_comprehension(self):
a = [(x, y)
for x in [1, 2, 3]
for y in [3, 1, 4]
if x != y]
b = []
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
... | mr-uuid/snippets | python/comprehension.py | Python | mit | 1,057 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/operations/usages_operations.py | Python | mit | 4,282 |
from setuptools import setup
setup(name='glreg',
version='0.9.0a3',
description='OpenGL XML API registry parser',
long_description=open('README.rst').read(),
url='https://github.com/pyokagan/pyglreg',
author='Paul Tan',
author_email='pyokagan@gmail.com',
license='MIT',
... | pyokagan/pyglreg | setup.py | Python | mit | 1,068 |
#!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool acceptance of raw transactions."""
from decimal import Decimal
import math
from test_fra... | mruddy/bitcoin | test/functional/mempool_accept.py | Python | mit | 16,115 |
import sys
import sdl2.ext
def run():
resources = sdl2.ext.Resources(__file__, "platformer")
sdl2.ext.init()
window = sdl2.ext.Window("SRG", size=(200, 200))
window.show()
factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
sprite = factory.from_image(resources.get_path("sky0.png"))
s2 = sp... | anokata/pythonPetProjects | var_scripts/sdl_test.py | Python | mit | 1,486 |
"""
Contour plots of unstructured triangular grids.
"""
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import math
# Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.
# First create the x and y coordinates of the points.
n... | bundgus/python-playground | matplotlib-playground/examples/pylab_examples/tricontour_demo.py | Python | mit | 4,613 |
from django.contrib import admin
from .models import PizzaPlace
admin.site.register(PizzaPlace)
| nicole-a-tesla/meetup.pizza | pizzaplace/admin.py | Python | mit | 99 |
#!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
"""
`Unit tests for cargo.clients.AioPostgresPool`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
2016 Jared Lunde © The MIT License (MIT)
http://github.com/jaredlunde
"""
import unittest
import psycopg2
from cargo.cursors import... | jaredlunde/cargo-orm | unit_tests/aio/AioPostgresPool.py | Python | mit | 5,680 |
import datetime
import socket
import struct
import time
import Queue
import mutex
import threading
import select
taskQueue = Queue.Queue()
stopFlag = False
def system_to_ntp_time(timestamp):
"""Convert a system time to a NTP time.
Parameters:
timestamp -- timestamp in system time
Returns:
corres... | limifly/ntpserver | ntpserver.py | Python | mit | 9,482 |
##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
import os
import tempfile
import pywps.configuratio... | geopython/pywps | pywps/processing/job.py | Python | mit | 4,609 |
### test if the match url is integer
def integers(*segment_names):
def predicate(info, request):
match = info['match']
for segment_name in segment_names:
try:
print (segment_names)
match[segment_name] = int(match[segment_name])
if int(ma... | NaturalSolutions/NS.Bootstrap | Back/ecoreleve_server/Views/__init__.py | Python | mit | 2,874 |
'''
Date : 2017-4-21
Author : Chilam
Application : Person Detector based on OpenCV HOG and SVM detector
'''
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import im... | knaffe/Face_Recog_sys | person_detectior/detect_motion.py | Python | mit | 2,007 |
from roglick.engine.ecs import ComponentBase
class AttributesComponent(ComponentBase):
_properties = (('st', 10), ('dx', 10), ('iq', 10), ('pe', 10))
| Kromey/roglick | roglick/components/attributes.py | Python | mit | 157 |
import converters
import math
import random
import sys
def random_real(a, b):
"""
Random real between a and b inclusively.
"""
return a + random.random() * (b - a)
def branch_length(depth):
"""
Somewhat random length of the branch. Play around
with this to achieve a desired tree structure... | 2deviant/Mathematica-Trees | trees.py | Python | mit | 2,017 |
from django.utils import timezone
from bulbs.content.models import Content, FeatureType
from bulbs.utils.test import make_content, BaseIndexableTestCase
from example.testcontent.models import (TestContentObj, TestReadingListObj, TestVideoContentObj)
from bulbs.videos.models import VideohubVideo
class ContentManage... | theonion/django-bulbs | tests/content/test_content_manager.py | Python | mit | 3,750 |
import os, sys
import shutil
brief = "output field types"
def execute(argv, argv0, engine):
print("""
table.big_increments('id') Incrementing ID using a “big integer” equivalent
table.big_integer('votes') BIGINT equivalent to the table
table.binary('data') ... | kreopt/aioweb | wyrm/modules/help/orator/types.py | Python | mit | 2,556 |
transforms = [
(1,0),
(-1,0),
(0,1),
(0,-1),
(-1,-1),
(-1,1),
(1,1),
(1,-1)
]
class Grid:
def __init__(self, filename):
self.flashes = 0
with open(filename) as f:
self.grid = []
for line in f:
line = line.strip()
... | astonshane/AdventOfCode | 2021/day11.py | Python | mit | 2,149 |
"""reqwire: wire up Python requirements with pip-tools."""
from __future__ import absolute_import
import pkg_resources
try: # pragma: no cover
__version__ = pkg_resources.get_distribution(__name__).version
except: # noqa: B901
__version__ = 'unknown'
| darvid/reqwire | src/reqwire/__init__.py | Python | mit | 264 |
from .providers import ProviderContext
from kao_decorators import proxy_for
@proxy_for('config', ['newConverter'])
class ConversionContext:
""" Represents the Configuration and Keyword Arguments provided to a Converter """
def __init__(self, config, **kwargs):
""" Initialize with the confi... | cloew/KaoJson | kao_json/conversion_context.py | Python | mit | 559 |
from typing import Dict, Iterable, Optional
from iota import AdapterSpec, Address, BundleHash, ProposedTransaction, Tag, \
TransactionHash, TransactionTrytes, TryteString, TrytesCompatible
from iota.adapter import BaseAdapter, resolve_adapter
from iota.commands import CustomCommand, core, extended
from iota.crypto... | iotaledger/iota.lib.py | iota/api_async.py | Python | mit | 57,097 |
import unittest
import numpy as np
import numpy.testing as test
from word2gauss.words import Vocabulary, iter_pairs
DTYPE = np.float32
class TestIterPairs(unittest.TestCase):
def test_iter_pairs(self):
np.random.seed(1234)
vocab = Vocabulary({'zero': 0, 'one': 1, 'two': 2})
actual = list... | seomoz/word2gauss | test/test_words.py | Python | mit | 1,114 |
import curses
import gspread
from google_credentials import username, password
from textwrap import fill
from multiprocessing import Pipe, Process, Event
class MainTerminal:
"""Class to manage the loading and refreshing of the main terminal."""
def _parse_menu(
self,
tmp_menu_list,
... | nasfarley88/rpg-game-terminal | main_terminal.py | Python | mit | 6,631 |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
FILE: sample_analyze_conversation_app_async.py
DESCRIPTION:
This sample demonstrates how to analyze user query for intents and entities using a ... | Azure/azure-sdk-for-python | sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_analyze_conversation_app_async.py | Python | mit | 2,671 |
"""
WSGI config for pelawak project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Django... | mclumd/pelawak | pelawak/wsgi.py | Python | mit | 482 |
# coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from .models import Book, Author, Publisher, Genre
admin.site.register(Book, admin.ModelAdmin)
admin.site.register(Author, admin.ModelAdmin)
admin.site.register(Publisher, admin.ModelAdmin)
admin.site.register(Genre, admin.ModelA... | ToxicWar/bibliotheque | library/admin.py | Python | mit | 326 |
import _plotly_utils.basevalidators
class ZerolinecolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="zerolinecolor", parent_name="layout.scene.zaxis", **kwargs
):
super(ZerolinecolorValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/scene/zaxis/_zerolinecolor.py | Python | mit | 438 |
class Solution:
# @param {string} path the original path
# @return {string} the simplified path
def simplifyPath(self, path):
# Write your code here
stack = []
i = 0
res = ""
while i < len(path):
end = i + 1
while end < len(path) and path[end] != "/"... | quake0day/oj | Simplify Path.py | Python | mit | 708 |
import caveGenerate
import yaml
filename = 'data/cavegen.map'
def addObjects():
o = list()
o.append('floor')
o.append('ground')
o.append('apple')
o.append('cherry')
o.append('enemy_poringp')
o.append('enemy_poringb')
return o
def writeMap(fn, m):
data = yaml.dump(m, default_flow_s... | anokata/pythonPetProjects | surgame/src/mapGenerator.py | Python | mit | 1,097 |
import json
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Optional, Type, TypeVar, Union
from .parse import Protocol, load_file, load_str_bytes
from .types import StrBytes
from .typing import display_as_type
__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as')
Name... | glenngillen/dotfiles | .vscode/extensions/ms-python.python-2021.5.842923320/pythonFiles/lib/jedilsp/pydantic/tools.py | Python | mit | 2,169 |
# coding=utf8
# encoding: utf-8
import os
import platform
import re
import signal
import sys
import traceback
from subprocess import Popen, PIPE
from threading import Thread, current_thread
from Queue import Queue
from util.log import get_logger, log
from video.models import Video, KeywordVideoId
from django.db.mode... | tangyanhan/homesite | manage_videos/import_videos.py | Python | mit | 11,680 |
# NEVER DO THIS IN SQL!
from Repository.Loader import Loader, LoaderException
from Domain import Grade, Student, Discipline
import sqlite3
class SQLLoader(Loader):
def __init__(self, repo):
self.repo = repo
self.conn = sqlite3.connect(self.repo.getStoragePath() + ".sqlite")
self.cursor = s... | Zephyrrus/ubb | YEAR 1/SEM1/FP/LAB/l6-l9/Repository/SQLLoader.py | Python | mit | 2,336 |
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# @Author: Alexander Sharov
from entity import config as cfg
from entity import calendar as cal
from generator import schedule as sch
def main():
config = cfg.Config()
calendar = cal.Calendar(configuration=config)
schedule = sch.generate('http://www.sgu.ru/sc... | kvendingoldo/Import-SSU-schedule-to-Google-Calendar | src/python/importer/main.py | Python | mit | 547 |
from __future__ import unicode_literals
from djblets.webapi.errors import WebAPIError
class WebAPITokenGenerationError(Exception):
"""An error generating a Web API token."""
pass
#
# Standard error messages
#
UNSPECIFIED_DIFF_REVISION = WebAPIError(
200,
'Diff revision not specified.',
http_sta... | custode/reviewboard | reviewboard/webapi/errors.py | Python | mit | 4,753 |
#!/usr/bin/env python
# Author: Angela Chapman
# Date: 8/6/2014
#
# This file contains code to accompany the Kaggle tutorial
# "Deep learning goes to the movies". The code in this file
# is for Part 1 of the tutorial on Natural Language Processing.
#
# *************************************** #
import os
from sk... | weiwang/popcorn | analysis/BagOfWords.py | Python | mit | 4,190 |
import numpy as np
import theano
from theano import tensor as T
from generateTrainDataonText import createTrain
from neuralmodels.utils import permute
from neuralmodels.loadcheckpoint import *
from neuralmodels.costs import softmax_loss
from neuralmodels.models import *
from neuralmodels.predictions import OutputMaxPro... | avisingh599/NeuralModels | character-rnn/char-rnn.py | Python | mit | 1,663 |
# first lets get 2 numbers to add
print "enter 2 number to add"
py
# getting the first number
number1 = raw_input("Ok enter the first number ")
# and now the second number
number2 = raw_input("and now the second number ")
# finally calculating the addidition of the numbers
# sum = number1 + number2
# seems to be ri... | OpenGuide/Python-Guide-for-Beginners | SimpleAddition/Sum_2_numbers.py | Python | mit | 661 |
"""
Description : Python implementation of Apriori Algorithm
Usage $python main.py -f [filename] -s [minSupport] -c [minConfidence]
Note to readers : my data structure is a list contains sets contains lists inside the sets
The reason I choose to implement in this way is because I can use the union method of the sets
... | MohanL/apriori-Fpgrowth | apriori.py | Python | mit | 5,171 |
import unittest
from LuckyNumbers import count
from typing import Dict, List
class TestLuckyNumbers(unittest.TestCase):
"""
All the unit tests of the lucky numbers program.
"""
def test_count_0(self):
"""
Tests the simplest case, with 0.
"""
self.assertEqual(count(0), ... | informaticienzero/CodinGame | Communautaires/[UT] The lucky number.py | Python | mit | 7,749 |
#!/usr/bin/python
import sys
sys.path.insert(0, '/usr/local/lib/python2.7/site-packages/')
import mraa
import time
from twython import Twython
# Authentication - Obtain Authorization URL
APP_KEY = 'lXZFwVtC8CGPKs4LOuv2m7WGS'
APP_SECRET = 'AoToSyNNyhzg2EhN38Edx6bQ59wPSLH8ztLZNZkWt1us7IzKUl'
OAUTH_TOKEN = '2892359329-f... | HelloTechie/tweeting_turkey | turkey_tweet.py | Python | mit | 1,243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.