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 |
|---|---|---|---|---|---|
from src import ma, BaseSchema
from .models import User, Role, Permission, UserRole, PosOutlet, Partner, Address, CommissionSlab
class UserSchema(BaseSchema):
class Meta:
model = User
exclude = ('created_on', 'updated_on', 'password', 'current_login_at', 'current_login_ip',
'la... | saurabh1e/SuperFlaskSeed | web/src/user/schemas.py | Python | mit | 1,666 |
from interface import interface
import inspect
#===========================================================
@interface
class IAnnotationRegistry(object):
def add(self, clazz, ann):
"""Associates annotation with specified class"""
def getByClass(self, clazz):
"""Returns all associated annotat... | mikhtonyuk/pyhk2 | hk2/types/annotations.py | Python | mit | 1,964 |
from config import influx_settings
from influx.measurement_strings import *
from influx.datapoint_utils import *
from measurement_type import MeasurementType
from influxdb import InfluxDBClient
from logging import getLogger
logger = getLogger(__name__)
username = influx_settings['username']
password = influx_settings[... | OzuYatamutsu/klima | influx/influx_adapter.py | Python | mit | 4,197 |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
lookup = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz... | Jan-zou/LeetCode | python/String/17_letter_combinations_of_a_phone_number.py | Python | mit | 1,935 |
# Relevant specifications:
# [RFC 1945]: https://www.ietf.org/rfc/rfc1945.txt
# "Hypertext Transfer Protocol -- HTTP/1.0"
# [RFC 2616]: https://www.ietf.org/rfc/rfc2616.txt
# "RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1"
# [RFC 2145]: https://www.ietf.org/rfc/rfc2145.txt
# "RFC 2145: Use and Interpret... | abusesa/idiokit | idiokit/http/server.py | Python | mit | 25,079 |
"""Copied from https://www.kaggle.com/robertkag/metric-script"""
import numpy as np
import scipy.stats
def calc_enptropy(probs, base=2):
_, counts = np.unique(probs, return_counts=True)
return scipy.stats.entropy(counts, base=base)
def calc_iou(actual, pred):
intersection = np.count_nonzero(actual * pr... | gtesei/fast-furious | competitions/tgs-salt-identification-challenge/solutions/9_place/utils/metrics.py | Python | mit | 1,758 |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import calendar
from frappe import _
from frappe.desk.form import assign_to
from frappe.utils.jinja import validate_templa... | ESS-LLP/frappe | frappe/desk/doctype/auto_repeat/auto_repeat.py | Python | mit | 13,408 |
# pylama:ignore=E501
import os
import re
import shutil
import tempfile
import itertools
import logging
import tabula
import requests
from fuzzywuzzy import fuzz
from datapackage_pipelines.wrapper import ingest, spew
parameters, dp, res_iter = ingest()
headers = parameters['headers']
HEADER_SEARCH_ROWS = 10
SCORE_... | okfn/datapackage_pipelines_od4tj | datapackage_pipelines_od4tj/processors/tabula_resource.py | Python | mit | 4,222 |
from django import forms
from etc.entities import create_handle
from entity_items.models import ContentItem
from org.models import Org, OrgIssueRelationship
from issue.models import Issue
from users.models import Location
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.core.exceptions import... | jumoconnect/openjumo | jumodjango/org/forms.py | Python | mit | 6,280 |
# coding: utf-8
import json
import hmac
import hashlib
import base64
def generate_signature(secret_key, serializable_data):
string = json.dumps(serializable_data)
sha256hash = hmac.new(secret_key, string, digestmod=hashlib.sha256).digest()
signature = base64.urlsafe_b64encode(sha256hash)
return signat... | paulocheque/python-django-bootstrap | utils/security.py | Python | mit | 324 |
# BIG BANG - STUDENT
# Import modules
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import RPi.GPIO as GPIO
####import pygame
import time
# GPIO pins on breadboard
BUTTON = 4
LED = 15
# Setup
mc = minecraft.Minecraft.create()
GPIO.setmode(GPIO.BCM) # use broadcom GPIO numbers
GPIO.set... | whaleygeek/mc_bigbang | sensors.py | Python | mit | 1,141 |
from __future__ import annotations
import contextlib
import logging
from typing import Generator
from pre_commit import color
from pre_commit import output
logger = logging.getLogger('pre_commit')
LOG_LEVEL_COLORS = {
'DEBUG': '',
'INFO': '',
'WARNING': color.YELLOW,
'ERROR': color.RED,
}
class Lo... | pre-commit/pre-commit | pre_commit/logging_handler.py | Python | mit | 1,022 |
from sklearn.naive_bayes import GaussianNB
import numpy as np
x = np.array([
[1, 2],
[3, 4],
[8, 7],
[9, 10],
[11, 13]
])
y = np.array([1, 2, 1, 2, 1])
model = GaussianNB()
model.fit(x, y)
predicted = model.predict([
[1, 2],
[1, 12]
])
print(predicted)
| matija94/show-me-the-code | ml/module_ml/naive_bayes.py | Python | mit | 287 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-04 15:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cliente', '0001_initial'),
]
operations = [
... | exildev/AutoLavadox | cliente/migrations/0002_auto_20161004_1057.py | Python | mit | 842 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import re
import shutil
from datetime import date
from subprocess import check_call
datestamp = date.today().strftime("%m%d")
TMPDIR = "fore" + datestamp
outfn = TMPDIR+".tar"
tex = open("ms.tex", "r").read()
try:... | dfm/peerless | document/publish.py | Python | mit | 1,374 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
class HECUVDDistConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HECUVDDistConnectedLHS.
"""
# Flag this instance as compiled now
self... | levilucio/SyVOLT | GM2AUTOSAR_MM/Properties/positive/Himesis/HECUVDDistConnectedLHS.py | Python | mit | 14,137 |
__author__ = 'peter'
def populate(model,value,modified):
model.controller = {'value': value, 'modified': modified} | PeterDowdy/py-eu4-editor | province-editor/rules/controller.py | Python | mit | 119 |
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager,Screen, FadeTransition
# IMPORTANDO MODULOS
from configurador import Guardar_datos
class Principal(ScreenManager):
#Acceder a los atributos del Textinput
nombre=ObjectProperty()
cedula=ObjectProper... | eliecer11/Uip-prog3 | Parciales/Parcial1/Aplicacion.py | Python | mit | 1,797 |
import zmq
import numpy as np
from online_monitor.utils import utils
from online_monitor.converter.transceiver import Transceiver
class ExampleConverter(Transceiver):
def deserialize_data(self, data):
return zmq.utils.jsonapi.loads(data, object_hook=utils.json_numpy_obj_hook)
def interpret_data(sel... | SiLab-Bonn/online_monitor | online_monitor/examples/converter/example_converter.py | Python | mit | 919 |
#!/usr/bin/env python3
import sys
import billboard
from jwp.jwmultithreaded import *
from jwp.jwcache import *
from datetime import date, timedelta
cache = {}
def get_thing(chart, d):
if chart in cache:
if d in cache[chart]:
print(chart, d, 'retrieved from cache')
return {}
pr... | jameswenzel/billboard-grabber | script.py | Python | mit | 969 |
# -*- coding: utf-8 -*-
import scipy.stats
"""
Parameters:
x : integer or array_like
the number of successes, or if x has length 2, it is the number of successes and the number of failures.
n : integer
the number of trials. This is ignored if x gives both the number of successes and failures
p : float, opti... | GreenGear5/planet-wars | test.py | Python | mit | 1,186 |
#!/usr/bin/env python
"""
oa
Objective analysis. This function will interpolate data using the
fortran routines written by Emanuelle Di Lorenzo and Bruce Cornuelle
Written by Brian Powell on 10/08/13
Copyright (c)2017 University of Hawaii under the BSD-License.
"""
import numpy as np
import seapy.oalib
_... | dalepartridge/seapy | oa.py | Python | mit | 4,466 |
import unittest
import numpy
from chainer.backends import cuda
from chainer import distributions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 2), (1,)],
'is_variable': [True, False],
'sample_shape':... | tkerola/chainer | tests/chainer_tests/distributions_tests/test_bernoulli.py | Python | mit | 5,265 |
# This weechat plugin pipes the current weechat buffer through urlview
#
# Usage:
# /urlview
#
# History:
# 10-04-2015
# Version 1.0.0: initial release
# Version 1.0.1: reverse text passed to urlview
# Version 1.0.2: remove weechat color from messages
import distutils.spawn
import os
import pipes
import weechat
def ... | keith/urlview-weechat | urlview.py | Python | mit | 1,654 |
import urllib.request
import sys
from typing import Tuple
# Take cupy_backends/stub/cupy_cusparse.h and generate
# cupy_backends/hip/cupy_hipsparse.h, with all return values replaced by an
# error if not supprted. This script mainly focuses on getting the CUDA ->
# HIP API mapping done correctly; structs, enums, etc,... | cupy/cupy | cupyx/tools/_hipsparse_stub_mapper.py | Python | mit | 14,422 |
from datetime import datetime
import time
import calendar
#-------------------------------------------------
# conversions to strings
#-------------------------------------------------
# datetime object to string
dt_obj = datetime(2008, 11, 10, 17, 53, 59)
date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print(date_str... | tranhuucuong91/coclib | coclib/standardize/ze_timeconvert.py | Python | mit | 2,824 |
import numpy as np
class Scaling:
# This function scales input in a robust way. The input parameters define the target value of a certain magnitude percentile and define whether the data should also be centered before scaling.
# By default, the data is not centered and is scaled so that the 67th percentile is... | clemenshage/grslra | grslra/scaling.py | Python | mit | 3,329 |
"""Utilities for converting formats used in wepy to mdtraj objects.
Requires mdtraj be installed.
"""
import json
from warnings import warn
import operator
import numpy as np
import mdtraj as mdj
import mdtraj.core.element as elem
from wepy.util.util import traj_box_vectors_to_lengths_angles
# the following meth... | ADicksonLab/wepy | src/wepy/util/mdtraj.py | Python | mit | 9,910 |
from datetime import datetime
import pytz
from django.test import SimpleTestCase
from django.utils.encoding import force_str
from sundial import zones
class TimezoneChoicesTests(SimpleTestCase):
def test_label_offset(self):
for value, label in zones.ALL_CHOICES:
offset = datetime.now(pytz.ti... | charettes/django-sundial | tests/test_zones.py | Python | mit | 1,547 |
"""
postagent - Handles POSTing file requests to other users
"""
from twisted.internet import defer, reactor
from twisted.python import log
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.web.iweb import IBodyProducer
from zope.interface import implements
JSONHEADERS = ... | derwolfe/teiler | teiler/postagent.py | Python | mit | 1,497 |
import os,sys
import iris
import iris.unit as unit
from iris.coord_categorisation import add_categorised_coord
import iris.analysis.geometry
from shapely.geometry import Polygon
import datetime
import numpy as np
import pdb
#Monsoon Trough
polygon = Polygon(((73., 21.), (83., 16.), (87., 22.), (75., 27.)))
#e... | peterwilletts24/Monsoon-Python-Scripts | rain/Rain_Rate_PDF_Polygon.py | Python | mit | 3,843 |
"""
@file
@brief Change Jupyter configuration
"""
import sys
import os
import re
from ..installhelper.link_shortcuts import add_shortcut_to_desktop, suffix
def noLOG(*args, **kwargs):
pass
def install_mathjax():
"""
install a local copy of mathjax
"""
from IPython.external import mathjax # pyl... | sdpython/pymyinstall | src/pymyinstall/setuphelper/ipython_helper.py | Python | mit | 6,598 |
import fix_paths
import common
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship, backref
class Hunk(common.Base):
__tablename__ = 'hunks'
id = Column(Integer, primary_key=True)
lines_added = Column(Integer)
lines_removed = Column(Integer)
file_diff_id = Co... | mglidden/git-analysis | models/hunk.py | Python | mit | 667 |
#coding: utf-8
# Copyright (c) 2015-2016, thumbor-community
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
from tornado.concurrent import return_future
from thumbor.storages import BaseStorage
from ..aws.storage import AwsStorage
class Storage(AwsStorage, BaseStor... | thumbor-community/aws | tc_aws/storages/s3_storage.py | Python | mit | 2,194 |
import functools
import numpy as np
import pytest
import tensorflow as tf
from mock import mock, Mock
from tfsnippet import DiscretizedLogistic
def safe_sigmoid(x):
return np.where(x < 0, np.exp(x) / (1. + np.exp(x)), 1. / (1. + np.exp(-x)))
def discretize(x, bin_size, min_val=None, max_val=None):
if min_... | korepwx/tfsnippet | tests/distributions/test_discretized.py | Python | mit | 14,601 |
"""Relay domain related models."""
from django.contrib.contenttypes import generic
from django.db import models
from django.db.models.manager import Manager
from django.utils.translation import ugettext as _, ugettext_lazy
import reversion
from modoboa.core.models import ObjectAccess
from modoboa.lib import paramete... | disko/modoboa-admin-relaydomains | modoboa_admin_relaydomains/models.py | Python | mit | 6,583 |
import os
import numpy as np
from keras import callbacks
from keras.models import Sequential, load_model
from keras.layers import Dense
from keras.layers import Dropout
from keras.constraints import maxnorm
from keras.optimizers import SGD
from sklearn.cross_validation import (StratifiedShuffleSplit, StratifiedKFold)
f... | ipashchenko/ml4vs | ml4vs/nn_fine.py | Python | mit | 4,588 |
"""
:author: Aidan Sawyer
:date: 2016-11-28
:name: Main
:description: ingest, parse, edit, export csv
"""
# import csv, sys, and beer libraries
import csv, sys
import styles
from beer import Beer, getHeader
# list of beers
lsBeers = []
# metrics used in filters and normalizations
max_ibu = 99999 # practically infi... | atla5/data-mining-project | src/main.py | Python | mit | 4,986 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
Very simple script to replace a template with another one.
It also converts the old MediaWiki boilerplate format to the new format.
Syntax:
python pwb.py template [-remove] [xml[:filename]] oldTemplate \
[newTemplate]
Specify the template on the command lin... | PersianWikipedia/pywikibot-core | scripts/template.py | Python | mit | 14,800 |
'''
Created on 21 Jun 2015
@author: @alexparsons
We have a shortage of housing, not bad housing ideas. Yet it is easier to train a robot to make these.
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
import random
import twitter
import credentials
from robot_core import Robot
random.seed()... | inkleby/inklebyrobots | robots/badhousingideas.py | Python | mit | 10,818 |
import pyven.constants
from pyven.exceptions.repository_exception import RepositoryException
from pyven.steps.step import Step
from pyven.checkers.checker import Checker
from pyven.logging.logger import Logger
from pyven.reporting.content.step import StepListing
class Deploy(Step):
def __init__(self, verbose, re... | mgaborit/pyven | source/pyven/steps/deploy.py | Python | mit | 2,667 |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | onshape-public/onshape-clients | python/onshape_client/oas/models/bt_version_or_workspace_params.py | Python | mit | 6,201 |
aws_region = "eu-west-1"
| Vilsepi/aws-udidwut | settings.py | Python | mit | 25 |
'''An opengl demo for PyQt5
test on Windows with Python3.6
'''
import array
from PyQt5 import QtGui
vertexShaderCode = '''#version 410
layout(location=0) in vec4 position;
layout(location=1) in vec4 color;
out vec4 theColor;
void main()
{
gl_Position = position;
theColor = color;
} ... | mackst/opengl-samples | triangle_PyQt5.py | Python | mit | 3,444 |
import numpy as np
import pytest
import pytoolkit as tk
def test_data_loader():
dataset = tk.data.Dataset(data=np.arange(3), labels=np.arange(4, 7))
data_loader = tk.data.DataLoader(batch_size=2, data_per_sample=1)
ds, steps = data_loader.get_ds(dataset, shuffle=False)
assert steps == 2
g = iter(... | ak110/pytoolkit | pytoolkit/data_test.py | Python | mit | 2,643 |
# -*- encoding:utf8 -*-
import time
#timeライブラリ
from akilib import AKI_I2C_LIS3DH
#akilibのAKI_I2C_LIS3DHを使用する事を宣言
LIS3DH = AKI_I2C_LIS3DH(1)
#AKI_I2C_LIS3DをI2C_1で使用する事を宣言
time.sleep(0.01)
LIS3DH.WhoAmI()
LIS3DH.Init()
#LIS3D特有の初期化処理を行います。
while 1:
xg = LIS3DH.X()
#X軸の加速度を取得
yg = LIS3DH.Y()
#Y軸の加速度を取得
... | nonNoise/Edison-MasterBook | source/3-03/I2C_LIS3DH.py | Python | mit | 593 |
# coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import si... | Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api_v3/models/qualifications_v30_rc1.py | Python | mit | 5,308 |
import os
from os.path import join, splitext, isfile, isdir
from turing.compiler.main import main, compile_source
def turingc_cmd(*args):
main(["main.py", '-d'] + list(args))
def turingc(source):
compile_source(source, os.devnull, debug=True)
def assert_turingc_ok(source):
try:
turingc(sour... | myaskevich/turing | turing/test/test_compiler.py | Python | mit | 1,947 |
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
table = [0] * 1001
for a in arr1:
table[a] += 1
result = [0] * len(arr1)
i = 0
for a in arr2:
while table[a] > 0:
result[i] = a
... | jiadaizhao/LeetCode | 1101-1200/1122-Relative Sort Array/1122-Relative Sort Array.py | Python | mit | 527 |
# -*- coding: utf-8 -*-
from seleniumbase import BaseCase
class AppleTests(BaseCase):
def test_apple_developer_site_webdriver_instructions(self):
self.demo_mode = True
self.demo_sleep = 0.5
self.message_duration = 2.0
if self.headless and (
self.browser == "chrome" or s... | seleniumbase/SeleniumBase | examples/test_apple_site.py | Python | mit | 1,368 |
from datetime import datetime
from datetime import timedelta
def add_gigasecond(time):
futuretime = time + timedelta(seconds=10**9)
return futuretime
| developerQuinnZ/this_will_work | student-work/quinn_zepeda/exercism/python/gigasecond/gigasecond.py | Python | mit | 159 |
#!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cPickle as pickle
import cv2
import fnmatch
import math
import numpy as np
import os.path
from progress.bar import Bar
import scipy.spatial
sys.path.append('../lib')
import ... | UASLab/ImageAnalysis | scripts/archive/4z-collapse-matches.py | Python | mit | 3,762 |
import deepchem.models.optimizers as optimizers
import tensorflow as tf
from tensorflow.python.framework import test_util
class TestLayers(test_util.TensorFlowTestCase):
"""Test optimizers and related classes."""
def test_adam(self):
"""Test creating an Adam optimizer."""
opt = optimizers.Adam(learning_r... | miaecle/deepchem | deepchem/models/tests/test_optimizers.py | Python | mit | 2,258 |
# 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/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2021_09_01/operations/_operations.py | Python | mit | 5,396 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 19:53:40 2017
@author: juan9
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import pickle
import xgboost as xgb
from math import radians, cos, sin, asin, sqrt
import datetime as dt
import json
# Input dat... | pyrdr/charlas | model_deployment/trip-duration/MLDemo/data/Script.py | Python | mit | 7,620 |
from components import featureBroker
from commands import *
import sys
import time
from components.daemon import Daemon
import os
import json
import logging.config
from ConfigParser import SafeConfigParser
from flask import Flask
from controllers import *
import app
from schedules import *
import schedules
from flask_... | JaronrH/RF | RF/app/application.py | Python | mit | 3,690 |
# -*- coding: utf-8 -*-
# python std lib
from __future__ import with_statement
import asyncio
import uuid
# rediscluster imports
from tests.cluster.conftest import skip_if_server_version_lt
from aredis import StrictRedis, StrictRedisCluster, RedisClusterException, ConnectionError
from aredis.nodemanager import NodeMa... | NoneGG/aredis | tests/cluster/test_node_manager.py | Python | mit | 15,107 |
"""
A web interface built on Flask and the Cisco UCS Python SDK that has the
following basic functionality:
- Connect to a UCSM domain
- View and Add VLANs
- Add a VLAN to a vNIC
The web UI currently has little to none error handling in place so proceed
accordingly.
"""
from flask import Flask, render_template, req... | drew-russell/Cisco-UCS-VLAN-Management | cisco_ucs_vlan_web_interface.py | Python | mit | 9,344 |
import numpy as np
from gym.spaces import Box
from metaworld.envs.asset_path_utils import full_v1_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerPegInsertionSideEnv(SawyerXYZEnv):
def __init__(self):
liftThresh = 0.11
hand_init... | rlworkgroup/metaworld | metaworld/envs/mujoco/sawyer_xyz/v1/sawyer_peg_insertion_side.py | Python | mit | 6,516 |
from __future__ import absolute_import
import os
import platform
import sys
from dataclasses import dataclass, field
from traceback import walk_tb
from types import ModuleType, TracebackType
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Type, Union
from pygments.lexers import guess_lexer... | willmcgugan/rich | rich/traceback.py | Python | mit | 25,871 |
from builtins import object
from math import *
from proteus import *
from proteus.default_p import *
from cylinder import *
from proteus.mprans import PresInit
#domain = ctx.domain
#nd = ctx.nd
name = "pressureInitial"
coefficients=PresInit.Coefficients(nd=nd,
modelIndex=PINIT_model... | erdc/proteus | proteus/tests/cylinder2D/sbm_3Dmesh/pressureInitial_p.py | Python | mit | 1,403 |
from django.shortcuts import render
# Create your views here.
# VR: Creating a basic index page
from django.http import HttpResponse
def registration(request):
return render(request, 'registration.html')
def loginpage(request):
return render(request, 'login.html')
def index(request):
return render(reque... | empowerhack/RecordOnTheGo | prototype_app/views.py | Python | mit | 378 |
# 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 ... | lmazuel/azure-sdk-for-python | azure-mgmt-sql/azure/mgmt/sql/operations/server_automatic_tuning_operations.py | Python | mit | 8,116 |
# -*- coding:utf-8 -*-
import random
import time
from owlmixin import OwlMixin
from jumeaux.addons.did_challenge import DidChallengeExecutor
from jumeaux.models import DidChallengeAddOnPayload, DidChallengeAddOnReference
from jumeaux.logger import Logger
logger: Logger = Logger(__name__)
class Config(OwlMixin):
... | tadashi-aikawa/gemini | jumeaux/addons/did_challenge/sleep.py | Python | mit | 781 |
import json
import random
import pytest
from google.appengine.ext import ndb
from backend.common.consts.alliance_color import AllianceColor
from backend.common.consts.comp_level import CompLevel
from backend.common.consts.event_type import EventType
from backend.common.consts.playoff_type import DoubleElimBracket
fro... | the-blue-alliance/the-blue-alliance | src/backend/common/helpers/tests/match_helper_test.py | Python | mit | 6,976 |
# You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list.
#
# Extra credit if you solve it in one line. You can asume there is never an empty list/array and there will always be an integer.
#
#... | SELO77/seloPython | 3.X/coding_test/6/Sum_consecutives.py | Python | mit | 848 |
from selfdrive.car import dbc_dict
class CAR:
FUSION = "FORD FUSION 2018"
FINGERPRINTS = {
CAR.FUSION: [{
71: 8, 74: 8, 75: 8, 76: 8, 90: 8, 92: 8, 93: 8, 118: 8, 119: 8, 120: 8, 125: 8, 129: 8, 130: 8, 131: 8, 132: 8, 133: 8, 145: 8, 146: 8, 357: 8, 359: 8, 360: 8, 361: 8, 376: 8, 390: 8, 391: 8, 392: 8, 394... | TheMutley/openpilot | selfdrive/car/ford/values.py | Python | mit | 821 |
from __future__ import print_function
import os
import time
import json
import pickle
import sys
from itertools import product, combinations
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from ruzicka.util... | mikekestemont/ruzicka | code/04latin_test_o2.py | Python | mit | 3,340 |
import threading
def upgradeHero(device, x, y):
device.touch(x, y, 'DOWN_AND_UP') # Trying to "level up" our hero
threading.Timer(10, upgradeHero, [device, x, y]).start() # every 10 second
| itatriev/tapbot | upgradeHero.py | Python | mit | 199 |
from il_elex_scraper import IllinoisElectionScraper
class OfficerScraper(IllinoisElectionScraper):
def scrape_one(self, comm_id):
url = self.url_pattern % comm_id
print url
officer_page = self._lxmlize(url)
rows = officer_page.xpath('//tr[starts-with(@class, "SearchListTableRow... | influence-usa/campaign-finance_state_IL | manual_scrapers/officer_scraper.py | Python | mit | 2,461 |
##################################################################
# Copyright 2016 OSGeo Foundation, #
# represented by PyWPS Project Steering Committee, #
# licensed under MIT, Please consult LICENSE.txt for details #
####################################################... | ldesousa/PyWPS | pywps/inout/outputs.py | Python | mit | 11,370 |
# 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/v2018_07_01/operations/_available_endpoint_services_operations.py | Python | mit | 5,396 |
# -*- coding: utf-8 -*-
#
# dectools documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 4 16:11:14 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | merriam/dectools | docs/sphinx/conf.py | Python | mit | 6,504 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
import numpy as np
pub = rospy.Publisher('/mobile_base/commands/velocity', Twist, queue_size=10)
def sc_callback(robot_sc):
scan_ranges = robot_s... | rafafigueroa/amrws | src/amrpkg/scripts/scan_control.py | Python | mit | 823 |
# coding: utf-8
from __future__ import print_function
import json
from os import path, _exit
from time import sleep
from flask import Flask, Response, send_file
def run_server(viewer):
resources = path.join(path.dirname(path.realpath(__file__)),
'web_viewer_resources')
app = Flask... | simpleai-team/simpleai | simpleai/search/web_viewer_server.py | Python | mit | 2,357 |
"""Softmax."""
scores = [3.0, 1.0, 0.2]
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return (np.exp(x) / np.sum(np.exp(x), axis=0))
print(softmax(scores))
# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack(... | Blitzman/udacity-730 | l1/softmax.py | Python | mit | 449 |
#!/usr/bin/env python2
#
# Copyright (c) Michael Tharp <gxti@partiallystapled.com>
#
# This file is distributed under the terms of the MIT License.
# See the LICENSE file at the top of this tree, or if it is missing a copy can
# be found at http://opensource.org/licenses/MIT
#
import os
import re
import subprocess
im... | mtharp/laureline-firmware | util/resize_ld.py | Python | mit | 3,819 |
def true():
return true | bigmassa/soup_helpers | build/lib/soup_helpers/objects.py | Python | mit | 27 |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 10:44:53 2017
@author: sebastian
"""
## retrieve ECMWF forecast data, based on example from
## https://software.ecmwf.int/wiki/display/WEBAPI/TIGGE+retrieval+efficiency
# ECMWF forecasts from TIGGE data set:
# T2M fields
# all available full years, 2007-2016
# ... | slerch/ppnn | data_retrieval/forecasts/retrieve_ecmwf_fc_data.py | Python | mit | 1,739 |
from __future__ import absolute_import
# import auth modules into client package
from .auth.oauth import Account
from .auth.oauth import Organization
from .auth.oauth import Link
from .auth.oauth import OAuth
from .auth.oauth import OAuthToken
from .auth.oauth import OAuthUserInfo
| docusign/docusign-python-client | docusign_esign/client/__init__.py | Python | mit | 283 |
import attr
from django.core.cache import cache
@attr.s
class PostcodeLookupResult(object):
postcode = attr.ib()
number = attr.ib()
street = attr.ib()
city = attr.ib()
def json(self):
return attr.asdict(self)
class PostcodeLookupException(IOError):
pass
class _none(object):
pa... | LabD/django-postcode-lookup | src/django_postcode_lookup/backends/base.py | Python | mit | 872 |
import pytest
import divelog.files
def test_formats_dict():
for key in divelog.files.formats:
assert divelog.files.formats[key].FORMAT_NAME == key
def test_formats_dict_error():
with pytest.raises(KeyError):
divelog.files.formats['NO_TYPE']
def test_extensions_dict():
assert divelog.fi... | johnstonskj/PyDL7 | tests/test_files.py | Python | mit | 759 |
from django.contrib import admin
from ..models import (FacebookAccount, FacebookMessage, FacebookSearch,
TwitterAccount, TwitterMessage, TwitterSearch,
RSSAccount, RSSMessage, Message,
InstagramAccount, InstagramSearch, InstagramMessage,
... | MadeInHaus/django-social | social/admin/__init__.py | Python | mit | 2,011 |
#
# This file is a part of the normalize python library
#
# normalize is free software: you can redistribute it and/or modify
# it under the terms of the MIT License.
#
# normalize is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI... | hearsaycorp/normalize | tests/test_mfs_diff.py | Python | mit | 14,100 |
"""
urlconf to include and get test targets.
Or you could use views.raise_view directly.
Note that these will be live even when DEBUG=False, because you need that for
exceptional_middleware to do its thing at all (DEBUG=True gives you the
"technical" exception output with stack trace and the like).
"""
from django.c... | jaylett/django_exceptional_middleware | exceptional_middleware/urls.py | Python | mit | 506 |
#! /usr/bin/env python
import collections
import random
import time
from txrudp import rudp, constants, connection
class StubHandler(connection.Handler):
def __init__(self):
self.shutdown = False
self.received_count = 0
self.last_message = None
def receive_message(self, message):
... | jorik041/txrudp | tests/benchmark.py | Python | mit | 3,482 |
import os
import asyncio
import logging
from discord import opus, ClientException
from discord.ext import commands
from discord.opus import OpusNotLoaded
from cogs.utils.music import Music
from cogs.utils.music_type import MusicType
from cogs.utils.music_player import MusicPlayer
OPUS_LIBS = ['libopus-0.x86.dll', 'lib... | WoodNeck/tataru | cogs/sound.py | Python | mit | 7,698 |
from setuptools import setup, find_packages
from slackminion.plugins.core import version
setup(
name='slackminion',
version=version,
packages=find_packages(exclude=['test_plugins']),
url='https://github.com/arcticfoxnv/slackminion',
license='MIT',
author='Nick King',
... | arcticfoxnv/slackminion | setup.py | Python | mit | 1,517 |
from flask import session, Blueprint
from lexos.helpers import constants as constants
from lexos.managers import session_manager as session_manager
from lexos.models.k_means_model import KMeansModel
from lexos.views.base import render
k_means_blueprint = Blueprint("k-means", __name__)
@k_means_blueprint.route("/k-me... | WheatonCS/Lexos | lexos/views/k_means.py | Python | mit | 1,097 |
"""
Dissimilarity measures for clustering
"""
import numpy as np
def matching_dissim(a, b, **_):
"""Simple matching dissimilarity function"""
return np.sum(a != b, axis=1)
def jaccard_dissim_binary(a, b, **__):
"""Jaccard dissimilarity function for binary encoded variables"""
if ((a == 0) | (a == 1... | nicodv/kmodes | kmodes/util/dissim.py | Python | mit | 3,486 |
from __future__ import unicode_literals, division, absolute_import
import logging
import re
from path import Path
from flexget import plugin
from flexget.config_schema import one_or_more
from flexget.event import event
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
log = log... | Pretagonist/Flexget | flexget/plugins/filter/exists_movie.py | Python | mit | 7,327 |
from poloniex_apis import trading_api
class Balances:
def __init__(self):
self.all_balances = trading_api.return_complete_balances()
def get_btc_total(self):
total_btc = 0
for stock, balances in self._get_active_balances().items():
total_btc += float(balances['btcValue'])
... | BenjiLee/PoloniexAnalyzer | poloniex_apis/api_models/balances.py | Python | mit | 750 |
import os
import shlex
import pytest
import pyperclip
from mitmproxy import exceptions
from mitmproxy.addons import export # heh
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.test import taddons
from unittest import mock
@pytest.fixture
def get_request():
return tflow.tflow(... | vhaupert/mitmproxy | test/mitmproxy/addons/test_export.py | Python | mit | 8,827 |
#!/bin/python
table = dict()
def climb(n):
if table.has_key(n):
return table[n]
if n == 0:
return 1
if n < 0:
return 0
total = 0
total += climb(n - 1)
total += climb(n - 2)
total += climb(n - 3)
table[n] = total
return total
... | migafgarcia/programming-challenges | hackerrank/cracking_the_coding_interview/davis_staircase.py | Python | mit | 423 |
from ctypes import windll
from accessible_output import paths
from main import OutputError, ScreenreaderSpeechOutput
class NVDA (ScreenreaderSpeechOutput):
"""Supports The NVDA screen reader"""
name = 'NVDA'
def __init__(self, *args, **kwargs):
super(NVDA, self).__init__(*args, **kwargs)
try:
self.dll = w... | Timtam/cards-against-humanity | accessible_output/speech/outputs/nvda.py | Python | mit | 744 |
from model import SRCNN
from utils import input_setup
import numpy as np
import tensorflow as tf
import pprint
import os
flags = tf.app.flags
flags.DEFINE_integer("epoch", 15000, "Number of epoch [15000]")
flags.DEFINE_integer("batch_size", 128, "The size of batch images [128]")
flags.DEFINE_integer("image_size", 33... | tegg89/SRCNN-Tensorflow | main.py | Python | mit | 1,707 |
#! /usr/bin/python
#
# Example to run classifier on webcam stream.
# Brandon Amos & Vijayenthiran
# 2016/06/21
#
# Copyright 2015-2016 Carnegie Mellon University
#
# 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... | m0re4u/SmartLight | client/modules/face_recognizer/recognize.py | Python | mit | 7,243 |
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'', # prefix
url(r'^tokens/([0-9a-f]{32})$', 'mailauth.views.auth', name='mailauth_auth'),
url(r'^auth/$', 'mailauth.views.auth_form', name='mailauth_form'),
)
| Nnonexistent/chemphys | src/mailauth/urls.py | Python | mit | 251 |
"""
Running KNN Recommenders [Rating Prediction]
- Cross Validation
- Simple
"""
from caserec.recommenders.rating_prediction.user_attribute_knn import UserAttributeKNN
from caserec.recommenders.rating_prediction.item_attribute_knn import ItemAttributeKNN
from caserec.recommenders.rating_prediction.itemkn... | ArthurFortes/CaseRecommender | examples/rating_prediction_knn.py | Python | mit | 1,542 |
# MIT License
# Copyright (c) 2016 Diogo Dutra <dutradda@gmail.com>
# 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, co... | dutradda/swaggerit | swaggerit/utils.py | Python | mit | 2,906 |