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 |
|---|---|---|---|---|---|
# NFAtoDFA.py
#
# Author: Stefan Mendoza
# Date: 2 October 2015
# Email: stefanmendoza.dev@gmail.com
import string
import sys
'''
Global variables
'''
alphabet = []
initial_state_nfa = []
table_nfa = {}
states_dfa = []
table_dfa = {}
'''
Flattens a nested listed into a single-dimension list
'''
def flatten(l):
... | stefanmendoza/NFA-to-DFA | NFAtoDFA.py | Python | mit | 6,202 |
from flask import jsonify
from http import HTTPStatus
from . import app
class ApiError(Exception):
def __init__(self, message, status_code=HTTPStatus.BAD_REQUEST):
self.message = message
self.status_code = status_code
def as_dict(self):
return dict(error=self.message)
@app.errorhand... | jparker/therminator_server | therminator/exc.py | Python | mit | 468 |
import errno
import os
import signal
from git_timeout import GitTimeout
class timeout:
def __init__(self, seconds, error_message=os.strerror(errno.ETIME)):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise GitTimeout(self.error_me... | Jfach/autostager | autostager/timeout.py | Python | mit | 521 |
import itertools
import random
from sqlalchemy import bindparam
from sqlalchemy import column
from sqlalchemy import exc
from sqlalchemy import exists
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalch... | sqlalchemy/sqlalchemy | test/sql/test_update.py | Python | mit | 50,298 |
from idl.Annotatable import Annotatable
from idl.IDLSyntaxError import IDLSyntaxError
from idl.Type import Type
from idl.lexer import Lang
class Variable(Annotatable):
def __init__(self, variableType, name=None, mods=0, arraySize=-1):
Annotatable.__init__(self)
self._type = variableType
... | spiricn/libIDL | idl/Variable.py | Python | mit | 2,895 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-07 03:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app01', '0001_initial'),
]
operations = [
migrations.AlterField(
... | AirChen/PythonPractic | djangoDemo/sitedemo/app01/migrations/0002_auto_20170107_0312.py | Python | mit | 992 |
import openpnm as op
import numpy as np
from openpnm.phases import mixtures
import openpnm.models as mods
class MixturesTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.N2 = mixtures.species.gases.N2(network=self.net)
self.O2 = mixtures.species.gases.O2(networ... | TomTranter/OpenPNM | tests/unit/models/phase/MixturesTest.py | Python | mit | 3,012 |
# coding=utf-8
# Author: Diego González Chávez
# email : diegogch@cbpf.br / diego.gonzalez.chavez@gmail.com
#
# This class controls the:
# Multimeter
# KEITHLEY : 2000
#
# TODO:
# Make documentation
from .instruments_base import InstrumentBase as _InstrumentBase
__all__ = ['KEITHLEY_2000']
class KEITHLEY_2000(_Ins... | Vrekrer/magdynlab | instruments/keithley_2000.py | Python | mit | 1,152 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-21 13:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0022_auto_20170919_2233'),
]
operations = [
migrations.AlterField(
... | XeryusTC/18xx-accountant | accountant/core/migrations/0023_auto_20170921_1355.py | Python | mit | 508 |
n = int(input())
start = 0
finish = 0
minstart = 0
minfinish = 0
prev = int(input())
for i in range(2, n + 1):
top = int(input())
if prev < top:
start = i - 1
if prev > top:
finish = i
if start * finish != 0 and finish > start and (minfinish - minstart == 0 or finish - start < minfinis... | dluschan/olymp | vseros/2016-17/school/mountain.py | Python | mit | 465 |
#!/usr/bin/env python3
# Copyright (c) 2015-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node responses to invalid network messages."""
import struct
import time
from test_framework.mes... | syscoin/syscoin | test/functional/p2p_invalid_messages.py | Python | mit | 11,480 |
from setuptools import setup, find_packages
import deepx
recommended = {
'tensorflow': ['tensorflow'],
'pytorch': ['torch'],
'jax': ['jax', 'jaxlib'],
}
setup(
name = "deepx",
version = deepx.__version__,
author = "Sharad Vikram",
author_email = "sharad.vikram@gmail.com",
description ... | sharadmv/deepx | setup.py | Python | mit | 503 |
import unittest
import numpy as np
from numpy.random import rand
from diogenes.display.display import describe_cols
import diogenes.read as read
from diogenes import utils
import utils_for_tests
from collections import Counter
class TestRead(unittest.TestCase):
def test_open_csv(self):
csv_file = util... | jamestwhedbee/diogenes | tests/test_read.py | Python | mit | 2,565 |
def pow_of_list(some_list, num):
if num > len(some_list)-1:
return 0
else:
return some_list[num]**num
def gap(some_list):
if any([type(x) == type('a') for x in some_list]):
return'문자열이 있습니다'
else:
return max(some_list) - min(some_list)
| saintdragon2/python-3-lecture-2015 | homework_checker/zest_pow_gap_hw/hw_zest_pg_15039022.py | Python | mit | 311 |
# 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/trafficmanager/azure-mgmt-trafficmanager/azure/mgmt/trafficmanager/_traffic_manager_management_client.py | Python | mit | 5,138 |
# install munkres module for the calculation of the Hungarian matrix: http://software.clapper.org/munkres/#installing
# pip install munkres
from munkres import Munkres
import numpy as np
import re
import copy
import matplotlib.pyplot as plt
import math
import scipy
import six
from matplotlib import colors
color = list... | sussexwearlab/OpenEnded | Utilities_JSI_release.py | Python | mit | 25,579 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Member Model."""
import uuid
from invenio_db import db
from invenio_accounts.models im... | inveniosoftware/invenio-communities | invenio_communities/members/records/models.py | Python | mit | 1,035 |
# -*- coding: utf-8 -*
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
from flask_moment import Moment
from flask_pagedown import PageDown
bootstrap = Bootstrap()
db = SQLAlchemy()
moment = Moment()
pa... | lrenze/renze_app | app/__init__.py | Python | mit | 954 |
#!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eit... | dmnfarrell/peat | PEATDB/Ekin/Ekin_images.py | Python | mit | 22,227 |
import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
from Bio import SeqUtils
import numpy as np
import pandas as pd
import cairi
from multiprocessing import Pool
import matplotlib.pyplot as plt
from Bio.SeqUtils import CodonUsage
from Bio import Data
def back_translate(protein,SynCodon,CodonWeigh... | sergpolly/Thermal_adapt_scripts | ArchNew/BOOTSTRAP/Equal_Cherry_BOOTSTRAP_shuffle_codons.py | Python | mit | 7,438 |
# -*- coding: utf-8 -*-
from __future__ import division
from pytest import raises
from numpy.testing import assert_allclose, assert_equal
import numpy as np
from SALib.analyze.morris import analyze, \
compute_mu_star_confidence, \
compute_elementary_effects, \
get_increased_values, \
get_decreased_va... | willu47/SALib | tests/test_analyze_morris.py | Python | mit | 15,255 |
import os, sys, glob
from collections import defaultdict
selectedFeaturesFilePath = sys.argv[1]
trainTestFilePath = sys.argv[2]
numFeaturesFilePath = sys.argv[3]
outFilePath = sys.argv[4]
numFeaturesDict = {}
if os.path.exists(numFeaturesFilePath):
numFeaturesFile = open(numFeaturesFilePath)
for line in numFe... | srp33/ShinyLearner | scripts/AppendOuterSelectedFeatures.py | Python | mit | 1,468 |
# -*- coding: utf-8 -*-
"""Universal Notifications
Sample usage:
WSNotification(item, receivers, context).send()
"""
import importlib
import logging
import re
from email.utils import formataddr
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.m... | ArabellaTech/universal_notifications | universal_notifications/notifications.py | Python | mit | 14,775 |
#!/usr/bin/env python
'''This uses subprocess to restart spotifyd and adjust Pulseaudio volume remotely'''
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess
INDEX_HEAD = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>spotifyd remote control</title>
<meta nam... | delucks/dotfiles | common/bin/spotifyrestartd.py | Python | mit | 2,154 |
import urllib
import rfc3987
import sys
try:
import urlparse
except:
import urllib.parse as urlparse
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
logger.addHandler(ch)
def to_iri(iri):
"""
Safely quotes an IRI... | CLARIAH-SDH/iribaker | iribaker/__init__.py | Python | mit | 3,383 |
from graphql.core.type import GraphQLInt, GraphQLString
from ....types.argument import Argument
__author__ = 'jake'
connection_args = {
'before': Argument(GraphQLString),
'after': Argument(GraphQLString),
'first': Argument(GraphQLInt),
'last': Argument(GraphQLInt),
}
| graphql-python/graphql-epoxy | epoxy/contrib/relay/connections/__init__.py | Python | mit | 287 |
# 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/storage/azure-mgmt-storage/azure/mgmt/storage/v2019_04_01/operations/_blob_containers_operations.py | Python | mit | 72,265 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11rc1 on 2017-04-08 16:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0012_auto_20170407_1604'),
]
operations = [
migrations.AlterField... | Sirikam/Gravitas | apps/users/migrations/0013_auto_20170408_1834.py | Python | mit | 462 |
"""
WSGI config for stalku 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.9/howto/deployment/wsgi/
"""
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.enviro... | henriquenogueira/stalku | stalku/wsgi.py | Python | mit | 423 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 18:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('magic', '0003_auto_20170929_0229'),
]
operations = [
migrations.AlterField(... | Angoreher/xcero | magic/migrations/0004_auto_20170929_1525.py | Python | mit | 478 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from hypothesis import given
import hypothesis.strategies as st
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized... | ryfeus/lambda-packs | pytorch/source/caffe2/python/operator_test/locally_connected_op_test.py | Python | mit | 7,686 |
class TrackingFailure(Exception):
"""Generic tracking failure, subclassed by more specific
exceptions.
"""
pass
class TrackingApiFailure(TrackingFailure):
"""Raised in the event of a failure with the service's API. For
example, a SOAP fault or authentication failure. The request was
valid ... | lilbowser/Package_Tracking_Alerter | Tracking/errors.py | Python | mit | 1,344 |
""" Finds any disconnected terminal service sessions and logs them off"""
import win32ts
import pywintypes
import winerror
sessions=win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE)
for session in sessions:
"""
WTS_CONNECTSTATE_CLASS: WTSActive,WTSConnected,WTSConnectQuery,WTSShadow,WTSDisconnecte... | sserrot/champion_relationships | venv/Lib/site-packages/win32/Demos/win32ts_logoff_disconnected.py | Python | mit | 950 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import cv2
import ast
from config_aa import *
data = np.load(os.path.join(TEST_RESULTS_DIR, 'atten... | pratikgujjar/DeepIntent | code/autoencoder_model/scripts/plot_heatmap.py | Python | mit | 834 |
# coding: utf-8
from .forms import BriteverifyFormMixin
__version__ = '1.0'
| uploadcare/django-briteverify | django_briteverify/__init__.py | Python | mit | 77 |
try:
# Python 3.8+
import importlib.metadata as importlib_metadata
except ImportError:
# <Python 3.7 and lower
import importlib_metadata
__version__ = importlib_metadata.version("django-push-notifications")
| rsalmaso/django-push-notifications | push_notifications/__init__.py | Python | mit | 224 |
from tests.testcase import CoverageReporterTestCase
class MinimumTest(CoverageReporterTestCase):
def test_minimum(self):
data = self.create_coverage_data({'foo.py' : {'missing' : 20},
'bar.py' : {'missing' : 10 }})
filter = self.load_plugin('minimum')
... | dugan/coverage-reporter | tests/test_filters/test_minimum.py | Python | mit | 458 |
import traceback
from sys import version_info
try:
from qualname import qualname
except ImportError:
def qualname(cls):
return cls.__qualname__
PY2 = version_info[0] == 2
PY3 = not PY2
if PY2:
def viewitems(d):
return d.viewitems()
else:
def viewitems(d):
return d.items()
d... | alexmojaki/cheap_repr | cheap_repr/utils.py | Python | mit | 903 |
from __future__ import absolute_import
import copy
import os.path
from allib.data import update_dict
_STR_TYPES = (str, bytes)
try:
_STR_TYPES += (unicode,) #pylint: disable=undefined-variable
except NameError:
pass
class ConfigError(Exception):
pass
def _validate_value(value, valid_type, key):
if valid_type... | anlutro/allib.py | allib/options/config.py | Python | mit | 4,600 |
class Solution:
def topKFrequent(self, nums, k):
freq = collections.Counter(nums)
buckets = [[] for _ in xrange(len(nums) + 1)]
for num, freq in freq.items():
buckets[freq].append(num)
return list(itertools.islice(itertools.chain(*buckets[::-1]), k))
| rahul-ramadas/leetcode | top-k-frequent-elements/Solution.62348845.py | Python | mit | 308 |
"""
Module for solving Rubik's Cube PLL.
"""
import csv, os
from pycuber import *
with open(os.path.join(os.path.dirname(__file__), "pll_algos.csv"), "r") as f:
reader = csv.reader(f, delimiter=",")
algo_dict = {}
for name, rec_id, algo in reader:
for i in range(4):
algo_dict[rec_id[-3... | adrianliaw/PyCuber | pycuber/solver/cfop/pll.py | Python | mit | 1,981 |
from sympy import C, pi, I
from sympy.core import Dummy, sympify
from sympy.functions import legendre, assoc_legendre
from sympy.functions.elementary.miscellaneous import sqrt
Pl = legendre
Plm= assoc_legendre
_x = Dummy("x")
def Plmcos(l, m, th):
l = sympify(l)
m = sympify(m)
sin = C.sin
cos = C.cos... | Cuuuurzel/KiPyCalc | sympy_old/functions/special/spherical_harmonics.py | Python | mit | 1,672 |
import pickle
import uuid
try:
import kombu
except ImportError:
kombu = None
from .pubsub_manager import PubSubManager
class KombuManager(PubSubManager): # pragma: no cover
"""Client manager that uses kombu for inter-process messaging.
This class implements a client manager backend for event shari... | sumedh123/debatify | venv/lib/python2.7/site-packages/socketio/kombu_manager.py | Python | mit | 2,800 |
"""
Sessions class for sorting sessions for guisort
"""
from __future__ import print_function, division, absolute_import
import numpy as np
from scipy.io import savemat
from .cluster import Cluster
from .group_list_model import GroupListModel
from .. import GROUP_ART, GROUP_NOCLASS, TYPE_MU, TYPE_ART, TYPE_NO
class S... | jniediek/combinato | combinato/guisort/sessions.py | Python | mit | 5,060 |
# coding: utf-8
# Deep Learning
# =============
#
# Assignment 2
# ------------
#
# Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html).
#
# The goal of this assignme... | ds-hwang/deeplearning_udacity | udacity_notebook/2_fullyconnected.py | Python | mit | 14,353 |
import weakref
##############################
# del not delete objects
s1 = {1,2,3}
s2 = s1
def bye(): print('Gone with wind...')
ender = weakref.finalize(s1, bye)
print(ender.alive) # True
del s1 # alive even the name is deleted
print(ender.alive) # True
s2 = 'spam' # rebinded, object freed
print(ender.alive) # False
... | stoneflyop1/fluent_py | ch08/weakref_demo.py | Python | mit | 1,350 |
#!/usr/bin/env python
"""mock_config.py - Library of high-level Mock configuration snippets
"""
from .builder import to
from .composition import compose, ConfigurationObject
__all__ = ['bind_mount', 'file', 'env_vars', 'use_host_resolv']
class BindMount(ConfigurationObject):
"""Class for generating Mock bind mou... | ifireball/python-mockchroot | mock_chroot/config/highlevel.py | Python | mit | 2,207 |
import re
import time
from random import randint
import collections
import sys
class Dice():
def __init__(self, mucbot):
self.mucbot = mucbot
def roll(self, i, d):
sum = 0
for x in range(0, i):
sum = sum + randint(1, d)
return sum
def handle(self, msg):
... | kbeckmann/Annalog | dice.py | Python | mit | 2,157 |
#!/usr/bin/python
import os
import json, sqlite3
import initdb
import builddb
import requests, zipfile
import shutil
import discordBot
APP_PATH = "/etc/destinygotg"
DBPATH = f"{APP_PATH}/guardians.db"
def check_db():
"""Check to see if a database exists"""
return os.path.isfile(os.environ['DBPATH'])
def init... | adherrling/destiny-gotg | model.py | Python | mit | 1,400 |
# coding=utf-8
import glob
import os
from fileManager import FileManager
__author__ = 'peter'
print(FileManager.getHomePath())
| PeterHo/Linalfred | test/test_filemanager.py | Python | mit | 130 |
import os
class Path:
def __init__(self, path, arg_names=None, defaults=None):
self._path = path
self._arg_names = tuple([] if arg_names is None else arg_names)
self._defaults = tuple([] if defaults is None else defaults)
@property
def path(self):
return self._path
@... | jbn/pathsjson | pathsjson/path.py | Python | mit | 2,714 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/eventhubs/tests/latest/test_eventhub_commands_namespace_byok_test.py | Python | mit | 6,478 |
from datetime import time, timedelta
from apps.core.tests import BaseTestCase
from apps.meetings.models import Meeting
class UseModelTestCase(BaseTestCase):
def test_change_settings_creates_meeting(self):
self.assertEqual(Meeting.objects.all().count(), 0)
# Change settings and save
self.... | SoPR/horas | apps/profiles/tests/test_models.py | Python | mit | 8,278 |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-cli"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util ... | litebitcoins/litebitcoin | test/functional/bitcoin_cli.py | Python | mit | 832 |
import serial, time, sys
import logging
class TimeoutError(Exception):
"""Raised when a serial communication times out.
*data* attribute contains any data received so far.
"""
def __init__(self, msg, data):
self.data = data
Exception.__init__(self, msg)
class DataError(Exception):
... | mgraupe/acq4 | acq4/drivers/SerialDevice.py | Python | mit | 7,575 |
"""Clowder command line branch controller
.. codeauthor:: Joe DeCapo <joe@polka.cat>
"""
import argparse
import clowder.util.formatting as fmt
from clowder.clowder_controller import CLOWDER_CONTROLLER, print_clowder_name, valid_clowder_yaml_required
from clowder.config import Config
from clowder.git.clowder_repo im... | JrGoodle/clowder | clowder/cli/branch.py | Python | mit | 2,005 |
"""
WSGI config for docker_django 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.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO... | philipp-x/docker-django | docker_django/wsgi.py | Python | mit | 403 |
"""
Convergence regions of the expansions used in ``struve.c``
Note that for v >> z both functions tend rapidly to 0,
and for v << -z, they tend to infinity.
The floating-point functions over/underflow in the lower left and right
corners of the figure.
Figure legend
=============
Red region
Power series is clo... | DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/special/c_misc/struve_convergence.py | Python | mit | 3,695 |
#!/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.
# Check 3rd-party dependencies
try:
import joblib # noqa: F401
import websocket # noqa: F401
import sh # ... | facebookresearch/ParlAI | parlai/chat_service/services/messenger/__init__.py | Python | mit | 489 |
from markdown import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from july.blog.models import Blog
register = template.Library()
@register.filter(is_safe=True)
@stringfilte... | julython/julython.org | july/templatetags/markup.py | Python | mit | 701 |
import numpy
from smop.core import *
# OSVR/constructParams.m
@function
def constructParams(dataset=None,labelset=None,epsilon=None,bias=None,flag=None,*args,**kwargs):
varargin = constructParams.varargin
nargin = constructParams.nargin
# formalize model parameters used by admm solver for OSVR
... | abyrne55/osvr-review | old/constructParams.py | Python | mit | 5,765 |
import numpy as np
from numpy.linalg import norm
import model
import math
from sample import Sample
import copy
class ParameterizedSolver(object):
def __init__(self, _prob, _ntasks, _mean_type, _alg=''):
self.name = 'Ours(%s)' % _mean_type
self.alg = _alg
self.prob = _prob
self.n =... | sehoonha/optskills | optskills/solver/parameterized.py | Python | mit | 8,604 |
from nanopore.mappers.abstractMapper import AbstractMapper
from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite
import os
class Last(AbstractMapper):
def run(self, params=""):
localReferenceFastaFile = os.path.join(self.getLocalTempDir(), "ref.fa") #Because we don't want to have any crufty fil... | mitenjain/nanopore | nanopore/mappers/last.py | Python | mit | 1,928 |
# -*- coding:utf-8 -*-
dict1 = {}
print(type(dict1))
| MiracleWong/PythonBasic | geekbang/test_dict.py | Python | mit | 54 |
import argparse
import sys
import pandas as pd
import tensorflow as tf
TRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv"
TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth',
'PetalLength', 'PetalWidth', 'Species']
SPECI... | bsautermeister/machine-learning-examples | dnn_classification/tf_estimator/dnn_iris.py | Python | mit | 4,333 |
def fix_django_evolution_issues(settings):
# XXX Django r8244 moves django.db.models.fields.files.ImageField and
# FileField into django.db.models.files, causing existing
# signatures to fail. For the purpose of loading, temporarily
# place these back into fields. The next time the signature is
# ge... | asutherland/opc-reviewboard | reviewboard/admin/migration.py | Python | mit | 776 |
mqtt_broker = "192.168.10.254"
mqtt_client_id = b"esp_bathroom_rgb"
mqtt_topic = b"bathroom/rgb1"
mqtt_user = "homeassistant"
mqtt_password = "internetofthings"
led_pin = 4 # d2
| ulno/micropython-extra-ulno | examples/ehdemov3/bathroom_rgb/config.py | Python | mit | 179 |
#!/usr/bin/env python3
"""
#
input:
1.AthARF.fa
2.LcPep.fa.mod-makeblastdb
....
output: tree
"""
import sys
import re
import subprocess
athFamily = sys.argv[1]
targetBlastDb = sys.argv[2] # only BlastP DB prefix
# simplify IDs
fafile = athFamily
blastInFile = fafile+".mod"
faOut = open(blastInFile,'w')
pa... | CJ-Chen/TBtools-Manual | BioScripts/PythonScript/Predict_TF_family.py | Python | mit | 2,645 |
import io
import os
import json
DIALECT_FILE_PATH = os.path.join(
os.path.dirname(__file__),
'gherkin-languages.json'
)
with io.open(DIALECT_FILE_PATH, 'rb') as file:
DIALECTS = json.load(file, encoding='utf-8')
class Dialect(object):
@classmethod
def for_name(cls, name):
return cl... | curzona/gherkin-python | gherkin3/dialect.py | Python | mit | 1,109 |
import bpy
vGroupList = []
myObject = bpy.context.object
for mesh in myObject.children: #for each mesh
for vGroup in mesh.vertex_groups: #for each vertexgroup
vGroupList.append(vGroup.name)
for bone in myObject.data.bones: #for each bone
if(bone.name not in vGrou... | Ganonmaster/sfm-scripts | Met/FindUnusedBones.py | Python | mit | 367 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main(argv):
from deg_logic import degrees
if len(argv) < 2:
print("Input file isn't specified. Using test values:")
print('n = 6')
n = 6
print('n = 7')
m = 7
graph = [[0 for _ in range(n)] for _ in range(n)]
... | ivanyu/rosalind | algorithmic_heights/deg/deg.py | Python | mit | 1,327 |
from django.conf.urls import patterns, include, url
from rest_framework.routers import DefaultRouter
from catalog.views import CourseViewSet
from views import HomeView
from django.contrib import admin
admin.autodiscover()
router = DefaultRouter()
router.register(r'courses', CourseViewSet)
urlpatterns = patterns('',
... | ltiao/unsw-catalog-old | unsw_catalog/unsw_catalog/urls.py | Python | mit | 612 |
# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from uuid import UUID, uuid4
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.po... | indico/indico | indico/modules/events/models/static_list_links.py | Python | mit | 3,436 |
"""
Some useful functions for manipulating time.
Copyright (C) 2017 The Pylp Authors.
This file is under the MIT License.
"""
def time_to_text(time):
"""Get a representative text of a time (in s)."""
if time < 0.001:
return str(round(time * 1000000)) + " µs"
elif time < 1:
return s... | pylp/pylp | pylp/utils/time.py | Python | mit | 473 |
import tensorflow as tf
from utils import *
LENET5_LIKE_BATCH_SIZE = 32
LENET5_LIKE_FILTER_SIZE = 5
LENET5_LIKE_FILTER_DEPTH = 16
LENET5_LIKE_NUM_HIDDEN = 120
def variables_lenet5_like(filter_size = LENET5_LIKE_FILTER_SIZE,
filter_depth = LENET5_LIKE_FILTER_DEPTH,
... | taspinar/sidl | cnn_models/lenet5_like.py | Python | mit | 2,428 |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
try:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
except Exception, e:
print "Forget setuptools, trying distutils..."
from distutils.core import setup
se... | hunse/deepnet | setup.py | Python | mit | 708 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LinkedInUser.email'
db.add_column(u'webapp_linkedinuser', 'email',
sel... | cfonger/group-insider | insider/webapp/migrations/0005_auto__add_field_linkedinuser_email.py | Python | mit | 1,660 |
# MIT License
#
# Copyright (c) 2015-2021 Iakiv Kramarenko
#
# 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, modif... | yashaka/selene | tests/integration/element__all__len_test.py | Python | mit | 1,561 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from mpi4py import MPI
def bcast_if_comm_is_not_null(x, comm):
"""
MPI broadcast. Broadcast object over given communicator only if the
communicator is not null.
Parameters
----------
x : any object
The object would shared over given commu... | ibara1454/pyss | pyss/mpi/util/communicative.py | Python | mit | 764 |
"""
The MIT License
Copyright (c) 2014 Jacob Reske
For use in MUS491 Senior Project, in partial fulfillment of the Yale College Music Major (INT).
Code may be reused and distributed without permission.
Module: clusterTest.py
"""
import sys, os, glob, argparse, logging
syspath = os.path.dirname(os.path.realpath(__file_... | colorthought/MUS490 | tests/clusterTest.py | Python | mit | 3,353 |
import argparse
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', action='store', dest='batch_size',help='batch-size , default 64',type=int,default = 64)
parser.add_argument('--epochs', action='store', dest='n_epochs',help='# of epochs, default = 500',type=int,default = 500)... | wolet/s2s-dependency-parsers | parser/utils.py | Python | mit | 2,723 |
#On the name of ALLAH
#Author : Fouad Teniou
#Date : 07/03/09
#version :2.6.1
""" New in python 2.6 namedtuple function is used in my program IRR-Versus-NPV
with a PresentValue as a typename, and discount rates r_1, r_2 and
number of periods until payments n as fieldnames (PresentValue('r_1','r_2','n'))
IR... | ActiveState/code | recipes/Python/576683_IRRVersusNPV_26/recipe-576683.py | Python | mit | 9,255 |
'''
title = "Non-unique Elements"
level = "intro"
dificulty = "medium"
tags = ["types", "calculator"]
description = """
You are given a non-empty list of integers (X).
For this task, you should return a list consisting of only the non-unique elements
in this list. To do so you will need to remove all unique elements
(e... | rmotr/whooshercises | assignments/non_unique_elements.py | Python | mit | 880 |
import _plotly_utils.basevalidators
class OpacityValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="opacity", parent_name="layout.scene.annotation", **kwargs
):
super(OpacityValidator, self).__init__(
plotly_name=plotly_name,
paren... | plotly/python-api | packages/python/plotly/plotly/validators/layout/scene/annotation/_opacity.py | Python | mit | 548 |
__author__ = 'igorsf@gmail.com (Igor Fridman)'
import requests
import datetime
import logging
import uuid
import time
import json
import base64
import rsa
from requests.auth import HTTPBasicAuth
logger = logging.getLogger(__name__)
# Constant strings for OAuth2 flow
# The OAuth authority
AUTHORITY = 'https://login.m... | igorsf/office365-api-python-client | client.py | Python | mit | 8,641 |
def skysofifrom2d(fitsfile, skyfile):
# print "LOGX:: Entering `skysofifrom2d` method/function in %(__file__)s"
# % globals()
import ntt
from ntt.util import readhdr, readkey3, delete
from numpy import mean, arange, compress
try:
from astropy.io import fits as pyfits
except:
... | svalenti/pessto | trunk/src/ntt/sofispec2Ddef.py | Python | mit | 44,042 |
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.db.models.signals import pre_save
import os
class Boardfile(models.Model):
user = models.ForeignKey(User)
docname = "generic"
whenUploaded = models.DateTimeField('whenUploaded') # Filled in with signal
the... | leephillips/FOTPweb | boarddocs/models.py | Python | mit | 4,152 |
from setuptools import setup
from blockchain_certificates import __version__
with open('README.rst') as readme:
long_description = readme.read()
setup(name='blockchain-certificates',
version=__version__,
description='Create pdf certificate files and issue on the blockchain!',
long_description=lo... | UniversityOfNicosia/blockchain-certificates | setup.py | Python | mit | 1,527 |
from __future__ import division
import numpy as np
from keras.models import Sequential, Model
from keras.optimizers import SGD
from keras_extensions.logging import log_to_file
from keras_extensions.rbm import RBM
from keras_extensions.layers import SampleBernoulli
from keras_extensions.initializations import... | bnsnapper/keras_bn_library | example/test_rbm.py | Python | mit | 2,586 |
"""Install packages via the MacOSX Homebrew and Linux Linuxbrew package manager.
https://github.com/mxcl/homebrew
https://github.com/Homebrew/linuxbrew
"""
import contextlib
from distutils.version import LooseVersion
import os
import sys
from cloudbio.custom import system, shared
from cloudbio.flavor.config import get... | heuermh/cloudbiolinux | cloudbio/package/brew.py | Python | mit | 18,439 |
# vim:ts=4:sts=4:sw=4:expandtab
"""Communications and scheduling of event clients.
"""
from types import GeneratorType
from satori.objects import Object, Argument
from satori.events.misc import flattenCoroutine
from satori.events.protocol import Command, ProtocolError
class Scheduler(Object):
"""Interface. Cho... | zielmicha/satori | satori.events/satori/events/client.py | Python | mit | 2,567 |
# -*- coding: utf-8 -*-
from flask import render_template, json
from flask.views import View
class GenericView(View):
def __init__(self, data_func, jsbundle, div_name, init_func, title, external_js, external_css):
self.data_func = data_func
self.jsbundle = jsbundle
self.div_name = div_na... | atlefren/beerdatabase | web/generic_view.py | Python | mit | 2,216 |
# Copyright (c) 2019-2021 Manfred Moitzi
# License: MIT License
import enum
import math
import logging
from typing import (
TYPE_CHECKING,
Union,
Tuple,
List,
Iterable,
Optional,
Callable,
cast,
)
from ezdxf.lldxf import const, validator
from ezdxf.lldxf.attributes import (
DXFAttr,... | mozman/ezdxf | src/ezdxf/entities/mtext.py | Python | mit | 45,837 |
from django.db import models
from django.dispatch import receiver
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from projects.models import Project
@python_2_unicode_compatible
class SumoMatch(models.Model):
i... | bilbeyt/ituro | ituro/sumo/models.py | Python | mit | 3,393 |
# settings/production.py
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PRO... | neosergio/vote_hackatrix_backend | vote_hackatrix/settings/production.py | Python | mit | 579 |
from OpenGLCffi.GLES2 import params
@params(api='gles2', prms=['numGroups', 'groupsSize', 'groups'])
def glGetPerfMonitorGroupsAMD(numGroups, groupsSize, groups):
pass
@params(api='gles2', prms=['group', 'numCounters', 'maxActiveCounters', 'counterSize', 'counters'])
def glGetPerfMonitorCountersAMD(group, numCounter... | cydenix/OpenGLCffi | OpenGLCffi/GLES2/EXT/AMD/performance_monitor.py | Python | mit | 1,541 |
ONLY_IN_FIRST = 'This settings is exclusive of first settings'
SIMPLE_CONF = 'Simple in first settings'
| drgarcia1986/simple-settings | examples/pipeline/first_settings.py | Python | mit | 104 |
import hashlib
import json
import os
import threading
import time
from dbx import IsDirError
class Config(object):
def __init__(self, config_file):
self._raw = json.load(open(config_file))
def __getitem__(self, key):
return self._raw[key]
class ETagCache(object):
def __init__(self, dbx_f... | sujayakar/public-domain | web.py | Python | mit | 7,471 |
from django.db import models
from datetime import datetime
class Contact(models.Model):
email = models.EmailField(
verbose_name='email address',
max_length=255,
db_index=True,
)
name = models.CharField(max_length=35, blank=False)
text = models.CharField(max_length=1000, blank=... | houssemFat/MeeM-Dev | core/apps/company/models.py | Python | mit | 645 |
"""voting URLs"""
import datetime
from django.urls import path, register_converter
from django.views.generic.base import RedirectView, TemplateView
from . import views
app_name = "voting"
class DateConverter:
"""Path converter to accept a YYYY/MM/DD date."""
regex = r'[0-9]{4}/[0-9]{2}/[0-9]{2}'
def... | jribbens/voting | voting/urls.py | Python | mit | 2,618 |