code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
import logging
class HeaderReorganization(object):
def __init__(self, project_layout, project_services):
self.project_layout = project_layout
self.project_services = project_services
def reorganizeHeaders(self):
logger = logging.getLogger('Archie')
logger.debug('Reorganizin... | niccroad/Archie | archie/headertiers/businessrules/HeaderReorganization.py | Python | mit | 4,774 |
from rest_framework.routers import DefaultRouter
from retail.views import CategoryViewSet, AssetViewSet, ProductViewSet, get_auth_token, UserViewSet, \
CustomerViewSet
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.authtoken import v... | Nobay/SampleStore | restful-api/urls.py | Python | mit | 1,066 |
class Config:
ServerUrl = 'http://homeserver.spdns.org/blot.php'
UseGetRequests = True
NotificationServiceUrl = 3333
IFTTTUrlTemplate = "https://maker.ifttt.com/trigger/tag_%s_pressed/with/key/cV2tU0tD8V2UWOjPb4H7SO"
| fablab-ka/labtags | blot-gateway/config.py | Python | mit | 234 |
"""Unit tests for top_k_accuracy.py
Written by Grant Van Horn.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import random
import unittest
import numpy as np
import top_k_accuracy
def make_accuracy_data(num_classes, num_test_samples, num_... | visipedia/inat_comp | eval/test_top_k_accuracy.py | Python | mit | 13,223 |
import os, sys, traceback
import github3
import gspread
import io
import json
import logging
from logging.config import dictConfig
from oauth2client.client import SignedJwtAssertionCredentials
GITHUB_CONFIG = {
'TOKEN': os.environ['GITHUB_TOKEN'],
'REPO_OWNER': 'opennews',
'REPO_NAME': 'srccon-2021',
'... | ryanpitts/membot | membot/apps/membot/commands/update_srccon_schedule.py | Python | mit | 8,643 |
"""
Author: Justin Cappos
Start Date: 29 June 2008
Description:
Timer functions for the sandbox. This does sleep as well as setting and
cancelling timers.
"""
import threading
import thread # Armon: this is to catch thread.error
import nanny
import idhelper
# for printing exceptions
import traceba... | SeattleTestbed/repy_v2 | emultimer.py | Python | mit | 3,081 |
from django.conf.urls.defaults import *
urlpatterns = patterns('django_fbi.views',
url(r'^channel/$', 'channel', name='channel'),
url(r'^connect/$', 'connect', name='connect'),
url(r'^deauthorize/$', 'deauthorize', name='deauthorize'),
url(r'^app/(?P<slug>[-\w]+)/$', 'view_app', {'page': 'canvas'... | dmpayton/django-fbi | django_fbi/urls.py | Python | mit | 426 |
import hashlib
import re
def class_name(obj):
class_name = str(type(obj))
class_name = re.search(".*'(.+?)'.*", class_name).group(1)
return class_name
def _can_iterate(obj):
import types
import collections
is_string = isinstance(obj, types.StringTypes)
is_iterable = isinstance(obj, coll... | edublancas/pipeline | pipeline/util.py | Python | mit | 986 |
# -*- coding: utf-8 -*-
from factory import Sequence, LazyAttribute
from factory.alchemy import SQLAlchemyModelFactory
from fogspoon.core import db
from fogspoon.films import Film
from fogspoon.locations import Location, GeoLoc
class BaseFactory(SQLAlchemyModelFactory):
class Meta:
abstract = Tr... | tkalus/fogspoon | tests/factories.py | Python | mit | 1,416 |
"""
This tutorial shows how to use cleverhans.picklable_model
to create models that can be saved for evaluation later.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import numpy as np
import tensor... | cleverhans-lab/cleverhans | cleverhans_v3.1.0/cleverhans_tutorials/mnist_tutorial_picklable.py | Python | mit | 10,006 |
from wrapper import Wrapper
class UberApi(Wrapper):
def __init__(self, user):
Wrapper.__init__(self, __name__.split('.').pop(), user) | whittlbc/jarvis | jarvis/api/uber.py | Python | mit | 138 |
# Create your views here.
import django.contrib.auth
from django.contrib.auth.models import User, check_password
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.http import Http404
from django.template im... | garyp/djwed | wedding/auth.py | Python | mit | 3,976 |
#/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#Simulation time
SimulationTimeFloat=1000.
#SimulationTimeFloat=0.2
BrianingDebugVariable=0.1 if SimulationTimeFloat<0.5 else 25.
#A - transition matrix
JacobianTimeFloat = 10. #(ms)
A... | Ledoux/ShareYourSystem | Pythonlogy/ShareYourSystem/Specials/Predicters/Predicter/tests/03_tests_chaotic/05_01_test_rate_chaotic_dense_ExampleCell.py | Python | mit | 2,520 |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 The Bitcoin Core developers
# Copyright (c) 2017 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test compact blocks (BIP 152).
Only testing Version 1 comp... | ftrader-bitcoinabc/bitcoin-abc | test/functional/p2p_compactblocks.py | Python | mit | 39,944 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Main Menu
"""
from icons import Icons
from pyqode.qt import QtWidgets
from pyqode.core import widgets
from dockTemplate import DockBase
class MainMenuBar(QtWidgets.QMenuBar):
def __init__(self, parent=None):
super(MainMenuBar, self).__init__(parent)
... | Zachacious/PyCreator | PyCreator/UI/mainMenu.py | Python | mit | 3,462 |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 1 19:11:52 2017
@author: mariapanteli
"""
import pytest
import numpy as np
from sklearn.model_selection import train_test_split
import scripts.classification as classification
def test_confusion_matrix():
X = np.random.randn(100, 3)
# create 2 classes by shi... | mpanteli/music-outliers | tests/test_classification.py | Python | mit | 731 |
"""
Problem Statement: https://community.topcoder.com/stat?c=problem_statement&pm=1918&rd=5006
"""
def getOrdering(heights, blooms, wilt):
pass
| MFry/pyAlgoDataStructures | Top_Coder/Dynamic Programming/TCCC04_FlowerGarden.py | Python | mit | 154 |
from django.test import TestCase
from django.shortcuts import render
from django.forms.forms import BoundField
from authtools.forms import UserCreationForm
from tunes.templatetags.add_css import add_class_to_field
class TunesTemplateTagsTestCase(TestCase):
def test_add_class_to_field(self):
"""
... | kevinharvey/ci-jmad | tunes/tests/test_templatetags.py | Python | mit | 599 |
"""
WSGI config for receiver 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.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "receiver.settings")
#from django.cor... | ministryofjustice/courtfinder-govuk-publisher-test | receiver/wsgi.py | Python | mit | 517 |
import cPickle as pckl
import codecs
import argparse
VOCAB_PATH = "../rsc/vocab.pickle"
def main():
""" Main method. """
argument_parser = init_argument_parser()
args = argument_parser.parse_args()
print args
# Save vocabulary to a pickle file
if args.write:
args_dict = vars(args)
... | Kaleidophon/doppelmoppelbot | misc/create_vocab.py | Python | mit | 4,734 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: bigip_irule
short_descr... | F5Networks/f5-ansible-modules | ansible_collections/f5networks/f5_modules/plugins/modules/bigip_irule.py | Python | mit | 16,597 |
import numpy
from six import moves
import chainer
from chainer import cuda
from chainer import function
from chainer.utils import conv
from chainer.utils import type_check
from chainer import variable
if cuda.cudnn_enabled:
cudnn = cuda.cudnn
libcudnn = cuda.cudnn.cudnn
_fwd_pref = libcudnn.CUDNN_CONVOLUT... | kashif/chainer | chainer/functions/connection/dilated_convolution_2d.py | Python | mit | 16,543 |
from PyQt5 import QtWidgets
from PyQt5.QtCore import QCoreApplication
from matplotlib.backends.backend_qt5agg import (FigureCanvasQTAgg as
FigureCanvas)
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as
... | Athemis/PyDSF | ui/mplwidget.py | Python | mit | 2,733 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('plea', '0034_auto_20160519_1047'),
]
operations = [
migrations.AlterField(
model_name='oucode',
name... | ministryofjustice/manchester_traffic_offences_pleas | apps/plea/migrations/0035_auto_20160519_1055.py | Python | mit | 462 |
import tensorflow as tf
import numpy as np
a = tf.placeholder(shape=[3,4], dtype=tf.float32)
b = tf.placeholder(shape=[4,6], dtype=tf.float32)
c = tf.matmul(a,b)
sess = tf.Session()
feed = {a:np.random.randn(3,4), b:np.random.randn(4,6)}
result = sess.run(c, feed_dict=feed)
print (result)
| kiseyno92/SNU_ML | Practice7/code/quiz0.py | Python | mit | 294 |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
'''
sqlite_fill.py -> inserts devices into the database
Copyright 2017 Ron Wellman
'''
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db.sqlite_gen import Base, Device, Config
import json
def load_database(inputfile):
'''... | ronwellman/nbmon | db/sqlite_fill.py | Python | mit | 1,089 |
import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
# Create your models here.
class TodoList(models.Model):
name = models.TextField()
author = models.ForeignKey(User)
create_time = models.DateTimeField(auto_now_add=True)
... | zhy0216/django-todo | todo/models.py | Python | mit | 546 |
# -*- coding: UTF-8 -*-
import setuptools
from distutils.core import setup
# http://stackoverflow.com/a/7071358/735926
import re
VERSIONFILE='wikimd/__init__.py'
verstrline = open(VERSIONFILE, 'rt').read()
VSRE = r'^__version__\s+=\s+[\'"]([^\'"]+)[\'"]'
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.g... | tsalmon/WikiMD | setup.py | Python | mit | 1,260 |
"""A sample custom HTTP server."""
import functools
import html
import traceback
import collect
import server
server.Logger.name = __file__
HTML_TMPL = '''\
<html>
<head>
<link rel="stylesheet" type="text/css" href="/myStyle.css"/>
</head>
<body id="consolas">
%s</body>
</html>
'''
LINK_HOME = '<a href="/">Home<... | cheeseywhiz/cheeseywhiz | socket/app.py | Python | mit | 3,395 |
#!/usr/bin/env python3
import matplotlib
#matplotlib.use("Agg")
import subprocess #import check_output
import operator
from os import mkdir
from shutil import rmtree
from networkit import *
from pylab import *
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
import os.path
import sys, traceback
impor... | emmanuj/ml-sparsifier | generateSparseGraphs.py | Python | mit | 6,757 |
"""
Starts a celery worker for ORES. Note that
Usage:
celery_worker -h | --help
celery_worker [--config=<path>]
Options:
-h --help Prints this documentation
--config=<path> The path to a yaml config file
[default: config/ores-localdev.yaml]
"""
import logging
impor... | aetilley/ores | ores/utilities/celery_worker.py | Python | mit | 753 |
import pyparsing as pp
from mitmproxy.net import http
from mitmproxy.net.http import user_agents, Headers
from . import base, message
"""
Normal HTTP requests:
<method>:<path>:<header>:<body>
e.g.:
GET:/
GET:/:h"foo"="bar"
POST:/:h"foo"="bar":b'content body payload'
Normal... | vhaupert/mitmproxy | pathod/language/http2.py | Python | mit | 7,126 |
#!/usr/bin/python
import os
import sys
import tempfile
import getopt
import re
import socket
import logging
import argparse
import xml.etree.ElementTree as ET
logging.basicConfig(level=logging.DEBUG)
try:
import MySQLdb
except ImportError:
print 'This program requires the python MySQLdb module'
sys.exit(10... | dwighthubbard/mythtv_user_scripts | scripts/cleanvideo.py | Python | mit | 22,022 |
# coding: UTF-8
from unittest import TestCase
from frame import matrix
from numpy import allclose
from math import radians
class MatrixTests(TestCase):
def test_transform_matrix(self):
# Y軸周りに-90度回転
a = matrix.transformMatrix(0, 0, 2.85, 0)
self.assertTrue(allclose((
... | 1stop-st/jsonrpc-calculator | frame/tests/test_matrix.py | Python | mit | 1,922 |
"""
Created by Gotham on 04-08-2018.
"""
from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, Filters
import flood_protection
import sqlite3
import json
import time
import os
from utility import Utility
timeouts = flood_protection.Spam_settings()
BDC, DB, CF = range(12000, 12003)
class AdminH... | Gotham13121997/superCodingBot | handlers/admin.py | Python | mit | 4,007 |
import json
from redlib.api.web import HtmlParser
from six.moves.urllib.parse import urlencode, urlparse, parse_qs
from ..util import log
from ..db.app.query_list import QueryList
from ..util.printer import printer
from .base import SourceError, SourceParams, Source
from .images import Images
from .http_helper import... | amol9/wallp | wallp/source/google.py | Python | mit | 3,624 |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import os
import json
class OnActiveStorePathResolver(object):
def __init__(self,resolver,dependency,resolve_config_path):
self.resolver=resolver
self.dependency=dependency
self.resolve_config... | looopTools/sw9-source | .waf-1.9.8-6657823688b736c1d1a4e2c4e8e198b4/waflib/extras/wurf/on_active_store_path_resolver.py | Python | mit | 796 |
import socket
import ssl
import logging
import datetime
import collections
from typing import Optional
from ..exceptions import SocketError, ListenerError
from ..compat import json
from .listener import BaseListener
logger = logging.getLogger(__name__)
class BetfairStream:
"""Socket holder, connects to betfair ... | liampauling/betfairlightweight | betfairlightweight/streaming/betfairstream.py | Python | mit | 12,065 |
import tensorflow as tf
import numpy as np
import os
import sys
import math
from audio import format_feedval, raw
from layers import conv1d, dilated_conv1d
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Model: neural network model for HeaviNet level
# inputs: init function
# level, integer of corresponding level
# recep... | taylorm7/HeaviNet | models.py | Python | mit | 10,781 |
################################################################################
# Copyright 2020-2021 Advanced Micro Devices, Inc. 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 t... | ROCmSoftwarePlatform/Tensile | Tensile/Utilities/merge.py | Python | mit | 19,651 |
import math
# http://www.ariel.com.au/a/python-point-int-poly.html
def point_in_polygon(point, polygon):
x, y = point['x'], point['z']
n = len(polygon)
inside = False
p1x, p1y = polygon[0]
for i in range(n + 1):
p2x, p2y = polygon[i % n]
if min(p1y, p2y) < y <= max(p1y, ... | vaal-/il2_stats | src/mission_report/helpers.py | Python | mit | 793 |
from django.views.generic.list import ListView
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from dja... | ITURO/ituro | ituro/orders/views.py | Python | mit | 8,516 |
import _plotly_utils.basevalidators
class YpadValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="ypad", parent_name="cone.colorbar", **kwargs):
super(YpadValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
e... | plotly/python-api | packages/python/plotly/plotly/validators/cone/colorbar/_ypad.py | Python | mit | 482 |
"""
This module contains a set of methods that can be used for page loads and
for waiting for elements to appear on a page.
These methods improve on and expand existing WebDriver commands.
Improvements include making WebDriver commands more robust and more reliable
by giving page elements enough time to load before ta... | seleniumbase/SeleniumBase | seleniumbase/fixtures/page_actions.py | Python | mit | 37,037 |
#!/usr/bin/python2.4 -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic string exercises
# D. verbing
# Given a string, if its length is a... | arghasen/Poker | google/basic/string2.py | Python | mit | 2,594 |
#sudo install pip pygal
#this is just Documentation for the code, it will be modified once we figure out how to fetch data as an array
import pygal
data_val = [1, 2, 3, 4] #put data values in array format
camera1 = 'Nixon' #additional info such as Camera in a string
bar_chart = pygal.Bar() #create bar graph
bar... | rayxke/Redshift-Project | flask/pygalgraph.py | Python | mit | 566 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_available_service_aliases_operations.py | Python | mit | 9,072 |
from crypto.hashes.hashinterface import HashInterface
from Crypto.Hash import SHA512 as libsha512
class SHA512(HashInterface):
def hashString(self, stringMessage):
sha512 = libsha512.new()
sha512.update(stringMessage.encode())
return sha512.digest()
def getDigestSize(self):
... | bensoer/pychat | crypto/hashes/sha512.py | Python | mit | 444 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('todos', '0005_auto_20150126_1238'),
]
operations = [
migrations.AlterField(
model_name='todo',
... | Anjali2906/lifetab | todos/migrations/0006_auto_20150126_1500.py | Python | mit | 462 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoTutorial.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure th... | pranavj1001/LearnLanguages | python/DjangoTutorial/manage.py | Python | mit | 812 |
#!/usr/bin/env python
import sys
import re
import shlex
import os
from argparse import ArgumentParser
try:
from Bio import AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_dna
from Bio.Align import MultipleSeqAlignment
except ImportError:
sys.... | zwickl/pygot | scripts/intronExonAlignments.py | Python | mit | 13,381 |
from api.forms import ContextAwareModelForm, HashidModelChoiceField
from django import forms
from django.utils.translation import ugettext_lazy as _
from submissions.models import Submission
from voting.models import Vote
from .fields import VoteValueField
class SendVoteForm(ContextAwareModelForm):
value = VoteV... | patrick91/pycon | backend/api/voting/forms.py | Python | mit | 1,378 |
import os
import sys
import string
from SCons.Script import *
from utils import _make_path_relative
BuildOptions = {}
Projects = []
WD_Root = ''
Env = None
class Win32Spawn:
def spawn(self, sh, escape, cmd, args, env):
import subprocess
newargs = string.join(args[1:], ' ')
cmdline = cmd ... | fwindpeak/lava-emu-c | tools/building.py | Python | mit | 15,516 |
#!/usr/bin/python
# coding: utf-8
class Solution(object):
def findShortestSubArray(self, nums):
left, right, count = {}, {}, {}
for i, x in enumerate(nums):
if x not in left: left[x] = i
right[x] = i
count[x] = count.get(x, 0) + 1
ans = len(nums)
... | Lanceolata/code-problems | python/leetcode_easy/Question_196_Degree_of_an_Array.py | Python | mit | 483 |
from uuid import uuid4
from apollo.choices import STATION_TYPE_CHOICES, STATION_RIG, RENTAL_STATUS_TYPES, RENTAL_DELIVERY_REQUESTED
from django.core.validators import RegexValidator
from django.db import models
class Station(models.Model):
"""
Object model for determining where physical equipment would be del... | awwong1/apollo | applications/station/models.py | Python | mit | 3,350 |
import os
usage = "usage : program LearningMethod Feature PositivePath NegativPath SavePath"
base_learner_path = "../build-Learner-Desktop_Qt_5_5_0_MSVC2013_64bit-Release/release/Learner.exe"
#base_learner_path = "\""+base_learner_path+"\""
learning_method = str(1)
learning_feature = str(0)
positive_... | goddoe/Learner | Learner/LearningTool/Learning.py | Python | mit | 954 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-04-18 20:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lotes', '0015_lote_local'),
]
operations = [
migrations.AlterField(
... | anselmobd/fo2 | src/lotes/migrations/0016_auto_20180418_1740.py | Python | mit | 451 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | jeremiedecock/snippets | python/tkinter/python3/paned_window_horizontal.py | Python | mit | 1,700 |
# Copyright (c) Andrew Helge Cox 2016-2019.
# All rights reserved worldwide.
#
# Parse the vulkan XML specifiction using Python XML APIs to generate
# a file of C++ functions to initialize standard Vulkan API structs.
#
# Usage, from project root:
#
# wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs... | ahcox/krust | tools/scripts/gen_info_struct_wrappers.py | Python | mit | 17,637 |
from elasticsearch import Elasticsearch
from benchmarks.elasticsearch import settings
def clean():
es = Elasticsearch(hosts=settings.storage['elasticsearch']['hosts'])
es.indices.delete([
index
for index in es.indices.status(index='_all')['indices']
if index.startswith(settings.storage['elasticsearch... | Locu/chronology | kronos/benchmarks/elasticsearch/__init__.py | Python | mit | 342 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.opt import Opt
from parlai.utils.misc import Timer, round_sigfigs, set_namedtuple_defaults, nice_report... | facebookresearch/ParlAI | tests/test_utils.py | Python | mit | 9,336 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# utils.py file is part of spman
#
# spman - Slackware package manager
# Home page: https://github.com/MyRequiem/spman
#
# Copyright (c) 2018 Vladimir MyRequiem Astrakhan, Russia
# <mrvladislavovich@gmail.com>
# All rights reserved
# See LICENSE for details.
"""
Utils
... | MyRequiem/spman | src/utils.py | Python | mit | 7,830 |
from seasons.models import Season
def seasons(request):
"""Add available seasons to context."""
available_seasons = Season.objects.all()
return {'available_seasons': available_seasons}
| pawelad/nba-rank | src/seasons/context_processors.py | Python | mit | 200 |
# -*- coding: utf-8 -*-
'''
Created on 9 déc. 2012
@author: Vincent Bruneau, Johann Verbroucht
'''
import unicodedata
from Student import Student
from Teacher import Teacher
class Code(object):
'''
Pour réaliser ces exercices il n'y a pas besoin de modifier les autres
classes, il suffit d'écrire les fonc... | johannv/pythonTestEasy | src/Code.py | Python | mit | 3,960 |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/connected-cell-in-a-grid
import collections
import os
import unittest
from typing import List
DELTAS = [
(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)
]
def check(matrix: List[List[int]], r: int, c: int) -> bool:
return ... | altermarkive/Coding-Interviews | algorithm-design/hackerrank/connected_cell_in_a_grid/connected_cell_in_a_grid.py | Python | mit | 1,719 |
import sys, os
from PyQt5.QtCore import QObject, pyqtSlot, QTimer
from .modules import ModuleInfo
from .modules.api.view_components import ARow, AColumn, ACard
import alfred.modules.api.a_module_globals as amg
class WidgetManager(QObject):
def __init__(self, view_widget):
QObject.__init__(self)
... | Sefrwahed/Alfred | alfred/widget_manager.py | Python | mit | 2,199 |
import random
class DataLoader:
def __init__(self, name):
self.name = name
self._data = []
def add_data(self, data):
self._data.append(data)
def _iter_data(self):
while True:
yield {d.name: next(d) for d in self._data}
def __iter__(self):
return s... | WhatDo/FlowFairy | flowfairy/data/loader.py | Python | mit | 339 |
# coding: utf-8
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
impor... | cliffano/swaggy-jenkins | clients/python-experimental/generated/openapi_client/model/pipeline_branches.py | Python | mit | 1,575 |
"""All blast commands used by aTRAM."""
import sys
import os
from os.path import basename, dirname, join
import re
import glob
import json
from shutil import which
from . import log
from . import util
def create_db(temp_dir, fasta_file, shard):
"""Create a blast database."""
cmd = 'makeblastdb -dbtype nucl -... | AntonelliLab/seqcap_processor | bin/aTRAM-master/lib/blast.py | Python | mit | 8,019 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2021-03-19 10:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('invoices', '0026_invoice_invoice_type'),
]
operations = [
migrations.AlterFi... | samupl/simpleERP | apps/invoices/migrations/0027_auto_20210319_1027.py | Python | mit | 654 |
from bridge.collections.apriori import Apriori
from bridge.collections.indexings import Indexing
import pymongo
class CollectionController:
def __init__(self,db):
self.apriori = Apriori()
self.indexings = Indexing()
self.hashCount = dict() #DB get Hash Count
self.db = db
... | hoonkim/Lesser | bridge/collections/collection_controller.py | Python | mit | 3,353 |
#!/usr/bin/env python
"""
Copyright (c) 2015 Andrew Azarov
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, ... | ServerAstra/gnt-ext-backup | gnt_ext_backup.py | Python | mit | 13,148 |
import array
import copy
#@TODO änderungen nur bei wirklichen änderungen (bessere Performance)
class memory:
def __init__(self, size):
self.size = size
#erzeugt liste mit size elementen
mem_tmp = [0] * size
#kopiert die liste in ein python array für bessere Performance
self.m... | schroeder-/pyssps | src/memory.py | Python | mit | 1,015 |
import contextlib
from six import StringIO
from ExtractMsg import Message
from fulltext.util import BaseBackend
class Backend(BaseBackend):
def handle_path(self, path):
text = StringIO()
with contextlib.closing(Message(path)) as m:
text.write(m.subject)
text.write(u'\n\n'... | btimby/fulltext | fulltext/backends/__msg.py | Python | mit | 384 |
from django.conf.urls.defaults import patterns, url
from webdnd.player.views.account import UserSearchApi
urlpatterns = patterns('webdnd.player.views',
# Account
url(r'^account/search/(?P<text>.*)/?$', UserSearchApi.as_view(), name="account_api_search"),
)
| Saevon/webdnd | player/urls/api.py | Python | mit | 267 |
# main.py
# Scott M. Phillips
# 31 December 2015
import sys
import argparse
from directoryconversiongui import directoryconversiongui
from propresenterconverter import propresenterconverter
def parsecommandline():
parser = argparse.ArgumentParser(
description='Convert Propresenter6 files from single to tr... | fundthmcalculus/propresenter-conversion | main.py | Python | mit | 1,289 |
from __future__ import unicode_literals
import json
import os
import mock
from django.contrib import admin
from django.contrib.admin.utils import quote
from django.contrib.auth import get_permission_codename
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import Conten... | chenesan/django-disqus-backstore | disqus_backstore/tests.py | Python | mit | 23,738 |
#http://doc.aldebaran.com/2-5/naoqi/peopleperception/alfacedetection.html
import os
import qi
import argparse
import sys
import time
import threading
def onDetection(value):
#
# print "onDetection ::value=",value
if(len(value) > 0):
detectionTimestamp=value[0]
cameraPose_InTorsoFra... | LCAS/spqrel_tools | face_detection/face_detection.py | Python | mit | 3,260 |
# -*- coding: utf-8
from __future__ import absolute_import
import unittest
from oaxmlapi import datatypes
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
class TestDatatypesClass(unittest.TestCase):
def test_str(self):
self.assertEqual(
... | 23maverick23/oaxmlapi | tests/datatypes/test_datatypes.py | Python | mit | 2,369 |
__author__ = 'novokonst'
import ply.lex as lex
def check_comment(fn):
def wrapped(self, t):
if self.nested_comment:
t.type = 'COMMENT'
return t
else:
return fn(self, t)
wrapped.__doc__ = fn.__doc__
return wrapped
class DummyLexer:
"""
Need to ... | sayon/ignoreme | tokenizers/general/dummylex.py | Python | mit | 1,584 |
from .spacynlp import string_id
SUBJECT = string_id('nsubj')
SUBJECTPASS = string_id('nsubjpass')
CLAUSAL_SUBJECT = string_id('csubj')
ATTRIBUTE = string_id('attr')
RELCL = string_id('relcl')
ADJMOD = string_id('amod')
NPADVMOD = string_id('npadvmod')
NOUNMOD = string_id('nmod')
NUMMOD = string_id('nummod')
COMPOUND =... | infolab-csail/whoami | whoami/spacydep.py | Python | mit | 1,590 |
class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
if m > n:
m, n = n, m
low = 1
high = m * n
while low < high:
mid = (low + high) // 2
count = 0
for i in range(1, m + 1):
count += min(mid // i, n)
... | jiadaizhao/LeetCode | 0601-0700/0668-Kth Smallest Number in Multiplication Table/0668-Kth Smallest Number in Multiplication Table.py | Python | mit | 439 |
from django.contrib import admin
# Register your models here.
from models import *
class LogAdmin(admin.ModelAdmin):
list_display = ('id', 'date', 'ttype', 'message', 'user')
list_filter = ('ttype',)
class CityAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'name_gde', 'slug', 'timediffk', 'wunder... | norn/bustime | bustime/admin.py | Python | mit | 2,399 |
__author__ = 'lewuathe'
import numpy as np
import hashlib
import common
def __calc_with_hash(vec, m, target):
for v in vec:
m.update(v)
if target == 'hex':
return m.hexdigest()
else:
return common.hex2dec(m.hexdigest())
def md5_for_vec(vec, target = 'dec'):
"""
Calculate h... | PhysicsEngine/kHLL | kHLL/hash/image.py | Python | mit | 1,542 |
import os
username = os.environ['ttiUsername']
password = os.environ['ttiPassword']
from pandac.PandaModules import *
accountServerEndpoint = ConfigVariableString('account-server-endpoint', 'https://toontowninfinite.net/api/').getValue()
http = HTTPClient()
http.setVerifySsl(0)
def executeHttpRequest(url, mess... | ToonTownInfiniteRepo/ToontownInfinite | toontown/toonbase/ToontownStartRemote.py | Python | mit | 967 |
from pprint import pprint
def _compute_coefs(la, nu_avg, N):
coefs = []
addings = [1]
for x in xrange(1, N+1):
coefs.append(nu_avg[-x]/(x * la))
addings.append(coefs[-1] * addings[-1])
return coefs, addings
def solve(la, nu_avg, N):
"""
:param la: lambda
:type la: floa... | tech-team/OpResearch | model1_right.py | Python | mit | 800 |
"""link plate with analysis
Revision ID: 21ef5ce15822
Revises: 88fa93c68dab
Create Date: 2016-12-05 15:12:49.067536
"""
# revision identifiers, used by Alembic.
revision = "21ef5ce15822"
down_revision = "88fa93c68dab"
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrad... | Clinical-Genomics/taboo | alembic/versions/21ef5ce15822_link_plate_with_analysis.py | Python | mit | 799 |
import time
import numpy as np
import keras
import tensorflow as tf
import keras.backend as K
from keras import optimizers
from keras.models import load_model
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, Callback
from keras.models import Model
from keras.layers.recurrent import LSTM, GRU
from kera... | DimiterM/santander | RecurrentModel.py | Python | mit | 8,420 |
"""
Homework 3
Data Description:
Input the training and testing data and store it in an array. Training results in 284x31
and Testing results in 284x31. The data entries
consist of a first entry class label('1' for malignant and '-1' for benign) followed by 30
breast cancer diagnostic measurements.
""... | andychase/classwork | machine_learning/hmw3/HW3.py | Python | mit | 4,807 |
import os
import platform
import unittest
import pytest
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestClient, GenConanfile
class RMdirFailTest(unittest.TestCase):
@pytest.mark.skipif(platform.system() != "Windows", reason="needs windows")
def test_fail_rmdir(self):... | conan-io/conan | conans/test/integration/cache/rmdir_fail_test.py | Python | mit | 948 |
"""Example isosurface visualiser.
press 't' to toggle isosurface on and off
"""
import sys
import logging
import types
from renderer import BaseGlutWindow, IsosurfaceVolumeRenderer
from parser.tiff_parser import open_tiff
class ExampleIsosurfaceVisualiser(BaseGlutWindow):
def load_image(self, fpath, spacing):... | jfozard/pyvol | pyvol/example_isosurface_visualiser.py | Python | mit | 1,241 |
#!/usr/bin/env python3
import numpy as np
from numpy.core.umath_tests import matrix_multiply as _matrix_multiply
# TODO: Write unit tests for all of these helper functions.
def SphPosToCart(vectors, radians=False):
"""Convert a spherical position vector into Cartesian position.
Arguments:
vector -- A... | fourwood/OutflowCone | Helpers.py | Python | mit | 13,229 |
"""Python API for talking to Bondora.com.
Bondora API Docs:
https://api.bondora.com/Intro
"""
import sys
import requests
import bondoraapi.account
import json
import logging
import datetime
import time
class Api(object):
def __init__(self, storage):
self.bondora_base_url = "https://api.bondora.com"
... | fxlv/bondora | bondoraapi/api.py | Python | mit | 4,882 |
from __future__ import division, print_function, absolute_import
import pkg_resources
from turgles.geometry import SHAPES
from turgles.gl.api import (
GL_STATIC_DRAW,
GL_TRIANGLES,
GLfloat,
glGetAttribLocation,
glDrawArrays,
)
from turgles.renderer import Renderer
from turgles.gl.buffer import Ve... | AllTheWayDown/turgles | turgles/es_renderer.py | Python | mit | 3,423 |
dia,mes,ano =input("data: ").split('/')
ms = '''Janeiro Fevereiro Março Abril Maio Junho Julho Agosto Setembro Outubro Novembro Dezembro'''.split()
print('Você nasceu em %s de %s de %s' % (dia, ms[int(mes)-1], ano))
| andersonsilvade/python_C | Python32/aulas/data.py | Python | mit | 219 |
"""
Modules to Set default parameters:
W.T. Franks FMP Berlin
"""
import de.bruker.nmr.mfw.root as root
import math
#import os
import sys
import TopCmds
import IntShape
import CPDtools
ret=u"\u000D"
spc=u"\u0020"
def name_confirm():
adbname=pul.GetPar('sCadb',"")
if adbname == "gauss" : adbname = "TanhTan"
... | TrentFranks/ssNMR-Topspin-Python | modules/TOBSY.py | Python | mit | 2,225 |
#!/usr/bin/python
import urllib
def main():
# url = 'https://screener.finance.yahoo.com/stocks.html'
url = 'https://screener.finance.yahoo.com/b?sc=&im=&prmin=0&prmax=&mcmin=&mcmax=&dvymin=0&dvymax=&betamin=&betamax=&remin=&remax=&pmmin=&pmmax=&pemin=&pemax=&pbmin=&pbmax=&psmin=&psmax=&pegmin=&pegmax=&gr=&grf... | jtraver/dev | python/urllib/urllib1.py | Python | mit | 411 |
import os
import numpy
import meshplex
from pynosh import magnetic_vector_potentials as mvp
def _run(filename, control_values):
"""Test $\int_{\Omega} A^2$."""
# read the mesh
mesh, _, _, _ = meshplex.read(filename)
if mesh.control_volumes is None:
mesh.compute_control_volumes()
tol = 1... | nschloe/pynosh | test/test_mvp.py | Python | mit | 2,871 |
#!/usr/bin/python3
"""
Copyright (c) 2018 Bill Peterson
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, pu... | albedozero/squishbox | squishbox.py | Python | mit | 18,383 |
from __future__ import (division, print_function)
from pomegranate import *
from nose.tools import with_setup
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools import assert_raises
from nose.tools import assert_almost_equal
import random
import numpy as np
import json
def se... | jmschrei/pomegranate | tests/test_profile_hmm.py | Python | mit | 17,863 |