code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
"""Family module for Meta Wiki."""
#
# (C) Pywikibot team, 2005-2020
#
# Distributed under the terms of the MIT license.
#
from pywikibot import family
# The Wikimedia Meta-Wiki family
class Family(family.WikimediaOrgFamily):
"""Family class for Meta Wiki."""
name = 'meta'
interwiki_forward = 'wikipedi... | wikimedia/pywikibot-core | pywikibot/families/meta_family.py | Python | mit | 564 |
from office365.runtime.client_value import ClientValue
class ServicePlanInfo(ClientValue):
"""Contains information about a service plan associated with a subscribed SKU. The servicePlans property of
the subscribedSku entity is a collection of servicePlanInfo."""
def __init__(self, _id=None, name=None, pr... | vgrem/Office365-REST-Python-Client | office365/directory/licenses/service_plan_info.py | Python | mit | 1,595 |
from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class SearchView(TemplateView):
template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
c... | hzdg/django-google-search | googlesearch/views.py | Python | mit | 2,809 |
'''
RP_extract: Rhythm Patterns Audio Feature Extractor
@author: 2014-2015 Alexander Schindler, Thomas Lidy
Re-implementation by Alexander Schindler of RP_extract for Matlab
Matlab version originally by Thomas Lidy, based on Musik Analysis Toolbox by Elias Pampalk
( see http://ifs.tuwien.ac.at/mir/downloads.html )
... | bastustrump/genimpro | rp_extract.py | Python | mit | 39,383 |
"""
Script used to convert data into sparse matrix format that
can easily be imported into MATLAB.
Use like this
python convertToSparseMatrix.py ../../../../../data/train_triplets.txt 1000 ../../../../../data/eval/year1_test_triplets_visible.txt ../../../../../data/eval/year1_test_triplets_hidden.txt 100
"""
import sys... | EmilienDupont/cs229project | convertToSparseMatrix.py | Python | mit | 3,343 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
running = os.system("nc -u -l -p 5001 | mplayer -cache 1024 -")
#subprocess.check_call('/opt/vc/bin/raspivid -n -w 800 -h 600 -fps 24 -t 0 -o - | socat - udp-sendto:' + '129.16.194.248' + ':5001')
| twistedretard/LaserSimulatedSecurityTurret | src/streaming/server.py | Python | mit | 272 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... | rwl/PyCIM | CIM14/IEC61970/Meas/LimitSet.py | Python | mit | 2,248 |
#-*- coding: utf-8 -*-
""" EOSS catalog system
external catalog management package
"""
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Thilo Wehrmann"
__email__ ... | eoss-cloud/madxxx_catalog_api | catalog/manage/__init__.py | Python | mit | 705 |
import _plotly_utils.basevalidators
class SizesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="sizesrc",
parent_name="scattermapbox.hoverlabel.font",
**kwargs
):
super(SizesrcValidator, self).__init__(
plotly_name=plo... | plotly/python-api | packages/python/plotly/plotly/validators/scattermapbox/hoverlabel/font/_sizesrc.py | Python | mit | 498 |
class Solution:
def crackSafe(self, n: int, k: int) -> str:
result = ['0'] * n
visited = set([''.join(result)])
for i in range(k ** n):
prev = result[len(result) - n + 1:]
for j in range(k - 1, -1, -1):
curr = ''.join(prev) + str(j)
if ... | jiadaizhao/LeetCode | 0701-0800/0753-Cracking the Safe/0753-Cracking the Safe.py | Python | mit | 478 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
class DCGAN(object):
"""
Tensorflow implementation of DCGAN, with four CNN layers.
We assume the input images are of size 32x32.
"""
def __init__(self):
... | gokul-uf/TF-DCGAN | model.py | Python | mit | 7,113 |
# -*- coding: utf-8 -*-
from datetime import datetime, date
import six
def fix_number(target_type):
return lambda value: None if isinstance(value, (str, six.text_type)) and len(value) == 0 else target_type(value)
fixed_datetime = lambda time_str: datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
fixed_date = lam... | anjianshi/flask-restful-extend | flask_restful_extend/reqparse_fixed_type.py | Python | mit | 425 |
import pymake.data, pymake.functions, pymake.util
import unittest
import re
def multitest(cls):
for name in cls.testdata.keys():
def m(self, name=name):
return self.runSingle(*self.testdata[name])
setattr(cls, 'test_%s' % name, m)
return cls
class SplitWordsTest(unittest.TestCase... | mozilla/pymake | tests/datatests.py | Python | mit | 6,946 |
from botapi.settings import *
DEBUG = True
ALLOWED_HOSTS = ['*']
| naelstrof/PugBot-Discord-Django | botapi/apache/override.py | Python | mit | 66 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as s... | ryfeus/lambda-packs | pytorch/source/caffe2/python/operator_test/lengths_top_k_ops_test.py | Python | mit | 2,523 |
import unittest
converter = __import__("obj-to-sm-conversion")
model = """
# Blender v2.71 (sub 0) OBJ File:
# www.blender.org
mtllib object.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.... | stbd/stoolbox | tests/obj-to-sm-test/conversion-test.py | Python | mit | 3,598 |
#!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
... | ranisalt/moita-migrant | migrant.py | Python | mit | 1,377 |
"""Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig
LOG = logging.getLogger(__name__)
class WebAPI: # pylint: disable=too-few-public-methods
"""An API for the command-line interface."""
@class... | kytos/kytos-utils | kytos/cli/commands/web/api.py | Python | mit | 986 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-29 05:42
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0025_auto_20170626_0008'),
]
operations = [
migrations.AlterModelOptions(
... | r26zhao/django_blog | blog/migrations/0026_auto_20170629_1342.py | Python | mit | 467 |
import string
import unittest
import datetime
import collections
from unittest import mock
from flumine.order.order import (
BaseOrder,
BetfairOrder,
ExchangeType,
OrderTypes,
OrderStatus,
VALID_BETFAIR_CUSTOMER_ORDER_REF_CHARACTERS,
LIVE_STATUS,
COMPLETE_STATUS,
)
from flumine.exceptio... | liampauling/flumine | tests/test_order.py | Python | mit | 23,869 |
# para os tipos numericos temos os seguintes operadores:
# + - * / % **
print "Numeros inteiros:"
x = 10
y = 3
print x, "+", y, "=", x + y
print x, "+", y, "=", x - y
print x, "+", y, "=", x*y
print x, "+", y, "=", x/y # repare como o resultado eh um inteiro
print x, "+", y, "=", x % y # esse eh o resto da divisao
pri... | folivetti/PI-UFABC | AULA_01/Python/operadores.py | Python | mit | 2,187 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.loa... | yxdong/ybk | ybk/lighttrade/trader.py | Python | mit | 2,160 |
import command_line
import ast
import os
import traceback
from operator import attrgetter
import settings
from execution_tree_builder import build_execution_tree
# TODO move classes to separate files
class DataCollectorCall(object):
def __init__(self, var_name="", indentation=0, line_position=0, need_stacktrace... | skyylex/Luminous-proof-of-concept | core/source_transformer.py | Python | mit | 9,513 |
#!env/bin/python
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() | iniweb/deployCD | manage.py | Python | mit | 266 |
def add_native_methods(clazz):
def getVMTemporaryDirectory____():
raise NotImplementedError()
clazz.getVMTemporaryDirectory____ = staticmethod(getVMTemporaryDirectory____)
| laffra/pava | pava/implementation/natives/sun/misc/VMSupport.py | Python | mit | 190 |
"""An example of using a middleware to require HTTPS connections.
requires https://github.com/falconry/falcon-require-https to be installed via
pip install falcon-require-https
"""
import hug
from falcon_require_https import RequireHTTPS
hug.API(__name__).http.add_middleware(RequireHTTPS())
@hug.get()
def my... | timothycrosley/hug | examples/force_https.py | Python | mit | 355 |
import sys
from .space_delimited import SpaceDelimited
try:
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("french")
except ValueError:
raise ImportError("Could not load stemmer for {0}. ".format(__name__))
try:
from nltk.corpus import stopwords as nltk_stopwords
stopwor... | ToAruShiroiNeko/revscoring | revscoring/languages/french.py | Python | mit | 1,905 |
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
import netaddr
name ... | ashmastaflash/gwdetect | dependencies/netaddr-0.7.10/release.py | Python | mit | 5,263 |
import model as Model
NODES_PER_ROBOT = 6
ROBOT_CPU_CAPACITY = 100
SERVER_CAPACITY = 400 # for greedy_2 the value must be 0
ALGORITHM = 'greedy_1' # greedy_2
###################################################################################################
def generate(num_computers, num_robots, num_cameras):
... | ipab-rad/perf_ros | src/tool/problem.py | Python | mit | 12,503 |
import numpy as np
import scipy.linalg as la
def calculate_vertex_normals(verts, tris):
v_array = np.array(verts)
tri_array = np.array(tris, dtype=int)
tri_pts = v_array[tri_array]
n = np.cross( tri_pts[:,1] - tri_pts[:,0],
tri_pts[:,2] - tri_pts[:,0])
v_normals = np.zeros(v_... | jfozard/pyvol | pyvol/mesh/algo.py | Python | mit | 602 |
"""
问题描述:给定一个矩阵matrix,其中的值有正、负和0,返回子矩阵的最大累加和.
例如,矩阵matrix为
-90 48 78
64 -40 64
-81 -7 66
其中,最大累加和的子矩阵为:
48 78
-40 64
-7 66
所以返回累加和209.
例如,matrix为:
-1 -1 -1
-1 2 2
-1 -1 -1
其中,最大累加和的子矩阵为:
2 2
所以返回累加和为4.
"""
import sys
from arrandmatrix.q16 import MaxSum
class MaxMatrixSum:
@classmethod
def g... | ResolveWang/algrithm_qa | arrandmatrix/q17.py | Python | mit | 1,207 |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 19 11:45:20 2016
@author: johnguttag
"""
import random, pylab, numpy
#set line width
pylab.rcParams['lines.linewidth'] = 4
#set font size for titles
pylab.rcParams['axes.titlesize'] = 20
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 20
#set size ... | johntauber/MITx6.00.2x | Unit4/Lecture10Video1Notes.py | Python | mit | 1,486 |
# Generated by Django 2.1.7 on 2019-03-09 11:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("account", "0018_auto_20190309_1153"),
]
operations = [
migrations.AddField(
model_name="taggedu... | fin/froide | froide/account/migrations/0019_auto_20190309_1223.py | Python | mit | 755 |
# -*- coding: utf-8 -*-
#
# Jetlibs documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 23 16:22:13 2015.
#
# 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.
#
# A... | jetspace/jetlibs | docs/source/conf.py | Python | mit | 10,239 |
"""engine.SCons.Tool.msvc
Tool-specific initialization for Microsoft Visual C/C++.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any p... | timj/scons | src/engine/SCons/Tool/msvc.py | Python | mit | 11,390 |
import fresh_tomatoes
import media
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys that come to life",
"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
"https://www.youtube.com/watch?v=vwyZH85NQC4")
#print(toy_sto... | tuanvu216/udacity-course | programming_foudations_with_python/entertainment_center.py | Python | mit | 1,734 |
import os, sys, shutil
if "SGE_ROOT" not in os.environ:
print "scramble(): Please set SGE_ROOT to the path of your SGE installation"
print "scramble(): before scrambling DRMAA_python"
sys.exit(1)
# change back to the build dir
if os.path.dirname( sys.argv[0] ) != "":
os.chdir( os.path.dirname( sys.arg... | volpino/Yeps-EURAC | scripts/scramble/scripts/DRMAA_python-macosx.py | Python | mit | 1,938 |
# -*- coding:utf-8 -*-
def length_of_last_word(str_):
split_str = str_.split(" ")
if not split_str:
return 0
return len(split_str[-1])
if __name__ == '__main__':
result = length_of_last_word("hello world")
print(result) | xudongyangwork/algo | day43/xudy.py | Python | mit | 251 |
# -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
LONGDOC = """
A very simple python library, used to format datetime with *** time ago statement.
Install
pip install timeago
Usage
import timeago, datetime
d = datetime.datetime.now() + datetime.timedelta(seconds = 60... | avrong/timeago | setup.py | Python | mit | 1,607 |
import subprocess
import os
"""
What are the differences and similarities between ffmpeg, libav, and avconv?
https://stackoverflow.com/questions/9477115
ffmeg encoders high to lower quality
libopus > libvorbis >= libfdk_aac > aac > libmp3lame
libfdk_aac due to copyrights needs to be compiled by end user
on MacOS brew... | AndreaMordenti/spotydowny | core/convert.py | Python | mit | 2,314 |
import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self... | delicb/SublimeConfig | tailf.py | Python | mit | 3,015 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import logging
from json import loads, dumps
from datetime import da... | wking/thumbor | thumbor/storages/redis_storage.py | Python | mit | 4,944 |
import re
import string
import nltk
from bs4 import BeautifulSoup
__author__ = 'nolram'
class NewsItem:
def __init__(self, news, stop_words):
self.all_words = []
self.stop_words = stop_words
self.regex = re.compile('[%s]' % re.escape(string.punctuation))
if "titulo" in news and... | nolram/news_crawler | classificador/news_item.py | Python | mit | 3,574 |
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
LOGIN_REDIRECT_URL = 'reviews'
A... | borfast/housing-reviews | housing_reviews/settings/auth.py | Python | mit | 476 |
import re
from six.moves import zip
def check_tag(root, expected):
pattern = re.compile(r"{.*}([a-zA-Z]+)")
for tag, el in zip(expected, root.iter()):
m = pattern.match(el.tag)
assert m is not None
assert m.group(1) == tag, "Expect tag=%s, get %s" % (tag, m.group(1))
| kunxi/docxgen | tests/__init__.py | Python | mit | 302 |
"""
Format and compress XML documents
"""
import getopt
import re
import sys
import xml.parsers.expat
__version__ = "0.2.4"
DEFAULT_BLANKS = False
DEFAULT_COMPRESS = False
DEFAULT_SELFCLOSE = False
DEFAULT_CORRECT = True
DEFAULT_INDENT = 2
DEFAULT_INDENT_CHAR = " "
DEFAULT_INLINE = True
DEFAULT_ENCODING_INPUT = None... | pamoller/xmlformatter | xmlformatter.py | Python | mit | 30,777 |
import os
import sys
import django
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
sys.path.append(os.path.abspath(os.path.dirnam... | hirokiky/django-websettings | runtest.py | Python | mit | 1,437 |
import Network
from time import sleep
from threading import Thread
CALL_ROOMLIST = 0
CALL_WEAPLIST = 1
CALL_PLAYERLIST = 2
CALL_NEWPLAYER = 3
CALL_PLAYERLEFT = 4
CALL_CHAT = 5
CALL_PLAYERDAT = 6
CALL_ROOMSTAT = 7
CALL_LEAVEROOM = 8
CALL_SHOOT = 9
CALL_SCORE = 10
class GameClient(Network.Client):
CONNECTING = 0
... | nemothekid/Colosseum--Year-3XXX | GameClient.py | Python | mit | 7,613 |
import functools
import itertools
import json
import multiprocessing
import os
import shutil
import sys
import time
import cv2
import numpy
import utility.config
import utility.cv
import utility.geometry
import utility.gui
import utility.image
import utility.log
# Explicitly disable OpenCL. Querying for OpenCL suppo... | joeydong/endless-lake-player | player.py | Python | mit | 4,891 |
import os
from tsc.models import *
def test_get_new_reservable_schedules():
old = [
Schedule(1, datetime.datetime(2015, 11, 1, 22, 00), ScheduleStatus.reservable),
Schedule(1, datetime.datetime(2015, 11, 1, 23, 00), ScheduleStatus.reservable),
]
new = [
Schedule(1, datetime.dateti... | oinume/dmm-eikaiwa-tsc | tests/test_models.py | Python | mit | 978 |
# -*- coding: utf-8 -*-
"""The application's model objects"""
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
# from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
# Global session manager: DBSession() returns the Thread-... | LamCiuLoeng/budget | budget/model/__init__.py | Python | mit | 2,408 |
# This script generates GeoTiff files based Corine land cover data
# Usage: python generateGeotiff.py berryName
# berryName is optional. If not provided all output layers are generated.
# Licensed under the MIT license
from osgeo import gdal, ogr, gdalconst
import sys
gdal.UseExceptions()
gdal.AllRegister()
# Paths ... | lukefi/missamustikka | backend/generateGeotiff.py | Python | mit | 2,298 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'r... | Shouqun/node-gn | tools/depot_tools/recipes/recipe_modules/git/examples/full.py | Python | mit | 5,612 |
from collections import defaultdict
from zipfile import ZipFile
from datetime import datetime
from itertools import izip
import logging
import sys
import shelve
from backtest import constants
def main():
PRICES_DATA = constants.PRICES_DATA
performances = shelve.open(constants.CACHE_PERFS, ... | chris-ch/us-equities | create-stats-perfs-db.py | Python | mit | 1,963 |
from functools import partial
def build_tag_filter(args):
"""
Returns a filter which selects entries with all of the given
tags only.
@param list(str) args, e.g. ["+tag1", "unrelated"]
@return (callable filter, list remaining_args)
"""
remaining_args = []
tags = set()
for arg in ar... | hoffie/ripple | ripple/filters/tag.py | Python | mit | 925 |
# Copyright (c) 2016 Lee Cannon
# Licensed under the MIT License, see included LICENSE File
from collections import Counter
from .filter import at_trigrams, with_words
def count_trigrams(interactions: list, minimum: int = 1, n: int = None, include_unknown: bool = False) -> list:
"""Returns the n most common trig... | leecannon/trending | trending/count.py | Python | mit | 4,854 |
# !/usr/bin/python
# @package model
# @author Attila Borcs
#
# Class for the deep neural net. Each class function wrapped with
# a decorator function using python @property for unifying
# the DNN functionalities when tensorflow graph initializer
# called (tf.global_variables_initializer())
import functools
impor... | attilaborcs/dnn-visualization | model.py | Python | mit | 3,922 |
#!/usr/bin/env python
"""
File: twitter_analyse.py
Author: Me
Email: 0
Github: 0
Description: Analyse tweets. For the detail, please refer to the document
```twitter_analyse.notes```
"""
# System lib
from __future__ import division
import json
import os
from math import log
import numpy
# 3-rd party lib
# import nltk... | mondwan/ProjectRazzies | twitter_analyse.py | Python | mit | 9,448 |
# -*- coding: utf-8 -*-
"""Module providing views for the folderish content page type"""
import json
import urllib
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from plone import api
from plone.i18n.normalizer.interfaces import IIDNormalizer
from zope.component import getUtility
from n... | a25kk/newe | src/newe.sitecontent/newe/sitecontent/browser/showroom.py | Python | mit | 7,487 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'final.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
... | kunz07/fyp2017 | GUI/final.py | Python | mit | 52,154 |
"""Store various constants here"""
from enum import Enum
# Maximum file upload size (in bytes).
MAX_CONTENT_LENGTH = 1 * 1024 * 1024 * 1024
# Authentication/account creation constants
PWD_HASH_ALGORITHM = 'pbkdf2_sha256'
SALT_SIZE = 24
MIN_USERNAME_LENGTH = 2
MAX_USERNAME_LENGTH = 32
MIN_PASSWORD_LENGTH = 8
MAX_PASSW... | ASCIT/donut-python | donut/constants.py | Python | mit | 2,372 |
"""
created 09/05/17
For executation of the kallisto quantification step
To be run with three arguements
* basedir - top level output directory
* input directory - contains folders with .fastq.gz files
* max_threads - how many threads to allocate to kallisto
Returns kallisto quantifications and associated l... | samleenz/rnaseq_pipe | kallisto_quant.py | Python | mit | 1,936 |
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import ro... | tapomayukh/projects_in_python | classification/Classification_with_kNN/Single_Contact_Classification/Scaled_Features/best_kNN_PCA/objects/test11_cross_validate_objects_1200ms_scaled_method_v.py | Python | mit | 4,915 |
# Kata link: https://www.codewars.com/kata/58daa7617332e59593000006
# First solution
def find_longest(arr):
count = [len(str(v)) for v in arr]
max_value = max(count)
max_index = count.index(max_value)
return arr[max_index]
# Another solution
def find_longest(arr):
return max(arr, key=lambda x: len... | chyumin/Codewars | Python/7 kyu/Most Digits.py | Python | mit | 330 |
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Modified by Mauy5043 (2016)
# 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... | Mausy5043/bonediagd | DHT22/bonediagd_DHT/platform_detect.py | Python | mit | 1,586 |
import numpy as _np
import lnls as _lnls
import pyaccel as _pyaccel
from . import lattice as _lattice
default_cavity_on = False
default_radiation_on = False
default_vchamber_on = False
def create_accelerator(optics_mode=_lattice.default_optics_mode, energy=_lattice.energy):
lattice = _lattice.create_lattice(op... | lnls-fac/sirius | pymodels/BO_V06_01/accelerator.py | Python | mit | 915 |
#!/usr/bin/env python
# coding: utf-8
# Copyright (C) USC Information Sciences Institute
# Author: Vladimir M. Zaytsev <zaytsev@usc.edu>
# URL: <http://nlg.isi.edu/>
# For more information, see README.md
# For license information, see LICENSE
from django.conf.urls import url
from django.conf.urls import patterns
from... | zaycev/n7 | n7/web/urls.py | Python | mit | 586 |
'''
Week-2:Exercise-grader-polysum
A regular polygon has n number of sides. Each side has length s.
The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n)
The perimeter of a polygon is: length of the boundary of the polygon
Write a function called polysum that takes 2 arguments, n and s. This function should sum the ... | ahmedkareem999/MITx-6.00.1x | polySum.py | Python | mit | 1,018 |
#!/usr/bin/env python3
print(sum(map(int, str(2**1000))))
| mazayus/ProjectEuler | problem016.py | Python | mit | 59 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-01 22:55
from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('contentcuration', '0038_contentnode_author'),
]
operations = [
... | DXCanas/content-curation | contentcuration/contentcuration/migrations/0039_auto_20161101_1555.py | Python | mit | 1,022 |
import os
import re
from setuptools import setup
base_path = os.path.dirname(__file__)
def get_long_description():
readme_md = os.path.join(base_path, "README.md")
with open(readme_md) as f:
return f.read()
with open(os.path.join(base_path, "cfscrape", "__init__.py")) as f:
VERSION = re.compile... | Anorov/cloudflare-scrape | setup.py | Python | mit | 943 |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'context_var': 'expected'})
def withUrlFields(request, value):
return HttpResponse(value)
@login_required
def requiresLog... | tctimmeh/django-testing-base | testsite/testapp/views.py | Python | mit | 449 |
#!/usr/bin/python
# Made by Sangpil Kim
# June 2016
import json
from google import search
import csv
def searchGoogle(query,dic):
bloomberg = []
forbes = []
# later do forbes as well
for url in search(query, stop=10):
print(url)
if 'bloomberg.com/research/stocks/private/person' in u... | spk921/scrapers | bloomberg/archive/getOldBloomberg.py | Python | mit | 1,395 |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest.ip_messaging import TwilioIpMessagingClient
# Your Account Sid and Auth Token from twilio.com/user/account
account = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
token = "your_auth_token"
client = TwilioIpMessagingClient(account, token)
... | teoreteetik/api-snippets | ip-messaging/rest/messages/list-messages/list-messages.5.x.py | Python | mit | 533 |
from . import common
import os
import hglib
class test_paths(common.basetest):
def test_basic(self):
f = open('.hg/hgrc', 'a')
f.write('[paths]\nfoo = bar\n')
f.close()
# hgrc isn't watched for changes yet, have to reopen
self.client = hglib.open()
paths = self.clie... | beckjake/python3-hglib | tests/test-paths.py | Python | mit | 512 |
# -*- coding: utf-8 -*-
# programme qui demande un nombre et affiche les 10 triples successifs
chaine = input("donne un nombre : ")
nombre = int(chaine)
triple = nombre
compteur=1
while(compteur<=10):
triple=triple*3
print(triple)
compteur=compteur+1
| Straor/Prog | Python/prog13.py | Python | mit | 255 |
#!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
# The rand7() API is already defined for you.
def rand7():
return 0
class Sol... | algorhythms/LeetCode | 470 Implement Rand10() Using Rand7().py | Python | mit | 773 |
import question_template
game_type = 'input_output'
source_language = 'C'
parameter_list = [
['$x1','int'],['$x2','int'],['$x3','int'],['$y0','int'],
]
tuple_list = [
['for_continue_',
[0,1,2,None],
[0,2,2,None],
[0,4,2,None],
[0,6,2,None],
[0,7,2,None],
[None,None,2,1],
[None,None,2,2],
[None... | stryder199/RyarkAssignments | Assignment2/ttt/archive/for_loops/for_continue.py | Python | mit | 1,067 |
"""
Geofilters
----------
Filters coded oriented to filter and detect uncorrect data.
"""
import os
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.neighbors import KDTree
from pySpatialTools.Preprocess.Transformations.Transformation_2d.geo_filters\
import check_in_square_area... | tgquintela/Mscthesis | FirmsLocations/Preprocess/geo_filters.py | Python | mit | 7,868 |
# -*- coding: utf-8 -*-
__author__ = "Ildar Bikmamatov"
__email__ = "vistoyn@gmail.com"
__copyright__ = "Copyright 2016"
__license__ = "MIT"
__version__ = "1.0.1"
from . import log
from .lib import *
from .error import *
from .colors import colorf
from .datelib import *
| vistoyn/python-foruse | foruse/__init__.py | Python | mit | 274 |
from __future__ import print_function
import sys
import subprocess
class AutoInstall(object):
_loaded = set()
@classmethod
def find_module(cls, name, path, target=None):
if path is None and name not in cls._loaded:
cls._loaded.add(name)
print("Installing", name)
... | Liuchang0812/slides | pycon2015cn/ex6_auto_install/autoinstall.py | Python | mit | 590 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
| qisanstudio/qstudio-launch | src/studio/launch/commands/config.py | Python | mit | 69 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-27 15:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lots_admin', '0021_auto_20160927_0941'),
]
operations = [
migrations.AlterFie... | datamade/large-lots | lots_admin/migrations/0022_auto_20160927_1051.py | Python | mit | 462 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
pr... | h4ck3rm1k3/pywikibot-core | scripts/watchlist.py | Python | mit | 3,349 |
"""Graphical user interface to Delta-Elektronika SM-700 Series
controllers."""
import sys
import pyhard2.driver as drv
import pyhard2.driver.virtual as virtual
import pyhard2.driver.deltaelektronika as delta
import pyhard2.ctrlr as ctrlr
def createController():
"""Initialize controller."""
config = ctrlr.Co... | Synss/pyhard2 | pyhard2/ctrlr/deltaelektronika.py | Python | mit | 1,159 |
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os
from helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.... | bjoernricks/python-quilt | tests/test_refresh.py | Python | mit | 1,125 |
# region Description
"""
nmap_scanner.py: Scan local network with NMAP
Author: Vladimir Ivanov
License: MIT
Copyright 2020, Raw-packet Project
"""
# endregion
# region Import
from raw_packet.Utils.base import Base
import xml.etree.ElementTree as ET
import subprocess as sub
from tempfile import gettempdir
from os.path ... | Vladimir-Ivanov-Git/raw-packet | raw_packet/Scanners/nmap_scanner.py | Python | mit | 5,743 |
from ipfs_connector import IPFSConnector, IPFSConfig
from nn_loader import NNListener, NNLoader
class ProcessorCallback:
pass
class Processor(NNListener):
def __init__(self, callback: ProcessorCallback, ipfs_config: IPFSConfig):
print("Connecting to IPFS server %s:%d..." % (ipfs_config.server, ipfs_c... | Neurochain/neurowrk | src/processor.py | Python | mit | 1,697 |
from .manager import Manager
__version__ = '0.2.4'
| chendx79/Python3HandlerSocket | pyhs/__init__.py | Python | mit | 51 |
#This thread handles user operations of only 1 user
#, and is connected to the matchmaking thread and to the database thread
#The list of operations is as follows:
#userType: 0 for normal, 1 for facebook
# ID | ARGUMENTS
# 0 --- User signup | userType(fb or norma... | Shalantor/Connect4 | server/userThread.py | Python | mit | 5,045 |
# Schema
DB = "db"
Name = "name"
Tables = "tables"
Table = "table"
Columns = "columns"
Column = "column"
Attributes = "attributes"
Initials = "initials"
Initial = "initial"
InitialValue = "initialvalue"
Value = "value"
PrimaryKey = "primarykey"
| eddiedb6/pdb | PDBConst.py | Python | mit | 245 |
# -*- coding: utf-8 -*-
"""
oyPivotSwitcher.py by Erkan Ozgur Yilmaz (c) 2009
v10.5.17
Description :
-------------
A tool for easy animating of switching of pivots
Version History :
-----------------
v10.5.17
- modifications for Maya 2011 and PyMel 1.0.2
v9.12.25
- removed oyAxialCorrectionGroup script import
- mov... | eoyilmaz/anima | anima/dcc/mayaEnv/pivot_switcher.py | Python | mit | 8,729 |
import subprocess
def convert_chinese(text):
return subprocess.getoutput("echo '%s' | opencc -c hk2s.json" % text) | josherich/mindynode-parsers | mindynode_nltk/utils/opencc.py | Python | mit | 117 |
"""
events.py
Defines a simple event handler system similar to that used in C#. Events allow
multicast delegates and arbitrary message passing. They use weak references so
they don't keep their handlers alive if they are otherwise out of scope.
"""
import weakref
import maya.utils
from functools import partial, wrap... | theodox/mGui | mGui/events.py | Python | mit | 8,231 |
from django.conf.urls import url
from api import views
urlpatterns = [
url(r'stations/$', views.get_stations, name='api_stations'),
url(r'entry/(?P<station_id>\d+)/$', views.make_entry, name='api_entry'),
url(r'new/$', views.add_station, name='api_add_station'),
# Booking api
url(r'booking/(?P<res... | boyombo/django-stations | stations/api/urls.py | Python | mit | 2,383 |
#-*- coding:Utf-8 -*-
from __future__ import print_function
"""
.. curentmodule:: pylayers.util.project
.. autosummary::
"""
import numpy as np
import os
import sys
import shutil
import pkgutil
import pdb
import seaborn as sns
import logging
class PyLayers(object):
""" Generic PyLayers Meta Class
"""
# ... | pylayers/pylayers | pylayers/util/project.py | Python | mit | 10,692 |
import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... | oaubert/TwitterFontana | backend/src/app.py | Python | mit | 7,176 |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import ... | xi-studio/anime | music/train.py | Python | mit | 6,297 |
import os
def get_template_path(path):
file_path = os.path.join(os.getcwd(), path)
if not os.path.isfile(file_path):
raise Exception("This is not a valid template path %s"%(file_path))
return file_path
def get_template(path):
file_path = get_template_path(path)
return open(file_path).read()
def render_context... | nirajkvinit/python3-study | 30days/day13/templates.py | Python | mit | 691 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0011_auto_20151207_0017'),
... | dulrich15/spot | apps/roster/migrations/0002_auto_20151207_0017.py | Python | mit | 1,095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.