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 |
|---|---|---|---|---|---|
# coding: utf-8
from unittest import TestCase
#import os
#import sys
#root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
#sys.path.insert(0, root)
from test.util import GRAB_TRANSPORT, ignore_transport, only_transport
from test.server import SERVER
from grab.selector import KitSelector
from grab impo... | subeax/grab | test/case/selector_kit.py | Python | mit | 3,668 |
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '_project.settings')
app = Celery('_project')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
| samitnuk/online_shop | _project/celery.py | Python | mit | 269 |
"""Test adding external statistics from Tibber."""
from unittest.mock import AsyncMock
from homeassistant.components.recorder.statistics import statistics_during_period
from homeassistant.components.tibber.sensor import TibberDataCoordinator
from homeassistant.util import dt as dt_util
from .test_common import CONSUM... | rohitranjan1991/home-assistant | tests/components/tibber/test_statistics.py | Python | mit | 2,649 |
from django.contrib import admin
from django.forms import ModelChoiceField, ModelForm, Textarea
from questionnaire.models import *
from django.core.exceptions import ValidationError
from django.forms.models import BaseInlineFormSet
from questionnaire import admin_helper
############################################### ... | mitchsmith/qd_screener | questionnaire/admin.py | Python | mit | 7,839 |
from django.db import models
from pyconuy2012.settings import LANGUAGES
class Background(models.Model):
title = models.CharField(max_length=40)
description = models.TextField()
place = models.CharField(max_length=20)
author = models.CharField(max_length=30, null=True, blank=True)
language = models... | sophilabs/pyconuy-site | pyconuy2012/background/models.py | Python | mit | 815 |
import unittest
import acpc_python_client as acpc
from cfr.main import Cfr
KUHN_POKER_GAME_FILE_PATH = 'games/kuhn.limit.2p.game'
KUHN_BIG_DECK_POKER_GAME_FILE_PATH = 'games/kuhn.bigdeck.limit.2p.game'
KUHN_BIG_DECK_2ROUND_POKER_GAME_FILE_PATH = 'games/kuhn.bigdeck.2round.limit.2p.game'
LEDUC_POKER_GAME_FILE_PATH = ... | JakubPetriska/poker-cfr | test/cfr_tests.py | Python | mit | 1,756 |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.debug = True
app.run(host = '0.0.0.0', port = 5000)
| SahSih/ARStreaming360Display | RealTimeVideoStitch/realtime-panorama-stitching/hello.py | Python | mit | 188 |
# output from elife04493.xml
expected = [
{
"mime-subtype": "mov",
"mimetype": "video",
"xlink_href": "elife04493v001.mov",
"content-type": "glencoe play-in-place height-250 width-310",
"component_doi": "10.7554/eLife.04493.007",
"type": "media",
"sibling_ordi... | elifesciences/elife-tools | tests/fixtures/test_media/content_07_expected.py | Python | mit | 7,974 |
# Programmer: Noah Osterhout
# Date: September 30th 2016 1:40PM EST
# Project: Kirby_Physics.py
#Ask what Problem they will be using
print()
print("This Program will find the misisng Variables using the three known ones and using PEMDAS")
print()
beetles_mem = input("What Beetles member will you be using? ")... | NoahFlowa/CTC_Projects | Osterhout_Python/Kirby_Physics.py | Python | mit | 1,794 |
"""
Django settings for cfg project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... | slezica/bleg | cfg/settings.py | Python | mit | 2,064 |
'''
Created on 17 Jun 2015
Don't be late!
@author: NoNotCar
'''
import Entity
import Img
import pygame
class Vehicle(Entity.Entity):
vspeed = 16
img = Img.blank32
name = "Vehicle"
pickup = False
solid = True
boat = False
def __init__(self, x, y, p):
self.p = p
self.x = x
... | NoNotCar/monolith | Monolith/Vehicles.py | Python | mit | 2,659 |
import csv
from collections import defaultdict
class DataIO:
'''Responsible for reading data from whatever source (CSV, DB, etc),
normalizing indexes for processing and writing results in denormalized form.
Also it provides an access to translation dictionaries between external and internal i... | ksavenkov/recsys-001 | recsys/dataset.py | Python | mit | 6,782 |
#!/usr/bin/env python3
"""Create a recording with arbitrary duration.
The soundfile module (https://PySoundFile.readthedocs.io/) has to be installed!
"""
import argparse
import tempfile
import queue
import sys
import sounddevice as sd
import soundfile as sf
import numpy # Make sure NumPy is loaded before it is used... | spatialaudio/python-sounddevice | examples/rec_unlimited.py | Python | mit | 2,826 |
import _plotly_utils.basevalidators
class ColumnValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(self, plotly_name="column", parent_name="table.domain", **kwargs):
super(ColumnValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/table/domain/_column.py | Python | mit | 437 |
"""
Tests for Molecular Graph data structures.
"""
from __future__ import division
from __future__ import unicode_literals
__author__ = "Han Altae-Tran and Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import unittest
import os
import sys
import numpy as np
from deepche... | ktaneishi/deepchem | deepchem/feat/tests/test_mol_graphs.py | Python | mit | 6,110 |
#! /usr/bin/env python3
a = [1, 3, 4, 5, 8]
a.append(23) #adding element at last position of list.
a.insert(0,23) #inserting at first position of list.
a.insert(2,21) #inserting at second position of list.
print("list : ", a)
del a[-1] #delete last element.
a.remove(3) #delete element from list.
print("deletion opear... | Skchoudhary/python_programm | list.py | Python | mit | 551 |
from django.contrib import admin
from .models import Produto, Foto
from rest_framework.authtoken.admin import TokenAdmin
TokenAdmin.raw_id_fields = ('user',)
# Register your models here.
# admin.site.register(Bucketlist)
admin.site.register(Produto)
admin.site.register(Foto)
| alexiwamoto/django-rest-api | rest_api/admin.py | Python | mit | 279 |
from PyQt4.QtCore import QObject, pyqtSignal
from ems.notification.abstract import FormNotifier
from ems.qt4.gui.widgets.balloontip import BalloonTip
from ems import qt4
from ems.qt4.util import variant_to_pyobject as py
class BalloonFormNotifier(FormNotifier):
def __init__(self):
self._widgetMap = {... | mtils/ems | ems/qt4/gui/notification/balloon_form_notifier.py | Python | mit | 2,764 |
from foo import bar # noqa
from foo import bar as bar2, xyz # noqa
from foo.baz import bang # noqa
from . import x
import example as example2 # noqa
import foo.baz # noqa
| caioariede/pyq | testfiles/imports.py | Python | mit | 177 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last-Updated : <2013/08/18 22:47:11 by samui>
import sys,os
def mkdir(folder):
if not os.path.isdir(folder):
os.system("mkdir {0}".format(folder))
if __name__ == "__main__":
data_file = os.path.abspath(sys.argv[1])
root,ext = os.path.splitext(os.p... | samui13/Gnuplot3D | script/split3D.py | Python | mit | 1,765 |
# -*- coding: utf-8 -*-
from .. import server, utils
class Memcached(server.Server):
binary = 'memcached'
def init(self, **kwargs):
self.binary = utils.find_binary(kwargs.get('memcached_bin', self.binary))
assert 'ip' in kwargs, "memcached servers requires <ip> option"
self.ip = kwa... | mialinx/testenv | testenv/contrib/memcached.py | Python | mit | 510 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-02 22:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('database', '0039_auto_20170902_1834'),
]
operations = [
migrations.RemoveField(
... | ACLARKNET/aclarknet-database | aclarknet/database/migrations/0040_auto_20170902_1841.py | Python | mit | 694 |
"""
Module: plugin.py
Author: Rinke Hoekstra
Created: 2 October 2012
Copyright (c) 2012, Rinke Hoekstra, VU University Amsterdam
http://github.com/Data2Semantics/linkitup
"""
from flask.ext.login import login_required
import re
from linkitup import app
from linkitup.util.baseplugin import plugin, SPARQLPl... | Data2Semantics/linkitup | linkitup/bio2rdf/plugin.py | Python | mit | 1,736 |
from flask import Flask
from flask import request
from subprocess import call
import git, json, os, sys
newname = "gitlistener"
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6') #Loading a 3rd party library C
buff = create_string_buffer(len(newname)+1) #Note: One larger ... | WilliamMarti/gitlistener | gitlistener.py | Python | mit | 1,001 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from funcy import partial
from canopen_301_402.constants import *
from canopen_301_402.async.async_chain import AsyncChain
from canopen_301_402.async.sdo_write_object import SdoWriteObject
from canopen_301_402.can402.ops.notify_new_target import NotifyNewTarget
import s... | xaedes/canopen_301_402 | src/canopen_301_402/can402/ops/set_target.py | Python | mit | 1,247 |
#here we can use wrapper to accerlate the whole process, since many text may be same, we can save the intermediate results
import operator
from math import log10
import re
import string
import random
import heapq
"""First Part:
Word Segmentation"""
def memory(f):
#memorize function f
table = {}
def fme... | zkmake520/ProbabilisticModel | NGram/NGram.py | Python | mit | 7,676 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-01 18:03
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | rymcimcim/django-foosball | game/migrations/0001_initial.py | Python | mit | 2,887 |
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2013, 2014 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>
# Copyright (c) 2013 James King <james@agentultra.com>
# Copyright (c) 2013, 2014 Bob Tolbert <bob@t... | algernon/hy | hy/compiler.py | Python | mit | 90,185 |
# coding=utf-8
from string import ascii_uppercase
import flask_featureflags
from app.main import main
from flask import render_template, request
from app.helpers.search_helpers import get_template_data
from app import data_api_client
import re
try:
from urlparse import urlparse, parse_qs
except ImportError:
fr... | mtekel/digitalmarketplace-buyer-frontend | app/main/suppliers.py | Python | mit | 2,705 |
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from neupy.datasets import reber
from neupy.utils import asfloat, tensorflow_session
from neupy.exceptions import LayerConnectionError
from neupy.layers.recurrent import clip_gradient
from neupy import layers, algorithms, i... | itdxer/neupy | tests/layers/test_recurrent.py | Python | mit | 10,661 |
import unittest
import bolt.utils._utfiles as utfiles
class TestFileDeleter(unittest.TestCase):
def setUp(self):
self.sourcedir = 'C:\\sourcedir'
self.pattern = '*.py'
self.recursive = True
self.subject = FileFinderSpy(self.sourcedir, self.pattern, self.recursive)
return ... | abantos/bolt | test/test_utils/test_utfiles.py | Python | mit | 1,917 |
"""Main entry point
"""
from pyramid.config import Configurator
from sqlalchemy import create_engine
from models import initialize_sql
db_name = "spacehub"
db_url = "sqlite:////tmp/test.db"
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include("cornice")
config.sca... | jeid64/Crawdad | crawdad/__init__.py | Python | mit | 435 |
#!/usr/bin/env python
from pkg_resources import require
from . import defer
__version__ = '1.1.3'
| SentimensRG/txCelery | txcelery/__init__.py | Python | mit | 100 |
from __future__ import absolute_import
from collections import defaultdict
import rdflib
from go_data import goa
def load_gene_terms(goa_path, go_owl_path):
"""
Load GO information related to a certain gene annotation.
A GO annotation file describes the GO terms related to each gene
in a specific ... | abuchanan/go_data | go_data/__init__.py | Python | mit | 2,074 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import SocketServer
from lib import const
class PowerIRSendHandler(SocketServer.StreamRequestHandler):
def handle(self):
# print "connected from:", self.client_address
sent_data = ""
while True:
data = self.req... | nmatsui/wasted_energy_of_tv_iot | power_ir_send_server.py | Python | mit | 939 |
import argparse
from . import dictionary_sample, generate_codenames
def main():
parser = argparse.ArgumentParser(
prog="codenamegenerator", description="Code name generator"
)
parser.add_argument("num", type=int, default=1)
parser.add_argument("-c", "--capitalize", action="store_true", defau... | mariocesar/namegenerator | codenamegenerator/__main__.py | Python | mit | 1,218 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class DependentHostedNumberOrde... | tysonholub/twilio-python | tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py | Python | mit | 5,011 |
__author__ = 'shkiper'
from . import morph
def get_best_parse(word: str, part: str):
possibilities = [x for x in morph.parse(word) if x.tag.POS == part]
if len(possibilities) == 0:
return None
else:
return max(possibilities, key=lambda x: (x.score, x.word))
WHO_PARSE = get_best_parse('кт... | hatbot-team/hatbot_resources | preparation/lang_utils/morphology/replace_with_gap.py | Python | mit | 2,900 |
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
class TallyUser(AbstractUser):
public = models.BooleanField(default=True)
balance = models.FloatField(default=0.0)
class Item(models.Model):
value = models.FloatField(default=1.... | vIiRuS/Tallyr | tally_sheet/models.py | Python | mit | 939 |
#!/usr/bin/python
"""A script to get information from MrTijn's new server so I (MrMadsenMalmo) can display it
on a website
"""
__author__ = "MrMadsenMalmo - Fredrik A. Madsen-Malmo & Tijndagamer"
import os
import time
import re
import datetime
def main():
dataList = []
dataList.append(os.popen("uptime").re... | FredrikAugust/server-status | statuspagescript.py | Python | mit | 2,247 |
#!/usr/bin/python
# pam_authenticate.py: a script to check a user's password against PAM.
# part of the pywiki project, see https://github.com/pepaslabs/pywiki
# written by jason pepas, released under the terms of the MIT license.
# usage: pipe a password into this script, giving the username as the first argument.
#... | pepaslabs/pywiki | pam_authenticate.py | Python | mit | 684 |
from django.conf.urls import patterns, url
urlpatterns = patterns(
'mtr.utils.views',
url(r'^model/(?P<name>.+)/pk/(?P<pk>\d+)$',
'model_label', name='model_label')
)
| mtrgroup/django-mtr-utils | mtr/utils/urls.py | Python | mit | 186 |
# -*- coding: utf-8 -*-
from timesheet.commands import Command
from timesheet.models import Subject
__author__ = 'vahid'
class SubjectsCommand(Command):
name = 'subjects'
description = 'Print all subjects'
def do_job(self):
print('\n'.join(Subject.all_titles()))
| pylover/timesheet | timesheet/commands/subjects.py | Python | mit | 286 |
# -*- coding: utf-8 -*-
'''
Weibull Estimators
-------
A small library of tools for fitting weibull pdfs to data
'''
from __future__ import division
import scipy.optimize as spyopt
from scipy.special import gamma
import numpy as np
#Least Squares
def least_sq(data, x):
'''Least squares fitting of parameters ... | wrobstory/climatic | climatic/weibull_est.py | Python | mit | 1,727 |
def mathem(a,b):
a = a/2
b = b+10
print(a+b)
num1 = 100
num2 = 12
mathem(num1,num2)
print num1
print num2
def mathem2():
print(num1+num2)
mathem2()
print a
print b | janusnic/py-21v | scope/2.py | Python | mit | 188 |
#!/usr/bin/env python
import logging
from os import environ
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
stream_handler = logging.StreamHandler()
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(stream_handler)
app.config['SQLALCHEMY_DATABASE_URI'] = (environ.get('... | okfn/hashtag-listener | app.py | Python | mit | 519 |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# Copyright (c) 2009, 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
# d... | rwl/traitsbackendpyjamas | enthought/traits/ui/pyjd/__init__.py | Python | mit | 1,896 |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | onshape-public/onshape-clients | python/onshape_client/oas/models/callback.py | Python | mit | 4,774 |
# USAGE
# python color_kmeans.py --image images/jp.png --clusters 3
# import the necessary packages
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import utils
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "-... | DarkShadow0/Content-Based-Image-Retrieval | abhi/color_kmeans.py | Python | mit | 1,211 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
import logging
from calamari_client import LOG, CalamariAPIv1Connection, CalamariAPIv2Connection
CALAMARI_HOST = 'http://127.0.0.1/'
CALAMARI_USERNAME = 'root'
CALAMARI_PASSWORD = 'root'
def add_stdout_handler(logger):
logger.setLevel(logg... | Blahhhhh/python-calamari-client | demo.py | Python | mit | 5,490 |
import pygame
pygame.mixer.init()
sound_object = pygame.mixer.Sound("sound/beep1.ogg")
sound_object.set_volume(1)
| sontung/pick_a_number | sound/click_sound.py | Python | mit | 116 |
def triNum(thresh):
a, n = 1, 1
l = [a]
while 1:
n += 1
a += n
l.append(a)
if a > thresh:
break
return l
def getData():
with open("data.042") as f:
for l in f.readlines():
l = l.split(',')
l = [i[1:-1] for i in l]
... | liuyang1/euler | 042.py | Python | mit | 566 |
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from datetime import datetime
from sqlalchemy.exc import DisconnectionError
import web
import config
engine = sqlalchemy.create_engine(config.dbconn, echo=False, co... | onlytiancai/warning-collector | src/db.py | Python | mit | 4,385 |
# -*- coding: utf-8 -*-
"""Tests for the services module."""
# These tests require pytest, and mock. Mock comes with Python 3.3, but has
# also been backported for Python 2.7. It is available on pypi.
from __future__ import unicode_literals
import pytest
from soco.exceptions import SoCoUPnPException
from soco.servi... | KennethNielsen/SoCo | tests/test_services.py | Python | mit | 10,298 |
#!/usr/bin/env python
# coding=utf-8
import json
import sys
data = {
'g1': {
'hosts': [
'172.17.0.2'
]
}
}
with open('w.log', 'w') as f:
f.write(str(sys.argv))
print json.dumps(data)
| tao12345666333/Talk-Is-Cheap | ansible/group.py | Python | mit | 227 |
"""
WSGI config for trialrun project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | mpirnat/hackday | hackday/wsgi.py | Python | mit | 1,137 |
import re
useless_words = ['Inc', 'Corporation', 'Company', 'Corp', 'Co', 'Energy', '&', 'The', '.com', "Inc.", "Corp.", "Co.", "of", "Ltd.", "Ltd"]
with open('companies.txt', 'r') as f:
companies = f.readlines()
new_companies = []
for company in companies:
company = company[:-1]
company_words = company.... | maxdrib/Trump-Twitter | keywords/parse_companies.py | Python | mit | 633 |
from abc import *
class PlotStyle(metaclass=ABCMeta):
"""The base interface for all ShakeMap formats/styles
It is a simple decorator and therefore allows arbitrarily deep nesting of
different styles.
>>> # `Style1` will be applied first, then `Style2`, ...
>>> style = Style1(Style2(Style3()))
... | TGM-HIT/eqep-api | eqep/shakemap/display/plotstyle.py | Python | mit | 898 |
import json
from PIL import Image, ImageFont, ImageDraw
with open('./config/nodes.json') as data_file:
data = json.load(data_file)
gray = (200, 200, 200)
black = (0,0,0)
lightblue = (225, 255, 255)
darkblue = (185, 255, 255)
img = Image.new("RGBA", (400,400), 128)
usr_font = ImageFont.truetype("./fonts/Arial.t... | Ibuprofen/gizehmoviepy | node_positions_image.py | Python | mit | 1,603 |
from django.contrib import admin
from .models import SnmpDevice, SnmpDeviceMessage, PingHistory
# Register your models here.
class SnmpDeviceAdmin(admin.ModelAdmin):
fields = [
'name', 'hostname', 'status', 'ping_mode', 'ping_port',
'snmp_template', 'snmp_port', 'snmp_community', 'snmp_system_con... | MikaelSchultz/dofiloop-sentinel | sentinel/device/admin.py | Python | mit | 1,293 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | jeremiedecock/snippets | python/pyqt/pyqt4/fullscreen.py | Python | mit | 2,472 |
ranged_attacker = "ranged attacker"
melee_attacker = "melee attacker"
healer = 'healer'
dismantling_attacker = 'dismantler'
general_attacker = 'general attacker'
tough_attacker = 'tough guy'
work_and_carry_attacker = 'multi-purpose attacker'
civilian = 'civilian'
scout = 'scout'
| daboross/screeps-warreport | warreport/constants.py | Python | mit | 280 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from tipi.compat import unicode
from tipi.html import HTMLFragment
__all__ = ('Replacement', 'replace')
class Replacement(object):
"""Replacement representation."""
skipped_tags = (
'code', 'kbd', 'pre', 'samp', 'script', 'style', 't... | honzajavorek/tipi | tipi/repl.py | Python | mit | 2,146 |
#! /usr/bin/env python
############################################################
# Program is part of PySAR v1.0 #
# Copyright(c) 2013, Heresh Fattahi #
# Author: Heresh Fattahi #
#####################################################... | mohseniaref/PySAR-1 | pysar/_remove_surface.py | Python | mit | 4,681 |
# -*- coding:utf8 -*-
from scrapy import Request
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.loader.processors import Join
from scrapy.loader import ItemLoader
from scrapy.selector import HtmlXPathSelector, Selector
from zadolbali.items import StoryItem
cla... | alexeyqu/zadolbali_corpus | crawler/zadolbali/zadolbali/spiders/stories.py | Python | mit | 1,809 |
# coding=utf-8
from rutermextract import TermExtractor
term_extractor = TermExtractor()
text = u'Съешь ещё этих мягких французских булок да выпей же чаю.'
for term in term_extractor(text):
print term.normalized, term.count | igor-shevchenko/rutermextract | example.py | Python | mit | 274 |
import json
import socket
from comms_manager import CommsManager
from constants import *
class BoardManager:
def __init__(self, args):
self.server_address = (args.IP, args.PORT)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(15)
self.sock.connec... | TeamProxima/predictive-fault-tracker | board/board_manager.py | Python | mit | 2,638 |
class GeneratorAdapter:
def visit_selector_view(self, view):
pass
def visit_selector_object(self, object, property):
pass
def visit_selector_fk_object(self, object, property, fk_properties):
pass
def visit_view(self, view):
pass
def visit_page(self, page):
... | theshammy/GenAn | src/main/common.py | Python | mit | 1,218 |
'''
Problem 1: Counting Vowels
'''
vowels = ['a', 'i', 'o', 'u', 'e']
count = 0
for i in s:
if i in vowels:
count +=1
print count
'''
Problem 2: Counting 'bob's
'''
s = 'azcbobobegghakl'
def count_word_parts(word_part, word):
'''
Function counts number times word_part
occurs in all woed
'''
... | maistrovas/My-Courses-Solutions | MITx-6.00.1x/ProblemSet1/PS1.py | Python | mit | 864 |
from collections import defaultdict
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
indices = defaultdict(list)
for i, x in enumerate(nums):
indices[x].append(i)
for _, v ... | shenfei/oj_codes | leetcode/python/n219_Contains_Duplicate_II.py | Python | mit | 659 |
# -*- coding: utf-8 -*-
from django.core.paginator import Paginator, InvalidPage
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseServerError, Http404
def paginator_parse(request, obj, item_per_page=1):
paginator = Paginator(obj, item_per_page)
try:
page_number = int(... | rsj217/dmblog | dmblog/utils/paginatorer.py | Python | mit | 1,092 |
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage, EmailMultiAlternatives
import base64
from postmark.core import PMMail, PMBatchMail
class PMEmailMessage(EmailMessage):
de... | themartorana/python-postmark | postmark/django_backend.py | Python | mit | 6,739 |
from castle.main import CastleGameLoop
if __name__ == "__main__":
castle = CastleGameLoop()
castle.start_game() | evasilchenko/castle | start_castle.py | Python | mit | 121 |
# -*- coding: utf-8 -*-
"""
This is part of HashBruteStation software
Docs EN: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station_en
Docs RU: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Integration tests f... | hack4sec/hbs-cli | tests/integration/test_HashlistsByAlgLoaderThread.py | Python | mit | 8,236 |
# -*- coding: utf-8 -*-
from md_preview import *
| simple/md-preview | md_preview/__init__.py | Python | mit | 49 |
import subprocess as sp
import os
import stat
import shutil
import tempfile
import pwd
import time
import json
import yaml
_NORMUSER = 'normuser'
_RUNNER_LOG_FILE_FOR_ROOT = '/root/.jobber-log'
_RUNNER_LOG_FILE_FOR_NORMUSER = '/home/{0}/.jobber-log'.\
format(_NORMUSER)
_CONFIG_PATH = '/etc/jobber.conf'
_OLD_CONFIG... | dshearer/jobber | platform_tests/keywords/testlib.py | Python | mit | 27,023 |
# -*- coding: utf8 -*-
"""
The ``parrot plugin
====================
Some can of russian parrot, that act like a russian roulette, randomly repeating some sentence.
May enter in berzek mode, but it is very rare.
"""
| salas106/lahorie | lahorie/plugins/parrot.py | Python | mit | 238 |
import antk.core.loader as loader
import numpy as np
import scipy.sparse as sps
"""
:any:`center`
:any:`l1normalize`
:any:`l2normalize`
:any:`pca_whiten`
:any:`tfidf`
:any:`unit_variance`
"""
x = np.array([[0.0,0.0,6.0],
[2.0,4.0,2.0],
[2.0,6.0,0.0]])
y = sps.csr_matrix(x)
# numpy.testi... | aarontuor/antk | test/test_transforms.py | Python | mit | 4,376 |
import matplotlib.pyplot as plt
import numpy as np
from plotData import *
from mapFeature import *
def plot_decision_boundary(theta, X, y):
plot_data(X[:, 1:3], y)
if X.shape[1] <= 3:
# Only need two points to define a line, so choose two endpoints
plot_x = np.array([np.min(X[:, 1]) - 2, np.m... | nsoojin/coursera-ml-py | machine-learning-ex2/ex2/plotDecisionBoundary.py | Python | mit | 1,180 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# downloadpkg.py file is part of spman
#
# spman - Slackware package manager
# Home page: https://github.com/MyRequiem/spman
#
# Copyright (c) 2018 Vladimir MyRequiem Astrakhan, Russia
# <mrvladislavovich@gmail.com>
# All rights reserved
# See LICENSE for details.
"""
... | MyRequiem/spman | src/downloadpkg.py | Python | mit | 18,965 |
from common import bounty, peers, settings
from common.safeprint import safeprint
from multiprocessing import Queue, Value
from time import sleep, time
import pickle
def sync():
from multiprocessing import Manager
man = Manager()
items = {'config': man.dict(),
'peerList': man.list(),
... | gappleto97/Senior-Project | main.py | Python | mit | 2,530 |
import numpy as np
def distance(x, y, maxX, maxY):
"""get the euclidian distance"""
xDis = (x-maxX/2)**2
yDis = (y-maxY/2)**2
distance = np.sqrt(xDis + yDis)
return distance
class TrainingSetGen:
def __init__(self):
#[Unit name(s), player number, unitMultiplyer]
sel... | peixian/Ultralisk | glaive/trainingSetGen.py | Python | mit | 2,419 |
# -*- coding: utf-8 -*-
from dp_tornado.engine.helper import Helper as dpHelper
class IndexingHelper(dpHelper):
@property
def partition(self):
return self.hash
@property
def hash(self):
return 'HASH'
@property
def sort(self):
return self.range
@property
def... | why2pac/dp-tornado | dp_tornado/helper/web/aws/dynamodb/table/indexing.py | Python | mit | 357 |
from pathlib import Path
import xarray
KEY = 'imgs' # handle to write inside the output file
CLVL = 1 # ZIP compression level
def writeframes(outfn: Path, img: xarray.DataArray):
"""writes image stack to disk"""
assert img.ndim == 3
if outfn is None:
return
outfn = Path(outfn).expanduser(... | scivision/raspberrypi_raw_camera | pibayer/io.py | Python | mit | 1,418 |
import ethereum.pruning_trie as pruning_trie
from ethereum.db import EphemDB
from ethereum.refcount_db import RefcountDB
import rlp
import ethereum.utils as utils
from ethereum.utils import to_string
import sys
import itertools
import ethereum.testutils as testutils
from ethereum.testutils import fixture_to_bytes
impor... | karlfloersch/pyethereum | ethereum/todo_tests/test_pruning_trie.py | Python | mit | 13,719 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from flask.ext.admin.contrib.sqla import ModelView
from studio.core.engines import db
from suibe.models import SlideModel, ArticleModel
from .forms import CKTextAreaField
class Article(ModelView)... | qisanstudio/qsapp-suibe | src/suibe/panel/article.py | Python | mit | 2,836 |
#!/usr/bin/env python
def main():
f = open('stage1_solution.csv')
ones = 0
zeros = 0
total = 0
for line in f:
if line[:3] == 'id,':
continue
line = line.strip().split(',')
label = int(line[1])
if label == 1:
ones += 1
total += 1
zeros = total-ones
print float(zeros)/total
f.close()
if __name__... | achon22/cs231nLung | project-a/labels.py | Python | mit | 343 |
import re
from dataclasses import dataclass
from logging import getLogger
from typing import List, Optional
from aiohttp import ClientError, ClientSession
from aioitertools import chain as achain
from discord import Colour, Embed
from discord.ext.commands import Cog, Context, command
# from ..utils import maybe_send
... | FallenWarrior2k/cardinal.py | src/cardinal/cogs/saucenao.py | Python | mit | 8,997 |
"""Internal module for human-friendly color generation.
.. important::
End users of this library should not use anything in this module.
Code adapted from:
- https://github.com/davidmerfield/randomColor (CC0)
- https://github.com/kevinwuhoo/randomcolor-py (MIT License)
Additional reference from:
- https://en.wi... | joke2k/faker | faker/providers/color/color.py | Python | mit | 10,362 |
#!/usr/bin/env python3
import asyncio
import contextlib
import datetime
import functools
import importlib
import itertools
import logging
import os
import sys
import traceback
import click
import discord
import config
from cogs.utils import db
from core import Chiaki, migration
# use faster event loop, but fall bac... | Ikusaba-san/Chiaki-Nanami | chiaki.py | Python | mit | 4,858 |
def main():
n=int(raw_input())
f1=0
f2=1
print f1,f2,
for i in range(2,n):
temp=f1
f1=f2
f2=f1+temp
print f2,
main()
| kumarisneha/practice_repo | techgig/techgig_fibonacci_series.py | Python | mit | 186 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import datetime
import fcntl
import os
import struct
import sys
import termios
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
import six
from natural.constant import... | tehmaze/natural | natural/data.py | Python | mit | 3,460 |
from models import Comment
from ..user.serializers import UserProfileSerializer
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
username = serializers.SerializerMethodField()
class Meta:
model = Comment
fields = ("id","user","username", "topic","comment","comment_html"... | shriyanka/daemo-forum | spirit/comment/serializers.py | Python | mit | 715 |
from typing import Callable, Tuple, Optional
import numpy as np
import picwriter.components as pc
from pp.components.waveguide_template import wg_strip
from pp.picwriter2component import picwriter2component
import pp
from pp.component import Component
@pp.autoname
def cdc(
length: float = 30.0,
gap: float =... | psiq/gdsfactory | pp/components/cdc.py | Python | mit | 3,663 |
import re
try:
import utils
except:
from . import utils
def expand_to_quotes(string, selection_start, selection_end):
quotes_regex = re.compile("(['\"])(?:\\\.|.)*?\\1")
# iterate over all found quotes pairs
for match in quotes_regex.finditer(string):
quotes_start = match.start()
quotes_end = match... | johyphenel/sublime-expand-region | expand_to_quotes.py | Python | mit | 1,231 |
import numpy as np
import pickle
import glob
from matplotlib import rc
from lamost import load_spectra, load_labels
from TheCannon import continuum_normalization
from TheCannon import dataset
from TheCannon import model
rc('text', usetex=True)
rc('font', family='serif')
with np.load("test_data_raw.npz") as data:
... | annayqho/TheCannon | code/lamost/xcalib_5labels/cont_norm_test_obj.py | Python | mit | 747 |
import os
import sys
root_path = os.path.abspath("../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
from Util.Metas import TimingMeta
class Optimizer:
def __init__(self, lr=0.01, cache=None):
self.lr = lr
self._cache = cache
def __str__(se... | carefree0910/MachineLearning | f_NN/Optimizers.py | Python | mit | 3,492 |
# -*- coding: utf-8 -*-
import re
import pandas as pd
from scrapy.spiders import Spider
from scrapy.selector import Selector
from ..parsing.zone import (
CityZoneParser,
EPCIZoneParser,
DepartmentZoneParser,
RegionZoneParser
)
from ..item import LocalFinance
from ..utils import DOM_DEP_MAPPING, unifo... | regardscitoyens/nosfinanceslocales_scraper | localfinance/spiders/localfinance_spider.py | Python | mit | 7,108 |
# 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 ... | AutorestCI/azure-sdk-for-python | azure-batch/azure/batch/models/job_get_all_lifetime_statistics_options.py | Python | mit | 1,726 |
import time
import urllib.parse
from dataclasses import dataclass
from typing import Dict, Iterable, Optional, Tuple, Union
import mitmproxy.net.http.url
from mitmproxy.coretypes import multidict
from mitmproxy.net.http import cookies, multipart
from mitmproxy.net.http import message
from mitmproxy.net.http.headers im... | vhaupert/mitmproxy | mitmproxy/net/http/request.py | Python | mit | 16,075 |