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 OpenGLCffi.GL import params
@params(api='gl', prms=['length', 'marker'])
def glInsertEventMarkerEXT(length, marker):
pass
@params(api='gl', prms=['length', 'marker'])
def glPushGroupMarkerEXT(length, marker):
pass
@params(api='gl', prms=[])
def glPopGroupMarkerEXT():
pass
| cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/EXT/debug_marker.py | Python | mit | 287 |
# -*- coding: utf-8 -*-
"""
Lumberjack utilities for serializing log records.
"""
from six.moves import cPickle as pickle
import logging
import struct
import json
import functools
class SerializingFormatter(logging.Formatter, object):
"""A base class for serializing formatters."""
serializer = lambda d :... | alexrudy/lumberjack | lumberjack/serialize.py | Python | mit | 2,077 |
def P_success(T, T0, Ts):
return 1.0 / (1.0 + np.exp(-(T-T0)/Ts))
| LSSTC-DSFP/LSSTC-DSFP-Sessions | Sessions/Session10/Day4/missing_information/.totallynothiddensolutions/psuccess.py | Python | mit | 70 |
'''
The MIT License (MIT)
Copyright (c) 2015 Thami Rusdi Agus - https://github.com/janglapuk/SPB-OpenCV-Recognizer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including w... | janglapuk/SPB-OpenCV-Recognizer | src/util.py | Python | mit | 2,489 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Cron jobs routes module."""
# WebApp 2
from webapp2_extras.routes import RedirectRoute
# Handlers
from . import handlers
_routes = [
RedirectRoute(
template='/jobs/retrieve_books',
handler=handlers.RetrieveBooksHandler,
name='jobs__retrieve_... | pablotrinidad/oreilly-api | oreilly/cron_jobs/routes.py | Python | mit | 528 |
from setuptools import setup
setup(
name='GaussOpt',
version='1.1.3',
author='John Garrett',
author_email='garrettj403@gmail.com',
description='Gaussian beam analysis',
license='MIT',
keywords='gaussian optics millimeter terahertz thz',
url='https://github.com/garrettj403/GaussOpt/',
... | garrettj403/GaussOpt | setup.py | Python | mit | 899 |
# coding: utf-8
import time
import msvcrt
import zmq
from agent_pb2 import *
zctx = zmq.Context()
zsck_ctrl = zctx.socket(zmq.PUSH)
zsck_status = zctx.socket(zmq.SUB)
zsck_status.setsockopt(zmq.SUBSCRIBE, '')
zsck_ctrl.connect('tcp://127.0.0.1:17267')
zsck_status.connect('tcp://127.0.0.1:17268')
j = 0
while True:
... | dkrikun/ffmpeg-rcd | agent_test.py | Python | mit | 1,332 |
import unittest
import os
import pandas as pd
from copy import deepcopy
from mock import MagicMock, Mock, patch
import ROOT
from PyAnalysisTools.PlottingUtils import PlottingTools
from PyAnalysisTools.base import InvalidInputError
from .Mocks import hist
from PyAnalysisTools.AnalysisTools import StatisticsTools as st... | morgenst/PyAnalysisTools | tests/unit/TestStatisticsTools.py | Python | mit | 6,513 |
from helper import help
if __name__ == '__main__':
Greet = help()
Greet.greeting('Hello')
| Sadeio/cs3240-labdemo | hello.py | Python | mit | 95 |
from .cplxfnc_cyth import py_zeta as zeta
from .cplxfnc_cyth import py_gamma_inc as gamma_inc
from .cplxfnc_cyth import py_u_asymp as u_asymp | cimatosa/cplxfnc | cplxfnc/__init__.py | Python | mit | 141 |
# coding: utf-8
__all__ = ('EVENT_SCHEDULER_START', 'EVENT_SCHEDULER_SHUTDOWN', 'EVENT_EXECUTOR_ADDED', 'EVENT_EXECUTOR_REMOVED',
'EVENT_JOBSTORE_ADDED', 'EVENT_JOBSTORE_REMOVED', 'EVENT_ALL_JOBS_REMOVED', 'EVENT_JOB_ADDED',
'EVENT_JOB_REMOVED', 'EVENT_JOB_MODIFIED', 'EVENT_JOB_EXECUTED', 'EVENT_J... | cychenyin/windmill | apscheduler/events.py | Python | mit | 2,628 |
#!/usr/bin/env python
"""
The SMB module performs smb-related
enumeration tasks.
@author: Gabor Seljan (gabor<at>seljan.hu)
@version: 1.0
"""
import sys
from ..config import Config
from ..process_manager import ProcessManager
from ..generic_service import GenericService
class SmbEnumeration(GenericService, ProcessMa... | sgabe/Enumerator | enumerator/lib/services/smb.py | Python | mit | 2,757 |
import sys
a = 150
from pypreprocessor import pypreprocessor
#[pypreprocessor]#exclude
#exclude
sys.exit(1)
#endexclude
#ifdef printTest
a+=50
#else
a-=50
#endif
#ifdef printTest
import os
print('Hello, world!')
print('가즈아ㅏㅏ')
print(a)
#endif
#[pypreprocessor]#endexclude | evanplaice/pypreprocessor | tests/parsetarget.py | Python | mit | 283 |
class Produto(object):
def __init__(self, codigo=0, nome="", preco=0.0, unidade="", quantidade=0):
self.__codigo = codigo
self.__nome = nome
self.__preco = preco
self.__unidade = unidade
self.__quantidade = quantidade
@property
def codigo(self):
return self.... | rodrigo-labs/controle_estoque | controle_de_estoque/models/entities.py | Python | mit | 1,473 |
# Django settings for django_webtest_tests project.
import os, sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
join = lambda p: os.path.abspath(os.path.join(PROJECT_ROOT, p))
sys.path.insert(0, join('..'))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
... | t0ster/django-webtest | django_webtest_tests/settings.py | Python | mit | 3,427 |
#!/usr/bin/env python
import os
import sys
import inspect
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
arch_dir = '../lib/x64' if sys.maxsize > 2**32 else '../lib/x86'
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
import Leap
| huangy6/vroombot | src/libs.py | Python | mit | 272 |
import sys,os
from os import walk
import urllib.request, urllib.parse, urllib.error,glob
import pyfits
from astropy.time import Time
import zipfile
import lib.explodeFits as expFits
#########
# main #
#########
if len(sys.argv)==1: # pas d argument
print("prend un argument: repertoire de travail")
exit()
else:
... | tlemoult/spectroDb | tools/explode-fits.py | Python | mit | 659 |
"""Library URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | a0919610611/Library | Library/urls.py | Python | mit | 1,645 |
"""Benchmarking module for AlignmentFile functionality"""
import os
import pysam
import unittest
from TestUtils import make_data_files, BAM_DATADIR, IS_PYTHON3, force_str, flatten_nested_list
import PileupTestUtils
def setUpModule():
make_data_files(BAM_DATADIR)
class TestPileupReadSelection(unittest.TestCase):... | pysam-developers/pysam | tests/AlignmentFilePileup_test.py | Python | mit | 16,021 |
# 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/metricsadvisor/azure-ai-metricsadvisor/azure/ai/metricsadvisor/_generated/_configuration.py | Python | mit | 3,206 |
# Job: Information about a beaver's job.
# DO NOT MODIFY THIS FILE
# Never try to directly create an instance of this class, or modify its member variables.
# Instead, you should only be reading its variables and calling its functions.
from games.stumped.game_object import GameObject
class Job(GameObject):
"""... | Loran425/MegaminerAI_2017_Stumped | games/stumped/job.py | Python | mit | 2,893 |
from django import forms
from django.contrib import admin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import CarouselPlugin, CarouselPicture
class PictureInline(admin.TabularInline... | MagicSolutions/cmsplugin-carousel | cmsplugin_carousel/cms_plugins.py | Python | mit | 1,290 |
OK = 200
CREATED = 201
NO_CONTENT = 204
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
NOT_ALLOWED = 405
CONFLICT = 409
INTERNAL_SERVER_ERROR = 500
| buckmaxwell/neoapi | neoapi/http_error_codes.py | Python | mit | 170 |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 02 18:20:40 2015
@author: Konstantin
"""
from scipy import optimize
import numpy as np
import configparser, os, csv
from fabric.api import env, execute, task, get
import cuisine
import pandas
import operator
import pickle
import scipy.stats as stats
... | icclab/vm-reliability-tester | model_validator.py | Python | mit | 10,696 |
"""
Acquire PicoScope data in Rapid-Block Mode.
"""
import os
from msl.equipment import (
EquipmentRecord,
ConnectionRecord,
Backend,
)
record = EquipmentRecord(
manufacturer='Pico Technology',
model='5244B', # update for your PicoScope
serial='DY135/055', # update for your PicoScope
con... | MSLNZ/msl-equipment | msl/examples/equipment/picotech/picoscope/rapid_block_mode.py | Python | mit | 2,602 |
#!/usr/bin/env python3
# encoding: utf-8
from engine.utils.string_utils import remove_single_digits, remove_citations, remove_special_chars, \
remove_single_chars, remove_stopwords, stem_words, remove_multiple_spaces
class TextProcessor(object):
def proceed_paper(self, paper):
paper.title_proceed = se... | thomasmauerhofer/search-engine | src/engine/preprocessing/text_processor.py | Python | mit | 1,633 |
import matplotlib.pyplot as plt
import numpy as np
with open('dhhf.out', 'r') as f:
array = [[],[],[]]
i = 0
for line in f:
if (i == 3):
i = 0
continue
array[i].append(float(line))
i = i + 1
for i in range(0, 3):
plt.plot(array[i])
plt.legend(("third laye... | vegetable68/deep-recurrent | print.py | Python | mit | 380 |
import csv
import json
import datetime
from urllib2 import urlopen
from country_iso_code import *
with open('user.csv', 'rb') as f:
f.next() #skip first line
reader = csv.reader(f)
raw_discourse_data = list(reader)
creation_date = [i[5] for i in raw_discourse_data]
ip_address = [i[17] for i in raw_disco... | matthieu-lapeyre/discourse-members-analysis | get_countries_from_ip_list.py | Python | mit | 2,553 |
# -*- coding: utf-8 -*-
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
def runtests():
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test... | jaredly/django-colorfield | runtests.py | Python | mit | 421 |
SUCCESS = 1
INVALID_METHOD = 2
UNHANDLED_ERROR = 3
| rgalanakis/practicalmayapython | src/chapter6/mayaserver/__init__.py | Python | mit | 51 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ReTweet'
db.create_table(u'tweets_retweet', (
... | assamite/TwatBot | tweets/migrations/0003_auto__add_retweet.py | Python | mit | 7,366 |
import os, posixpath, sys, subprocess
# Settings
MUSIC_DIR = '/home/mark/Music'
PHONE_DIR = '/storage/9016-4EF8/Music'
SYNC_FILETYPES = 'mp3,flac'
ADB_CMD = 'adb'
# Windows only settings
if(os.name == 'nt'):
MUSIC_DIR = 'D:\Music'
ADB_CMD = 'adb\\adb'
print('Starting MusicSync v1.0.0-alpha')
# Firs... | markeroberts/MusicSync | MusicSync.py | Python | mit | 2,960 |
# 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 ... | Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-cognitiveservices-language-textanalytics/azure/cognitiveservices/language/textanalytics/models/entities_batch_result.py | Python | mit | 1,816 |
__all__ = ['AbstractCrudConf']
class AbstractCrudConf(object):
"""
This is the abstract crudconf your concrete CrudConf should inherit from.
A crudconf provides a common interface for the Crud views in order to provide
appropriate model instance url resolving in the template.
"""
model = None
... | tonimichel/django-modelcrud | modelcrud/abstract_crudconf.py | Python | mit | 3,166 |
#!/usr/bin/env python
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['stableinterface']... | TerryHowe/ansible-modules-hashivault | ansible/modules/hashivault/hashivault_approle_role_secret.py | Python | mit | 4,930 |
#!/usr/bin/env python3
"""
Data may be obtained from
https://drive.google.com/open?id=0B7P8Xeeyo_YIVTlfMk9wY0YtbzQ
Example code on using the alt_slice_overlay function in the plotting.py file.
Takes two h5 files--a PFISR file and a Neo sCMOS file-- and creates 2 objects,
which are input into alt_slice_overlay.
The out... | jswoboda/GeoDataPython | Test/subplots_mishap.py | Python | mit | 1,949 |
import _plotly_utils.basevalidators
class LabelValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="label",
parent_name="layout.xaxis.rangeselector.button",
**kwargs
):
super(LabelValidator, self).__init__(
plotly_name=pl... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/xaxis/rangeselector/button/_label.py | Python | mit | 454 |
import argparse, os
import torch
import random
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from lapsrn import Net, L1_Charbonnier_loss
from dataset import DatasetFromHdf5
# Training setting... | twtygqyy/pytorch-LapSRN | main_lapsrn.py | Python | mit | 5,258 |
import logging
import shelve
from boto.exception import S3ResponseError
import boto
from flask.ext.sandboy import BadRequestException
import os.path
class FileManager(object):
def __init__(self, app):
self.app = app
# Name of the lazy db on the s3 bucket
self.lazy_db = "lazy"
# ... | Diolor/ADP | backend/file_manager.py | Python | mit | 2,544 |
def guess():
# Guessing game where user guesses a num between 1-10
number = 6
while True:
guess = int(input("Guess a number from 1-10 : "))
if guess == number:
return(True)
def converter():
# Convert str to unicode num, then back to str
user_string = input("Enter an uppe... | J-kaizen/kaizen | python/LTP/exception_handling.py | Python | mit | 479 |
from setuptools import setup, find_packages
import os
import re
import django_lets_go
def read(*parts):
return open(os.path.join(os.path.dirname(__file__), *parts)).read()
def parse_requirements(file_name):
requirements = []
for line in open(file_name, 'r').read().split('\n'):
if re.match(r'(\s*... | areski/django-lets-go | setup.py | Python | mit | 1,860 |
from __future__ import print_function
from unittest import TestCase
from indexdigest.linters.linter_0006_not_used_columns_and_tables import check_not_used_tables, check_not_used_columns, \
get_used_tables_from_queries
from indexdigest.database import Database
from indexdigest.test import DatabaseTestMixin, read_q... | macbre/index-digest | indexdigest/test/linters/test_0006_not_used_columns_and_tables.py | Python | mit | 3,679 |
"""
Simple Flask web site
"""
import flask
from flask import render_template
from flask import request
from flask import url_for
from flask import jsonify # For AJAX transactions
import json
import logging
import sys
# Our own modules
from letterbag import LetterBag
import find
###
# Globals
###
app = flask.Flask(... | UO-CIS-322/scrabble-helper | flask_scrabble.py | Python | mit | 1,819 |
from functools import partial
import numpy as np
from .util_math import dct2, dft2, idct2, idft2
def blockproc(im, fun, block_size=8):
N = block_size
new = np.zeros(im.shape, dtype='complex_')
for i in range(im.shape[0] // N):
for j in range(im.shape[1] // N):
sl = slice(i*N, i*N + N... | uvNikita/image-proc-demo | app/compression.py | Python | mit | 887 |
import time
import sys
import csv
from subprocess import call
from random import randint
def prints(string):#Creating a function that types letter by letter
for c in string:#
sys.stdout.write(c)#
sys.stdout.flush()#
time.sleep(0.05)#
print#
def printf(string):#Creating another... | husky-prophet/personal-backup | Treasure chest/Al gore loves treasure.py | Python | mit | 7,426 |
import dj_database_url
from madewithwagtail.settings import *
DATABASES = {"default": dj_database_url.parse(DATABASE_URL, conn_max_age=600)}
| springload/madewithwagtail | madewithwagtail/settings/grains/database.py | Python | mit | 143 |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test the CHECKLOCKTIMEVERIFY (BIP65) soft-fork logic
#
from test_framework.test_framework import Di... | digibyte/digibyte | qa/rpc-tests/bip65-cltv.py | Python | mit | 3,314 |
import functools
class EdgeCache(object):
"""
Provides easy methods to for setting edge caching, both via the browser and App Engine's
intermediate caching proxies.
"""
def __init__(self, controller):
self.controller = controller
def _get_default_expiration(self):
return self... | markEarvin/password-tracker | ferris/components/edge_cache.py | Python | mit | 1,245 |
from django.conf.urls import patterns
urlpatterns = patterns('',
(r'authorized/?$', 'hiicart.gateway.paypal2.views.authorized'),
(r'do_pay/?$', 'hiicart.gateway.paypal2.views.do_pay'),
(r'ipn/?$', 'hiicart.gateway.paypal2.views.ipn'),
)
| hiidef/hiicart | hiicart/gateway/paypal2/urls.py | Python | mit | 288 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import sys
class NewVisitorTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
for arg in sys.argv:
if 'liveserver' in arg:
... | miracode/django_tdd | functional_tests/tests.py | Python | mit | 4,711 |
from __future__ import unicode_literals
import re
import inspect
import json
from .exceptions import SpecError
from .types import *
__all__ = ['get_args', 'args_to_datum', 'assert_is_compatible',
'deserialize_json', 'serialize_json', 'string_to_json',
'validate_underscore_identifier', 'is_stri... | cosmic-api/cosmic.py | cosmic/tools.py | Python | mit | 4,541 |
"""
Support for calling code when the main thread exits.
atexit cannot be used, since registered atexit functions only run after *all*
threads have exited.
The watchdog thread will be started by crochet.setup().
"""
import threading
import time
from twisted.python import log
class Watchdog(threading.Thread):
... | itamarst/crochet | crochet/_shutdown.py | Python | mit | 1,591 |
"""
Base_Map.py
Created by amounra on 2012-12-30.
Copyright (c) 2010 __artisia__. All rights reserved.
This file allows the reassignment of the controls from their default arrangement. The order is from left to right;
Buttons are Note #'s and Faders/Rotaries are Controller #'s
"""
OSC_TRANSMIT = False
OSC_OUTPORT... | LividInstruments/LiveRemoteScripts | Livid_Base_LE/Map.py | Python | mit | 6,114 |
#!/usr/bin/env python
"""Produces data that matches the CAI for a gene against its P3."""
from cogent.parse.cutg import CutgParser
from cogent.parse.fasta import MinimalFastaParser
from cogent.core.usage import UnsafeCodonUsage as CodonUsage, \
UnsafeCodonsFromString
from cogent.maths.stats.cai.util import cais
fro... | sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/cogent/maths/stats/cai/get_by_cai.py | Python | mit | 2,274 |
#!/home/daniel/Documents/ecommerce/bin/python
#
# The Python Imaging Library.
# $Id$
#
# print image files to postscript printer
#
# History:
# 0.1 1996-04-20 fl Created
# 0.2 1996-10-04 fl Use draft mode when converting.
# 0.3 2003-05-06 fl Fixed a typo or two.
#
VERSION = "pilprint 0.3/2003-05-05"
from ... | DMLoy/ECommerceBasic | bin/pilprint.py | Python | mit | 2,335 |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: 周二 九月 16 11:56:22 2014
# by: The Resource Compiler for PyQt (Qt v4.8.6)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x00\x70\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48... | wood9366/2dSkeletonAnimation | main_rc2.py | Python | mit | 2,569 |
#!/usr/bin/env python3
import re
import asyncio
import os
import configparser
import operator
import logging
import atexit
from collections import OrderedDict
from types import SimpleNamespace
from importlib import import_module
import nvchecker.lib.nicelogger as nicelogger
from serializer import PickledData
import n... | cuihaoleo/nvnotifier | main.py | Python | mit | 8,322 |
import os
from channels.asgi import get_channel_layer
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
channel_layer = get_channel_layer()
| dehu4ka/lna | config/asgi.py | Python | mit | 165 |
import mxnet as mx
import random
from mxnet.io import DataBatch, DataIter
import numpy as np
def add_data_args(parser):
data = parser.add_argument_group('Data', 'the input images')
data.add_argument('--data-train', type=str, help='the training data')
data.add_argument('--data-val', type=str, help='the validatio... | yancz1989/lr_semi | common/data.py | Python | mit | 6,204 |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"Also available in": "Ankaŭ disponebla en",
"Archive": "Arĥivo",
"Categories": "Kategorioj",
"LANGUAGE": "Anglalingve",
"More posts about": "Pli artikoloj pri...",
"Newer posts": "Pli novaj artikoloj",
"Next post"... | Proteus-tech/nikola | nikola/data/themes/base/messages/messages_eo.py | Python | mit | 909 |
from datetime import datetime
import json
import time
import re
import os
import threading
import pycurl
from array import array
from io import BytesIO
from event_treatment import *
from apscheduler.schedulers.background import BackgroundScheduler
class SchedulerEdge(object):
#instacia do objeto e inicia o escalo... | hubertokf/lupsEdgeServer | projects/old_files/Backup e arquivos N utilizados/scheduler_backup.py | Python | mit | 5,522 |
from tools import *
from tools_ast import *
@istest
def int():
assert_ast(
'1',
"""
[INT:1]
[EOF:]
"""
)
@istest
def two_blocks_int_int():
assert_ast(
'1 1',
"""
[INT:1]
[INT:1]
[EOF:]
"""
)
@istest
def string():
... | andybalaam/pepper | old/pepper1/src/test_newsyntax/test_ast_basic.py | Python | mit | 3,497 |
"""1239. Maximum Length of a Concatenated String with Unique Characters
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/
"""
from typing import List
class Solution:
def max_length(self, arr: List[str]) -> int:
def check(char_set, string: str) -> bool:
... | isudox/leetcode-solution | python-algorithm/leetcode/problem_1239.py | Python | mit | 1,306 |
import sys, os, random
from basic.constant import ROOT_PATH, DEFAULT_POS_NR
from basic.common import checkToSkip, readRankingResults, printStatus, makedirsforfile
from basic.annotationtable import readConcepts, writeConceptsTo, writeAnnotations, readAnnotationsFrom
INFO = __file__
if __name__ == '__main__':
argv... | li-xirong/jingwei | model_based/dataengine/createRefinedAnnotations.py | Python | mit | 3,560 |
#!/usr/bin/env python3
"""A matrix! Of languages!"""
import nikola.nikola
keys = ['LUXON_LOCALES', 'MOMENTJS_LOCALES', 'PYPHEN_LOCALES', 'DOCUTILS_LOCALES']
keys_short = ['language', 'luxon', 'moment', 'pyphen', 'docutils']
print('\t'.join(keys_short))
for tr in nikola.nikola.LEGAL_VALUES['TRANSLATIONS']:
if isin... | getnikola/nikola | scripts/langmatrix.py | Python | mit | 607 |
import sys
import lasagne.layers.corrmm as __cloned
from .base import bayes as __bayes
__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name)))
__all__ += [obj_name]
except TypeError:
pa... | ferrine/gelato | gelato/layers/corrmm.py | Python | mit | 390 |
#!/usr/bin/env python2.7
import argparse
from util.assemble import SPYMHeader, SPYM_HDR_LEN, disassemble
def get_args():
parser = argparse.ArgumentParser(description='Display information about SPYM format files.')
parser.add_argument('file', metavar='FILE', type=str,
help='SPYM binar... | mossberg/spym | spread.py | Python | mit | 582 |
# -*- coding: utf-8 -*-
from zope.interface import Interface, implements
from twisted.internet import protocol
from twisted.internet.defer import Deferred
from protocol.AgentRemoteControlProtocol import AgentRemoteControlProtocol
class IBasicAgentClientFactory(Interface):
def doSomething(stuff):
"""Ret... | christoforov/edusensors | edusensors/dispatchers/factory/BasicAgentClientFactory.py | Python | mit | 1,149 |
#!/usr/bin/env python
# Parse json from machine files, build hardware.json
import os
import shutil
import sys
import re
import json
import jsontools
import openscad
import syntax
from types import *
def parse_machines():
src_dir = '../'
logfile = 'openscad.log'
outfile = 'hardware.json'
oldfile = 'ba... | snhack/LogoBot | hardware/ci/parse.py | Python | mit | 14,934 |
import os
class Config(object):
DEBUG = False
MONGODB_HOST = "mongodb://127.0.0.1:27017/iky-ai"
# Intent Classifier model details
MODELS_DIR = "model_files/"
INTENT_MODEL_NAME = "intent.model"
DEFAULT_FALLBACK_INTENT_NAME = "fallback"
DEFAULT_WELCOME_INTENT_NAME = "init_conversation"
U... | alfredfrancis/ai-chatbot-framework | config.py | Python | mit | 835 |
import os
import argparse
import boto
from boto.s3 import key
parser = argparse.ArgumentParser(description="Upload files to Github")
parser.add_argument("version", help="Version of upload")
args = parser.parse_args()
c = boto.connect_s3()
b = c.get_bucket('files.projecthawkthorne.com')
releases = [
'hawkthorne-w... | TRex22/hawkthorne-journey | scripts/symlink.py | Python | mit | 593 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
cmap = ListedColormap(['r', 'g', 'b'])
points = np.array([x, y]).T
p1 = points[:300,:]
p2 = points[300:,:]
... | sysid/nbs | ml_old/Prognose/plt.py | Python | mit | 505 |
#!/usr/bin/env python
import argparse
import sys
import subprocess
import os
import glob
import shutil
import fileinput
# This script blasts the entries of a fasta file,
# provided they're over the length threshold
# It also concatenates the results and does some minor filtering
humantaxid = '9606'
# --------------... | RabadanLab/Pandora | scripts/blast_wrapper.py | Python | mit | 11,197 |
# for python 3
# You'll need to customize this according to your needs. Proper orientation of
# the kinect is vital; if participants are able to maintain their head or wrists
# continuously inside the word rects, they will repeatedly trigger the collision
# detection
from pykinect2 import PyKinectV2
from pykinect2.PyKi... | jgerschler/ESL-Games | Kinect/Word Translations/WordTranslationsFullScreen.py | Python | mit | 8,514 |
# Created by PyCharm Pro Edition
# User: Kaushik Talukdar
# Date: 24-04-2017
# Time: 05:03 PM
# What if we need both Car() & ElectricCar() in this program? Importing both individually will be a long cut if we can
# import the entire module in 1 go.
import e_car
... | KT26/PythonCourse | 8. Class/14.py | Python | mit | 534 |
"""
Django settings for tasktracker project.
Generated by 'django-admin startproject' using Django 1.9.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... | PeriodicTaskTracker/tasktracker-django | tasktracker/settings.py | Python | mit | 3,689 |
"""GPML backend for Gaussian processes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from pprint import pprint
# MATLAB scripts
_gp_train_epoch = """
hyp = minimize(hyp, @gp, -{n_iter:d}, {inf}, {mean}, {cov}, {lik}, X_t... | alshedivat/kgp | kgp/backend/gpml.py | Python | mit | 8,999 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from numpy import *
import time
# import igraph.vendor.texttable
# from texttable import Texttable
# 协同过滤推荐算法主要分为:
# 1、基于用户。根据相邻用户,预测当前用户没有偏好的未涉及物品,计算得到一个排序的物品列表进行推荐
# 2、基于物品。如喜欢物品A的用户都喜欢物品C,那么可以知道物品A与物品C的相似度很高,而用户C喜欢物品A,那么可以推断出用户C也可能喜欢物品C。
# 不同的数据、不同的程序猿写出的协同过滤推荐算法不同,但其核心是一... | woniukaibuick/DA-ML | src/com/valar/movierec/myRec.py | Python | mit | 7,671 |
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import ServerFactory
class ParseData(object):
def __init__(self):
self.dispatch_dict = {'REGISTER': self.register, 'CHAT': self.chat, 'UNREGISTER': self.unregister }
self.clients = {}
def dispatch(self, cmd, conten... | ersran9/chat | server.py | Python | mit | 3,516 |
import numpy as np
from faps.paternityArray import paternityArray
from faps.genotypeArray import genotypeArray
from faps.transition_probability import transition_probability
from faps.incompatibilities import incompatibilities
from warnings import warn
def paternity_array(offspring, mothers, males, mu=1e-12, missing_p... | ellisztamas/faps | faps/paternity_array.py | Python | mit | 12,149 |
import _plotly_utils.basevalidators
class GridcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="gridcolor", parent_name="layout.ternary.aaxis", **kwargs
):
super(GridcolorValidator, self).__init__(
plotly_name=plotly_name,
par... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/ternary/aaxis/_gridcolor.py | Python | mit | 428 |
# -*- coding: utf-8 -*-
# pep8: disable-msg=E501
# pylint: disable=C0301
from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from packagesample import __version__
# from packagesample import log
from packagesample.modules import * # noqa
import __builtin__
app = Flask(__name__)
Bootstr... | lovato/machete | machete/templates/bootstrap/packagesample/start.py | Python | mit | 618 |
from optparse import OptionParser
from easy_todo.storage.sqlite3 import SQLite3Storage
from easy_todo.output import SimpleTextOutput
def createOptionParser():
parser = OptionParser()
addCommands(parser)
addCommandsArguments(parser)
return parser
def addCommands(parser):
parser.add_option("-a", "... | wojtekzozlak/easy_todo | easy_todo/options.py | Python | mit | 2,494 |
# -*- coding: utf-8 -*-
"""Main modules.
Start from main()
"""
import configparser
import os.path
import sys
from configobj import ConfigObj
from kaidoku.command import command
from kaidoku.help import welcommessage
from kaidoku.misc import openappend
# Kaidoku starts here
def main(argv=sys.argv[1:]):
"""Main... | sekika/kaidoku | kaidoku/main.py | Python | mit | 5,923 |
from rest_framework import status
from django.http import JsonResponse
from api.models import Tokens
class AuthMiddleware(object):
def process_request(self, request):
try:
token = request.META['HTTP_AUTHORIZATION']
object = Tokens.objects.get(token=token)
request.api_u... | SWE574-Nerds/friendly-eureka | backend/eureka/api/middleware/AuthMiddleware.py | Python | mit | 491 |
__author__ = 'Nicole'
import json
import random
import time
GREEN = 'green'
CONSERVATIVE = 'conservative'
LIBERAL = 'liberal'
LIBERTARIAN = 'libertarian'
MAX_CACHED_POINTS = 400
STATES = [GREEN, CONSERVATIVE, LIBERAL, LIBERTARIAN]
class MyStates:
def __init__(self):
self.currentStates = [CurrentStateOf... | minicole/elpolitico | elpolitico/elpolitico/MyState.py | Python | mit | 2,660 |
#!/usr/bin/env python
#
# Copyright (c) 2010 Christian Hergert <chris@dronelabs.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 ri... | chergert/yosemite | yosemite/log.py | Python | mit | 1,512 |
## 3. Resilient Distributed Data Sets (RDDs) ##
raw_data = sc.textFile("daily_show.tsv")
raw_data.take(5)
## 6. Pipelines ##
daily_show = raw_data.map(lambda line: line.split('\t'))
daily_show.take(5)
# Hit check to see the output
## 8. ReduceByKey() ##
tally = daily_show.map(lambda x: (x[0], 1)).reduceByKey(lambd... | vipmunot/Data-Analysis-using-Python | pySpark/Introduction to Spark-122.py | Python | mit | 832 |
import unittest
from app.sublime_command import SublimeCommand
from tests.view_spy import ViewSpy
from tests.region_stub import EmptyRegionStub, RegionStub
class TestSublimeCommand(unittest.TestCase):
def setUp(self):
# SUT
self.settings = SettingsStub()
self.settings.separator = ''
... | ldgit/hours-calculator | tests/test_sublime_command.py | Python | mit | 4,535 |
# -*- coding: utf-8 -*-
import logging
from twisted.internet import reactor, endpoints
from helper.site import YuzukiSite
from helper.resource import YuzukiResource
from route import ROUTE
class Main(YuzukiResource):
isLeaf = False
def __init__(self):
YuzukiResource.__init__(self)
for path ... | Perlmint/Yuzuki | main.py | Python | mit | 508 |
#!/usr/bin/env python3
import logging
from portingdb import htmlreport
level = logging.INFO
logging.basicConfig(level=level)
sqlite_path = 'portingdb.sqlite'
application = htmlreport.create_app(directories=['data'], cache_config=None)
if __name__ == '__main__':
from elsa import cli
cli(application, base_ur... | fedora-python/portingdb | elsasite.py | Python | mit | 355 |
import logging
from decimal import Decimal
from django.conf import settings
from exchange.models import Currency, ExchangeRate
from exchange.utils import update_many, insert_many
logger = logging.getLogger(__name__)
class BaseAdapter(object):
"""Base adapter class provides an interface for updating currency an... | metglobal/django-exchange | exchange/adapters/__init__.py | Python | mit | 3,554 |
# vim:ts=4:sts=4:sw=4:expandtab
import ipaddr
from satori.ars.server import server_info
from satori.core.dbev import Events
from satori.core.models import Role, LoginFailed, InvalidLogin, login_ok, password_ok, password_crypt, password_check, password_rehash_old
from satori.core.models import LoginFailed
@Export... | zielmicha/satori | satori.core/satori/core/entities/Machine.py | Python | mit | 3,243 |
#! /usr/bin/env python
# coding: utf-8
import subprocess
import os
word=raw_input()
for filename in os.listdir("."):
print filename
shell_line = "jar tf %s | grep %s" % (filename,word)
p = subprocess.Popen(shell_line, shell=True)
p.wait()
#-guice-3.0.jar
| 0ED/Toy | p2p_network/kademlia/lib/find.py | Python | mit | 264 |
#!/usr/bin/env python
class Result(object):
STATUS_ERROR = "error"
STATUS_SUCCESS = "success"
_default_code = 500
def __init__(self, status, code=_default_code, data={}, msg=""):
self._status = status
self._code = code
self._data = data
self._msg = msg
def status(s... | sadikovi/forkfeed | src/result.py | Python | mit | 1,118 |
# Count number of bits needed to be flipped to convert A to B
def count_bits_flip(a, b):
# XOR a and b to get 1 on opposite value bit position
c = a ^ b
# initialise the counter for 1
count = 0
# count the number of 1s while there is 1 in a ^ b
while c != 0:
count += 1
c &= (... | anubhavshrimal/Data_Structures_Algorithms_In_Python | Bit_Manipulation/Count_Bits_Flip_A_B.py | Python | mit | 425 |
from .square import Square
class Tax(Square):
'''
Represents the Income Tax and Super Tax squares.
'''
def __init__(self, name, tax):
'''
The 'constructor'.
'''
super().__init__(name)
self.tax = tax
def landed_on(self, game, player):
'''
Ca... | richard-shepherd/monopyly | monopyly/squares/tax.py | Python | mit | 423 |
#!/bin/python3
# -*- coding: utf-8 -*-
from runner import Runner
import numpy as np
import matplotlib.pyplot as plt
class Perihelion(Runner):
def setup(self):
self['number of years'] = 100
self['do save results'] = False
self['do save any results'] = False
self['use all planets'] =... | Caronthir/FYS3150 | Project3/analysis/perihelion.py | Python | mit | 1,597 |
"""Helpers to deal with Cast devices."""
from __future__ import annotations
from typing import Optional
import attr
from pychromecast import dial
from pychromecast.const import CAST_TYPE_GROUP
from pychromecast.models import CastInfo
@attr.s(slots=True, frozen=True)
class ChromecastInfo:
"""Class to hold all da... | rohitranjan1991/home-assistant | homeassistant/components/cast/helpers.py | Python | mit | 4,912 |
#!/usr/bin/env python
from flask import Flask, jsonify, send_file, send_from_directory
import db
app = Flask(__name__)
# Special route because "/" technically redirects to "index.html".
@app.route('/')
def index():
return send_file('static/index.html')
@app.route('/api/total')
def total_logs():
data = {
... | gt-big-data/gtpd-crawler | server.py | Python | mit | 2,774 |