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 django.urls import path, re_path
from . import views
urlpatterns = [
path('noslash', views.empty_view),
path('slash/', views.empty_view),
path('needsquoting#/', views.empty_view),
# Accepts paths with two leading slashes.
re_path(r'^(.+)/security/$', views.empty_view),
]
| georgemarshall/django | tests/middleware/urls.py | Python | bsd-3-clause | 299 |
from __future__ import unicode_literals
import cgi
import codecs
import logging
import sys
from io import BytesIO
from threading import Lock
import warnings
from django import http
from django.conf import settings
from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers impo... | rooshilp/CMPUT410Lab6 | virt_env/virt1/lib/python2.7/site-packages/django/core/handlers/wsgi.py | Python | apache-2.0 | 9,514 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# Plural-Forms for af (Afrikaans (South Africa))
nplurals=2 # Afrikaans language has 2 forms:
# 1 singular and 1 plural
# Determine plural_id for number *n* as sequence of positive
# integers: 0,1,...
# NOTE! For singular form ALWAYS return plural_id = 0
get_p... | manuelep/openshift_v3_test | wsgi/web2py/gluon/contrib/plural_rules/af.py | Python | mit | 598 |
"""Python 2/3 compatibility definitions.
These are used by the rest of Elpy to keep compatibility definitions
in one place.
"""
import sys
if sys.version_info >= (3, 0):
PYTHON3 = True
from io import StringIO
def ensure_not_unicode(obj):
return obj
else:
PYTHON3 = False
from StringIO... | dspelaez/dspelaez.github.io | resources/dotfiles/dot.emacs.d.own/elpa/elpy-20170214.318/elpy/compat.py | Python | mit | 673 |
import errno
from http import client
import io
import os
import array
import socket
import unittest
TestCase = unittest.TestCase
from test import support
here = os.path.dirname(__file__)
# Self-signed cert file for 'localhost'
CERT_localhost = os.path.join(here, 'keycert.pem')
# Self-signed cert file for 'fakehostna... | invisiblek/python-for-android | python3-alpha/python3-src/Lib/test/test_httplib.py | Python | apache-2.0 | 24,526 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | dcorbacho/libcloud | libcloud/test/loadbalancer/test_brightbox.py | Python | apache-2.0 | 5,292 |
# Copyright 2013, Big Switch Networks
# 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 requ... | yuewko/neutron | neutron/plugins/bigswitch/routerrule_db.py | Python | apache-2.0 | 1,500 |
from geopy.point import Point
class Location(object):
def __init__(self, name="", point=None, attributes=None, **kwargs):
self.name = name
if point is not None:
self.point = Point(point)
if attributes is None:
attributes = {}
self.attributes = dict(attributes... | golismero/golismero | thirdparty_libs/geopy/location.py | Python | gpl-2.0 | 850 |
# -*- 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 GNU... | inovtec-solutions/OpenERP | openerp/addons/lunch/report/report_lunch_order.py | Python | agpl-3.0 | 2,799 |
"""Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is remov... | DmitryADP/diff_qc750 | vendor/nvidia/tegra/3rdparty/python-support-files/src/Lib/commands.py | Python | gpl-2.0 | 2,540 |
def build_models(payment_class):
return []
| dekoza/django-getpaid | getpaid/backends/transferuj/models.py | Python | mit | 47 |
from matplotlib.numerix import which
if which[0] == "numarray":
from numarray.linear_algebra.mlab import *
elif which[0] == "numeric":
from MLab import *
elif which[0] == "numpy":
try:
from numpy.oldnumeric.mlab import *
except ImportError:
from numpy.lib.mlab import *
else:
raise Run... | tkaitchuck/nupic | external/linux64/lib/python2.6/site-packages/matplotlib/numerix/mlab/__init__.py | Python | gpl-3.0 | 381 |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division)
__metaclass__ = type
import json
import os
import shutil
import tempfile
import p... | aperigault/ansible | test/units/module_utils/basic/test_tmpdir.py | Python | gpl-3.0 | 4,159 |
from __future__ import unicode_literals
from django.db import router
from .base import Operation
class SeparateDatabaseAndState(Operation):
"""
Takes two lists of operations - ones that will be used for the database,
and ones that will be used for the state change. This allows operations
that don't ... | KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/db/migrations/operations/special.py | Python | gpl-3.0 | 7,662 |
xs = 1<caret>, 2
| ahb0327/intellij-community | python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertTupleWithoutParenthesesToList.py | Python | apache-2.0 | 17 |
from __future__ import unicode_literals
import datetime
import unittest
from django.apps.registry import Apps
from django.core.exceptions import ValidationError
from django.db import models
from django.test import TestCase
from .models import (
CustomPKModel, FlexibleDatePost, ModelToValidate, Post, UniqueErrors... | DONIKAN/django | tests/validation/test_unique.py | Python | bsd-3-clause | 7,108 |
try:
1 // 0
except ZeroDivisionError:
print("ZeroDivisionError")
try:
1 % 0
except ZeroDivisionError:
print("ZeroDivisionError")
| pfalcon/micropython | tests/basics/int_divzero.py | Python | mit | 146 |
class <caret>A(B
pass | caot/intellij-community | python/testData/codeInsight/smartEnter/class.py | Python | apache-2.0 | 25 |
def foo(bar):
""" @param """ | asedunov/intellij-community | python/testData/completion/epydocTagsMiddle.after.py | Python | apache-2.0 | 32 |
class Foo:
@property
def bar(self):
import warnings
warnings.warn("this is deprecated", DeprecationWarning, 2)
foo = Foo()
foo.<warning descr="this is deprecated">bar</warning>
| asedunov/intellij-community | python/testData/deprecation/deprecatedProperty.py | Python | apache-2.0 | 202 |
""" Python Character Mapping Codec iso8859_5 generated from 'MAPPINGS/ISO8859/8859-5.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,i... | zwChan/VATEC | ~/eb-virt/Lib/encodings/iso8859_5.py | Python | apache-2.0 | 13,578 |
# -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y.'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. E Y. H:i'
YEAR_MONTH... | ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/conf/locale/hr/formats.py | Python | bsd-3-clause | 1,758 |
"""
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""
from __future__ import unicode_literals
import mimetypes
import os
import stat
import posixpath
import re
try:
from urllib.parse import unquote
except ImportError: ... | ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/views/static.py | Python | bsd-3-clause | 5,193 |
"""
Iterator based sre token scanner
"""
import sre_parse, sre_compile, sre_constants
from sre_constants import BRANCH, SUBPATTERN
from re import VERBOSE, MULTILINE, DOTALL
import re
__all__ = ['Scanner', 'pattern']
FLAGS = (VERBOSE | MULTILINE | DOTALL)
class Scanner(object):
def __init__(self, lexicon, flags=FL... | ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/utils/simplejson/scanner.py | Python | bsd-3-clause | 2,009 |
# Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# 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 withou... | harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/integration/swf/test_cert_verification.py | Python | gpl-3.0 | 1,553 |
# Copyright 2009 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 ... | jjoaonunes/namebench | libnamebench/tk.py | Python | apache-2.0 | 13,586 |
data = (
'Yao ', # 0x00
'Yu ', # 0x01
'Chong ', # 0x02
'Xi ', # 0x03
'Xi ', # 0x04
'Jiu ', # 0x05
'Yu ', # 0x06
'Yu ', # 0x07
'Xing ', # 0x08
'Ju ', # 0x09
'Jiu ', # 0x0a
'Xin ', # 0x0b
'She ', # 0x0c
'She ', # 0x0d
'Yadoru ', # 0x0e
'Jiu ', # 0x0f
'Shi ', # 0x10
'Tan ... | samuelmaudo/yepes | yepes/utils/unidecode/x082.py | Python | bsd-3-clause | 4,649 |
# -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | oshepherd/eforge | eforge/views.py | Python | isc | 2,416 |
"""Host Reservation DHCPv6"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_msg
import srv_control
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
@pytest.mark.pgsql
def test_v6_host_reservation_duplicate_reservation_duid():
misc.test_setup()
srv_cont... | isc-projects/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_pgsql.py | Python | isc | 22,290 |
import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_success(getenv):
getenv.return_value = 'world'
assert require('hello') == 'wo... | textbook/flask-forecaster | tests/test_config.py | Python | isc | 3,431 |
"""
Collection of astronomy-related functions and utilities
"""
__version__ = '0.1.1'
| KathleenLabrie/KLpyastro | klpyastro/__init__.py | Python | isc | 86 |
from collections import defaultdict
from operator import itemgetter
import re
def isRealRoom(name, checksum):
if len(checksum) != 5:
raise Exception
totals = defaultdict(int)
for c in name:
if c != '-':
totals[c] += 1
pairs = zip(totals.keys(), totals.values())
alphaPair... | kmcginn/advent-of-code | 2016/day04/security.py | Python | mit | 922 |
from typing import List
class Solution:
def arrayStringsAreEqualV1(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
def arrayStringsAreEqualV2(self, word1: List[str], word2: List[str]) -> bool:
def generator(word: List[str]):
for s in word... | l33tdaima/l33tdaima | pr1662e/array_strings_are_equal.py | Python | mit | 950 |
import math
from pyb import DAC, micros, elapsed_micros
def tone1(freq):
t0 = micros()
dac = DAC(1)
while True:
theta = 2*math.pi*float(elapsed_micros(t0))*freq/1e6
fv = math.sin(theta)
v = int(126.0 * fv) + 127
#print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
... | pramasoul/pyboard-fun | tone.py | Python | mit | 1,739 |
# Problem name: 12148 Electricity
# Problem url: https://uva.onlinejudge.org/external/121/12148.pdf
# Author: Andrey Yemelyanov
import sys
import math
import datetime
def readline():
return sys.stdin.readline().strip()
def main():
while True:
n_readings = int(readline())
if n_readings == 0:
... | andrey-yemelyanov/competitive-programming | cp-book/ch1/adhoc/time/12148_Electricity.py | Python | mit | 1,212 |
import DeepFried2 as df
from .. import dfext
def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)):
kw = dict(mkbn=mkbn)
net = df.Sequential(
# -> 128x48
df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None),
dfext.resblock(64, **kw),
df.PoolingCUDNN((2,2... | VisualComputingInstitute/towards-reid-tracking | lib/models/lunet2.py | Python | mit | 1,896 |
# Copyright 2017 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... | lanpa/tensorboardX | tensorboardX/beholder/beholder.py | Python | mit | 8,355 |
#Author Emily Keiser
def addition(x,y):
return int(x)+int(y)
def subtraction (x,y) :
return int(x) -int(y)
def multiplication (x,y) :
return int(x) *int(y)
def module (x,y) :
return int(x) %int(y)
a=raw_input("Enter variable a: ")
b=raw_input("Enter variable b: ")
print addition (a,b)
print subtrac... | davidvillaciscalderon/PythonLab | Session 3/basic_operations_with_function.py | Python | mit | 537 |
# pylint: disable=api-one-deprecated
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda in... | it-projects-llc/website-addons | portal_event_tickets/models/event_mail.py | Python | mit | 3,646 |
# Jacqueline Kory Westlund
# May 2016
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Personal Robots Group
#
# 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 w... | personal-robots/sar_social_stories | src/ss_script_handler.py | Python | mit | 43,375 |
import tornado.web
import forms
import config
import io
class Index(tornado.web.RequestHandler):
"""
Returns the index page.
"""
def get(self):
form = forms.RecomputeForm()
recomputations_count = io.get_recomputations_count()
latest_recomputations = io.load_all_recomputations... | cjw-charleswu/Recompute | recompute/server/pageserver.py | Python | mit | 1,804 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actua... | tgbugs/hypush | test/memex/util/markdown_test.py | Python | mit | 3,893 |
import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def no_op():
pass
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
... | xlevus/python-diana | tests/test_context.py | Python | mit | 1,257 |
from django.db import models
from django_hstore import hstore
# Create your models here.
class Place(models.Model):
osm_type = models.CharField(max_length=1)
osm_id = models.IntegerField(primary_key=True)
class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved wor... | lluc/django_jdf | jdf/models.py | Python | mit | 1,451 |
from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... | gilleshenrard/ikoab_elise | api/views.py | Python | mit | 2,172 |
from django.conf import settings
""" Your GSE API key """
GOOGLE_SEARCH_API_KEY = getattr(settings, 'GOOGLE_SEARCH_API_KEY', None)
""" The ID of the Google Custom Search Engine """
GOOGLE_SEARCH_ENGINE_ID = getattr(settings, 'GOOGLE_SEARCH_ENGINE_ID', None)
""" The API version. Defaults to 'v1' """
GOOGLE_SEARCH_AP... | hzdg/django-google-search | googlesearch/__init__.py | Python | mit | 662 |
'''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | gavinfish/leetcode-share | python/126 Word Ladder II.py | Python | mit | 3,018 |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generatin... | nickjhughes/polyominohs | generator.py | Python | mit | 7,968 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import io
import unittest
from prov.model import *
from prov.dot import prov_to_dot
from prov.serializers import Registry
from prov.tests.examples import primer_example, primer_example_alternate
EX_NS = Name... | krischer/prov | prov/tests/test_extras.py | Python | mit | 8,671 |
# -*- coding: utf-8 -*-
"""
sphinx.ext.napoleon.docstring
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Classes for docstring parsing and formatting.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import collections
import inspect
import re
# from ... | ajbouh/tfi | src/tfi/parse/docstring.py | Python | mit | 17,890 |
from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... | zenieldanaku/DyDCreature_Editor | azoe/widgets/basewidget.py | Python | mit | 2,314 |
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
#
# 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 appli... | ool2016-seclab/quarantineSystem | ryu/services/protocols/bgp/utils/bgp.py | Python | mit | 5,129 |
#!/usr/bin/env python
from mattermost_bot.bot import Bot, PluginsManager
from mattermost_bot.mattermost import MattermostClient
from mattermost_bot.dispatcher import MessageDispatcher
import bot_settings
class LocalBot(Bot):
def __init__(self):
self._client = MattermostClient(
bot_settings.BOT... | seLain/mattermost_bot | tests/behavior_tests/run_bot.py | Python | mit | 701 |
import numpy as np
import cv2
import cv2.cv as cv
#im = cv2.imread('/Users/asafvaladarsky/Documents/img/Ad0010401.png')
im = cv2.imread('pic.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
invert = 255 - imgray
cv2.imwrite('/Users/asafvaladarsky/Documents/pic1.png', invert)
#ret,thresh = cv2.threshold(invert,0,0,... | hasadna/OpenPress | engine/ocr/Test1.py | Python | mit | 2,585 |
#!/usr/bin/env python
"""
moveit_attached_object_demo.py - Version 0.1 2014-01-14
Attach an object to the end-effector and then move the arm to test collision avoidance.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2014 Patrick Goebel. All rights reserved.
This... | fujy/ROS-Project | src/rbx2/rbx2_arm_nav/scripts/moveit_attached_object_demo.py | Python | mit | 4,719 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from os import listdir
files = listdir('./data/plots/')
colorarray = np.random.random_sample((10000, 3))
for f in files:
size = int(f.split('-')[0])
x, y, c = np.loadtxt('./data/plots/' + f, unpack=True)
fig = plt.fig... | kdungs/coursework-computational-physics | src/02/plot_forest.py | Python | mit | 630 |
from pypermissions.permission import PermissionSet
def _prepare_runtime_permission(self, perm=None, runkw=None, args=None, kwargs=None):
"""This function parses the provided string arguments to decorators into the actual values for use when the
decorator is being evaluated. This allows for permissions to be c... | Acidity/PyPermissions | pypermissions/decorators.py | Python | mit | 5,369 |
#!/usr/bin/env python3
import sys
import os
import subprocess
import time
filename = sys.argv[1]
print("extracting " + filename)
p = subprocess.Popen(["unzip", filename, "-dintro"], stdout=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(["php","-f","uploadtodb.php","intro/courses.csv","courses"],stdout=subproc... | 401LearningAnalytics/Project | server_side/upload.py | Python | mit | 2,202 |
#! /usr/bin/env python3
# encoding: utf-8
'''
http://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
# Since May 22 2012
from projecteuler import c... | fossilet/project-euler | pe1.py | Python | mit | 1,110 |
"""
file: cas_manager.py
authors: Christoffer Rosen <cbr4830@rit.edu>
date: Jan. 2014
description: This module contains the CAS_manager class, which is a thread that continously checks if there
is work that needs to be done. Also contains supporting classes of Worker and ThreadPool used by
the CAS_Manager.
"""
... | bumper-app/bumper-bianca | bianca/cas_manager.py | Python | mit | 7,075 |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | miguelgrinberg/flasky | config.py | Python | mit | 3,883 |
import csv
from datetime import datetime
from matplotlib import pyplot as plt
# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_2017.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
cu... | helanan/Panda_Prospecting | panda_prospecting/prospecting/insights/high_lows.py | Python | mit | 966 |
# -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
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,... | ollej/shoutbridge | src/plugins/CryptoPlugin.py | Python | mit | 2,129 |
#!/usr/bin/env python3
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
@click.command()
@click.version_option(__version__)
@click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type... | janpipek/boadata | boadata/commands/boaview.py | Python | mit | 911 |
r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
't... | flav-io/flavio | flavio/physics/higgs/signalstrength.py | Python | mit | 3,003 |
import numpy as np
import cv2
from math import pi
def points2mapa(landmarks,pos_rob,mapa,P, delete_countdown): #mapa = (x,y, Px,Py, updt)
new_points2add = []
landmarks = np.array(landmarks)
for i in range(0,landmarks.shape[0]):
x_mapa = pos_rob[0] + landmarks[i,1]*np.cos((pos_rob[2])*pi/180+landmarks[i,0])
... | TheCamusean/DLRCev3 | scripts/slam/mapping_BASE_10668.py | Python | mit | 5,371 |
import collections
from client.constants import FieldKeyword
from metadata import Metadata
class FileUrlMetadata(Metadata):
def get_title(self, soup):
image_url = self.prop_map[FieldKeyword.URL]
return image_url.split('/')[-1]
def get_files_list(self, response):
file_list = collecti... | SAAVY/magpie | client/scraper/file_metadata.py | Python | mit | 836 |
#! .env/bin/python
# -*- coding: utf8 -*-
from __future__ import unicode_literals
# import time
import random
import itertools
# from collections import defaultdict
import gym
import numpy as np
# implementation of the sarsa algorithm on the mountain car using values
# rounding for value function approximation
# N... | Hiestaa/RLViz | experiments/gym_test_2.py | Python | mit | 7,015 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... | cryptapus/electrum-uno | lib/pem.py | Python | mit | 6,584 |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="surface.hoverlabel.font", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=... | plotly/plotly.py | packages/python/plotly/plotly/validators/surface/hoverlabel/font/_color.py | Python | mit | 470 |
''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... | joejcollins/CaptainScarlet | web_app/main.py | Python | mit | 2,641 |
# -*- coding: utf-8 -*-
import os
from fuel import config
from fuel.datasets import H5PYDataset
from fuel.transformers.defaults import uint8_pixels_to_floatX
class SVHN(H5PYDataset):
"""The Street View House Numbers (SVHN) dataset.
SVHN [SVHN] is a real-world image dataset for developing machine
learnin... | EderSantana/fuel | fuel/datasets/svhn.py | Python | mit | 2,213 |
from seabreeze.pyseabreeze.features._base import SeaBreezeFeature
# Definition
# ==========
#
# TODO: This feature needs to be implemented for pyseabreeze
#
class SeaBreezeDataBufferFeature(SeaBreezeFeature):
identifier = "data_buffer"
def clear(self) -> None:
raise NotImplementedError("implement in ... | ap--/python-seabreeze | src/seabreeze/pyseabreeze/features/databuffer.py | Python | mit | 1,040 |
"""
Basic pulsar-related functions and statistics.
"""
import functools
from collections.abc import Iterable
import warnings
from scipy.optimize import minimize, basinhopping
import numpy as np
import matplotlib.pyplot as plt
from .fftfit import fftfit as taylor_fftfit
from ..utils import simon, jit
from . import HAS... | abigailStev/stingray | stingray/pulse/pulsar.py | Python | mit | 25,604 |
from Crypto import Random
from src.aes import encrypt_message, decrypt_message
def test_integrity():
plaintext = 'Test Text'
key = Random.new().read(16)
# Ensure that D(k, E(k, p)) == p
assert decrypt_message(key, encrypt_message(key, plaintext)) == plaintext
def test_privacy():
plaintext = 'T... | MichaelAquilina/CryptoTools | src/tests/aes_test.py | Python | mit | 561 |
import shutil
import tempfile
import time
import os
import random
import subprocess
import unittest
from basefs.keys import Key
from basefs.logs import Log
from . import utils
class MountTests(unittest.TestCase):
def setUp(self):
__, self.logpath = tempfile.mkstemp()
__, self.logpath_b = tempfil... | glic3rinu/basefs | basefs/tests/test_mount.py | Python | mit | 2,043 |
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import datetime
from Bio.Seq import Seq
if __name__ == '__main__':
from needleman_wunsch import needleman_wunsch
else:
from .needleman_wunsch import needleman_wunsch
#-------------------------------
def plot_nw(seq_alpha_col,... | kevinah95/bmc-sequence-alignment | algorithms/needleman_wunsch/plot_nw.py | Python | mit | 3,189 |
# http://stackoverflow.com/questions/1477294/generate-random-utf-8-string-in-python
import random
def get_random_unicode(length):
try:
get_char = unichr
except NameError:
get_char = chr
# Update this to include code point ranges to be sampled
include_ranges = [
(0x0021, ... | gouthambs/Flask-Blogging | test/utils.py | Python | mit | 948 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Alexander David Leech
@date: 03/06/2016
@rev: 1
@lang: Python 2.7
@deps: YAML
@desc: Class to use as an interface to import YAML files
"""
import yaml
class yamlImport():
@staticmethod
def importYAML(pathToFile):
try:
... | FlaminMad/RPiProcessRig | RPiProcessRig/src/yamlImport.py | Python | mit | 521 |
"""
Example of module documentation which can be
multiple-lined
"""
from sqlalchemy import Column, Integer, String
from wopmars.Base import Base
class FooBaseH(Base):
"""
Documentation for the class
"""
__tablename__ = "FooBaseH"
id = Column(Integer, primary_key=True, autoincrement=True)
na... | aitgon/wopmars | wopmars/tests/resource/model/FooBaseH.py | Python | mit | 472 |
"""
Derivation and Elementary Trees live here.
"""
from __future__ import print_function
from baal.structures import Entry, ConstituencyTree, consts
from baal.semantics import Predicate, Expression
from collections import deque
from copy import copy, deepcopy
from math import floor, ceil
try:
input = raw_input
ex... | braingineer/baal | baal/structures/gist_trees.py | Python | mit | 54,149 |
import guess_language
import threading
from job_queue import JobQueue
from multiprocessing import cpu_count
from app_config import *
from html_parser_by_tag import HTMLParserByTag
from event_analysis import EventAnalysis
from events.models import Event, Feature, EventFeature, Weight
from tree_tagger import Tree... | Diego999/Social-Recommendation-System | event_analyse/functions.py | Python | mit | 13,838 |
# ######## KADEMLIA CONSTANTS ###########
BIT_NODE_ID_LEN = 160
HEX_NODE_ID_LEN = BIT_NODE_ID_LEN // 4
# Small number representing the degree of
# parallelism in network calls
ALPHA = 3
# Maximum number of contacts stored in a bucket
# NOTE: Should be an even number.
K = 8 # pylint: disable=invalid-name
# Maximum n... | im0rtel/OpenBazaar | node/constants.py | Python | mit | 1,678 |
"""Tests for distutils.archive_util."""
__revision__ = "$Id: test_archive_util.py 86596 2010-11-20 19:04:17Z ezio.melotti $"
import unittest
import os
import tarfile
from os.path import splitdrive
import warnings
from distutils.archive_util import (check_archive_formats, make_tarball,
... | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.2/Lib/distutils/tests/test_archive_util.py | Python | mit | 7,249 |
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=30)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
de... | bootcamptropa/django | categories/models.py | Python | mit | 362 |
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import math
import warnings
from random import shuffle
from unittest import TestCase
from matrixprofile.exceptions import... | blue-yonder/tsfresh | tests/units/feature_extraction/test_feature_calculations.py | Python | mit | 83,172 |
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.utils.safestring import mark_safe
# Create your models here.
class ProductQuerySet(models.query.QuerySet):
def active(self):
return sel... | dizzy54/ecommerce | src/products/models.py | Python | mit | 5,256 |
#!/usr/bin/env python2
import ringo_config
cfg = ringo_config.RingoConfig()
import pyximport;pyximport.install(build_dir=cfg.pyximport_build())
import argparse
import random
import numpy as np
import model
from simulation import Simulation, SimParameters, EventType, RearrangementType
def run_L_D_simulation(self, L, ... | pedrofeijao/RINGO | src/ringo/LD_simulation.py | Python | mit | 5,857 |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
mu = 0
variance1 = 20000**2
variance2 = 2000**2
sigma1 = math.sqrt(variance1)
sigma2 = math.sqrt(variance2)
x = np.linspace(mu - 3*sigma1, mu + 3*sigma1, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma1))
... | jdurbin/sandbox | python/plotting/plotnormal.py | Python | mit | 568 |
VERSION = (0, 11)
__version__ = '.'.join(map(str, VERSION))
DATE = "2015-02-06"
| 20tab/twentytab-sortable | sortable/__init__.py | Python | mit | 80 |
#!/usr/bin/env python3
import sys
import os
import path_utils
import generic_run
def puaq():
print("Usage: %s input_file.flac" % path_utils.basename_filtered(__file__))
sys.exit(1)
def convert_flac_to_mp3(input_file, output_file, bitrate):
cmd = ["ffmpeg", "-i", input_file, "-ab", bitrate, "-map_metadat... | mvendra/mvtools | audio/flac_to_mp3.py | Python | mit | 823 |
"""
Flask-Validictory
-------------
Simple integration between Flask and Validictory.
"""
import os
from setuptools import setup
module_path = os.path.join(os.path.dirname(__file__), 'flask_validictory.py')
version_line = [line for line in open(module_path)
if line.startswith('__version_info__')][0]
... | inner-loop/flask-validictory | setup.py | Python | mit | 1,318 |
from .base import ApplicationVersion, package_version # noqa
| LostProperty/wsgiappversion | wsgiappversion/__init__.py | Python | mit | 62 |
# @name <%= app_name %>
# @description
# Models for UserControler.
import json
from src.models import BaseModel
class <%= endpoint %>Model(BaseModel):
_parse_class_name = '<%= table %>'
pass | nghiattran/generator-python-parse | generators/endpoint/templates/model_template.py | Python | mit | 201 |
#!/usr/bin/python3
# -*- Coding : UTF-8 -*-
from os import path
import github_update_checker
from setuptools import setup, find_packages
file_path = path.abspath(path.dirname(__file__))
with open(path.join(file_path, "README.md"), encoding="UTF-8") as f:
long_description = f.read()
setup(
name="github_upda... | BenjaminSchubert/py_github_update_checker | setup.py | Python | mit | 995 |
"""Forms to render HTML input & validate request data."""
from wtforms import Form, BooleanField, DateTimeField, PasswordField
from wtforms import TextAreaField, TextField
from wtforms.validators import Length, required
class AppointmentForm(Form):
"""Render HTML input for Appointment model & validate submission... | abacuspix/NFV_project | Instant_Flask_Web_Development/sched/forms.py | Python | mit | 1,083 |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(3,GPIO.OUT)
state=True
GPIO.output(3,True)
| raj808569/homeautomationIOT | d.py | Python | mit | 139 |
from collections.abc import Mapping, Iterable
from ctypes import c_int, c_int32, c_double, c_char_p, POINTER
from weakref import WeakValueDictionary
import numpy as np
from numpy.ctypeslib import as_array
from openmc.exceptions import AllocationError, InvalidIDError
from . import _dll
from .core import _FortranObject... | wbinventor/openmc | openmc/capi/cell.py | Python | mit | 5,272 |
import collections
import yaml
import netCDF4
import numpy as np
from pyresample import geometry
from pyresample import kd_tree
from pyresample import utils
from pyresample import grid
from satistjenesten.utils import get_area_filepath
class GenericScene(object):
""" Generic Scene object
It is a parent class... | mitkin/avhrr-sic-analysis | satistjenesten/data.py | Python | mit | 7,349 |
"""kuoteng_bot URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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... | rapirent/toc_project | kuoteng_bot/kuoteng_bot/urls.py | Python | mit | 972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.