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 |
|---|---|---|---|---|---|
import os
import pwd
import Pyro5.api
class RestrictedService:
@Pyro5.api.expose
def who_is_server(self):
return os.getuid(), os.getgid(), pwd.getpwuid(os.getuid()).pw_name
@Pyro5.api.expose
def write_file(self):
# this should fail ("permission denied") because of the dropped privileg... | irmen/Pyro5 | examples/privilege-separation/drop_privs_server.py | Python | mit | 1,333 |
import tkinter as tk
# Default values
DEFAULT_HORIZONTALS = 4
DEFAULT_VERTICALS = 6
DEFAULT_LENGTH = 100
DEFAULT_WIDTH = 5
DEFAULT_ALPHA = 0.03
DEFAULT_BETA = 1e-3
DEFAULT_THRESHOLD = 2
# Dimensions
ENTRY_WIDTH = 4
PADX = 10
class CreationTools(tk.LabelFrame):
"""This class of methods implements creation tools i... | janzmazek/wave-propagation | source/components/tools.py | Python | mit | 12,428 |
import os
import base64
import requests
import time
import zlib
from pycrest import version
from pycrest.compat import bytes_, text_
from pycrest.errors import APIException
from pycrest.weak_ciphers import WeakCiphersAdapter
from hashlib import sha224
try:
from urllib.parse import urlparse, urlunparse, parse_qsl
e... | lodex/PyCrest | pycrest/eve.py | Python | mit | 13,675 |
import cPickle as pickle
import unittest
from .dataflow import *
from .node import Node
from .state import State
n1 = Node("n1")
n2_1 = Node("n2_1", depends = [n1])
n2_2 = Node("n2_2", depends = [n1])
n3 = Node("n3", depends = [n2_1, n2_2])
n4 = Node("n4")
# Can't be a lambda function
def Compute2_1(o1): return ["2_1... | mthomure/glimpse-project | glimpse/util/dataflow/dataflow_test.py | Python | mit | 3,002 |
import numpy as np
a = np.array([0, 1, 2])
b = np.array([2, 0, 6])
print(np.minimum(a, b))
# [0 0 2]
print(np.fmin(a, b))
# [0 0 2]
a_2d = np.arange(6).reshape(2, 3)
print(a_2d)
# [[0 1 2]
# [3 4 5]]
print(np.minimum(a_2d, b))
# [[0 0 2]
# [2 0 5]]
print(np.fmin(a_2d, b))
# [[0 0 2]
# [2 0 5]]
print(np.minimu... | nkmk/python-snippets | notebook/numpy_minimum_fmin.py | Python | mit | 524 |
# -*- coding: utf-8 -*-
"""One Million.
Usage:
onemillion <host> [--no-cache | --no-update | (-l <cache> | --cache_location=<cache>)]
onemillion (-h | --help)
onemillion --version
Options:
-h --help Show this screen.
--version Show version.
--no-cache Don't cache the top million do... | fhightower/onemillion | onemillion/cli.py | Python | mit | 1,255 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('images_metadata', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='imagethesaurus',
... | acdh-oeaw/defc-app | images_metadata/migrations/0002_auto_20160314_1343.py | Python | mit | 433 |
# 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/hybridcompute/azure-mgmt-hybridcompute/azure/mgmt/hybridcompute/aio/_hybrid_compute_management_client.py | Python | mit | 5,609 |
# The MIT License (MIT)
# Copyright (c) 2021 Microsoft Corporation
# 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... | Azure/azure-sdk-for-python | sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/endpoint_component.py | Python | mit | 7,370 |
# -*- coding: utf-8 -*-
import os
import codecs
import sys
import urllib
import json
from wekeypedia.wikipedia_page import WikipediaPage as Page, url2title, url2lang
from wekeypedia.wikipedia_network import WikipediaNetwork
from wekeypedia.exporter.nx_json import NetworkxJson
from multiprocessing.dummy import Pool as... | WeKeyPedia/toolkit-python | examples/analysis-data.py | Python | mit | 2,562 |
from planner import feedback as fb
from extend import RRG as rrg
from helper import visualize as vis
import matplotlib.image as mpimg
from env_classes.States import *
from time import clock
from math import floor
from helper.iClap_helpers import *
from helper.logging import *
import helper.bvp as bvp
def main():
glo... | quentunahelper/game-theoretic-feedback-loop | RRG/iCLAP.py | Python | mit | 3,595 |
#! /usr/bin/env python
import logging
import random
import pickle
import os
import sys
import getopt
from lib.common import LOW_SCORE, finished_flag, visited_flag, result_flag, error_flag
from lib.common import touch, deepcopy
from lib.common import setup_logging
# Import PDFRW later for controling the logging format... | uvasrg/EvadeML | gp.py | Python | mit | 18,807 |
print "-- This shows that the environment file is loaded --"
| abbotao/harmonious | test/input_data/environment.py | Python | mit | 61 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import unittest
class ExemploDeTeste(unittest.TestCase):
def test_adicao(self):
resultado_obtido=1+2
self.assertEqual(3,resultado_obtido) | renzon/livrogae | backend/test/exemplo_de_teste.py | Python | mit | 240 |
'''
Distributed under the MIT License, see accompanying file LICENSE.txt
'''
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.locale
import os.path
from ConfigParser import SafeConfigParser
from tornado.options import define, options
#api
from handlers.ApiHa... | NewEconomyMovement/blockexplorer | NEMBEX.py | Python | mit | 3,700 |
import sys
def synced_impl(dependencies, python):
import subprocess
from ast import literal_eval
from packaging.requirements import Requirement
from ...dep.core import dependencies_in_sync
sys_path = None
if python:
output = subprocess.check_output([python, '-c', 'import sys;print([... | ofek/hatch | backend/src/hatchling/cli/dep/__init__.py | Python | mit | 930 |
input1="""Some
text."""
input2="""package main
import "fmt"
func main() {
queue := make(chan string, 2)
queue <- "one"
queue <- "twoO"
close(queue)
for elem := range queue {
fmt.Println(elem)
}
}"""
def transpose(text):
lines = text.splitlines()
lens = [len(line) for line in ... | jamtot/DailyChallenge | transpose_text (06jun2016)/transpose.py | Python | mit | 778 |
import pytest
from pytest_bdd import (
scenarios,
then,
when,
)
from . import browsersteps
pytestmark = [
pytest.mark.bdd,
pytest.mark.usefixtures('workbook', 'admin_user'),
]
scenarios(
'title.feature',
'select_variant.feature',
'variant_curation_tabs.feature',
'generics.feature',... | ClinGen/clincoded | src/clincoded/tests/features/test_generics.py | Python | mit | 1,131 |
from plumbum import local
import benchbuild as bb
from benchbuild.environments.domain.declarative import ContainerImage
from benchbuild.settings import CFG
from benchbuild.source import HTTP
from benchbuild.utils import path
from benchbuild.utils.cmd import make, tar
from benchbuild.utils.settings import get_number_of... | PolyJIT/benchbuild | benchbuild/projects/benchbuild/mcrypt.py | Python | mit | 4,034 |
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import swaggyjenkins
from swaggyjenkins.mo... | cliffano/swaggy-jenkins | clients/python/generated/test/test_pipeline_step_impl.py | Python | mit | 1,040 |
#!/usr/bin/python
"""
assembles raw cuts into final, titles, tweaks audio, encodes to format for upload.
"""
import datetime
import os
from pprint import pprint
import sys
import subprocess
import xml.etree.ElementTree
import pycaption
from mk_mlt import mk_mlt
from process import process
from django.db import conn... | CarlFK/veyepar | dj/scripts/enc.py | Python | mit | 29,456 |
'''
Example of how to transform a corpus into the streamcorpus format.
This uses the John Smith corpus as a test data set for illustration.
The John Smith corpus is 197 articles from the New York Times gathered
by Amit Bagga and Breck Baldwin "Entity-Based Cross-Document
Coreferencing Using the Vector Space Model"
htt... | trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_john_smith.py | Python | mit | 5,197 |
import tornado.web
from tornado import gen
from engines.verify import EmailVerificationEngine
class IndexPageHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class VerifyPageHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self, payload):
# 1. Activ... | rmoritz/chessrank | chessrank/server/requesthandlers/__init__.py | Python | mit | 747 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Setup file for willchaterr.
This file was generated with PyScaffold 2.4.4, a tool that easily
puts up a scaffold for your new Python project. Learn more under:
http://pyscaffold.readthedocs.org/
"""
import sys
from setuptools import setup
def setup_p... | totalgood/willchatterr | setup.py | Python | mit | 654 |
import os
import uuid
import zipfile
from flask import Flask, request, render_template, jsonify, redirect, url_for
from constants import CONTRIBUTION_LINK, DEFAULT_ERROR_MESSAGE
from utils import get_parsed_file, empty_directory
app = Flask(__name__)
IS_PROD = os.environ.get("IS_PROD", False)
def allowed_file(file... | prabhakar267/whatsapp-reader | app.py | Python | mit | 2,888 |
import _plotly_utils.basevalidators
class TitleValidator(_plotly_utils.basevalidators.TitleValidator):
def __init__(
self, plotly_name="title", parent_name="densitymapbox.colorbar", **kwargs
):
super(TitleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=p... | plotly/python-api | packages/python/plotly/plotly/validators/densitymapbox/colorbar/_title.py | Python | mit | 1,252 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-06-19 13:52
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):
dependencies = [
('caffe', '0004_auto_20160619... | VirrageS/io-kawiarnie | caffe/caffe/migrations/0005_auto_20160619_1552.py | Python | mit | 624 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView, TemplateView
from django.contrib.auth.forms import AuthenticationForm
from registration.forms import RegistrationForm
class HomeView(TemplateView):
template_name = "home.html"
... | cpsimpson/pollcat | pollcat/urls.py | Python | mit | 1,230 |
import threading
import inspect
import re
from collections import defaultdict
from difflib import unified_diff
from StringIO import StringIO
from os.path import dirname, join, basename, splitext
NEWLINE = '\n'
SPACE = ' '
PREFIX = 'test_'
NEWLINE_PATTERN = re.compile(r'\r?\n')
def _lines(text):
return NEWLINE_PA... | vjmp/texpectpy | texpect.py | Python | mit | 4,707 |
# Copyright (c) 2015 Uber Technologies, Inc.
#
# 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, publ... | Willyham/tchannel-python | tchannel/zipkin/formatters.py | Python | mit | 5,332 |
import numpy as np
from lazyflow.rtype import SubRegion
from .abcs import OpTrain
from .abcs import OpPredict
from tsdl.tools import Classification
from tsdl.tools import Regression
class OpStateTrain(OpTrain, Classification):
def execute(self, slot, subindex, roi, result):
assert len(self.Train) == 2... | burgerdev/hostload | tsdl/classifiers/state.py | Python | mit | 2,316 |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter
import datetime
import sys
from collections import Counter
import math
import re
import numpy as np
months = HourLocator()
hourFmt = DateFormatter('%H')
filepath = str(sys.argv[1])
mtagged ... | jwheatp/twitter-riots | analysis/plotfreq.py | Python | mit | 1,668 |
from django.shortcuts import render
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.db.models import Avg, Count, Max, ExpressionWrapper, F, CharField
import json... | pythonvietnam/nms | apps/transaction/views.py | Python | mit | 3,975 |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'sensuconfigs.views.home', name='home'),
# url(r'^sensuconfigs/', include('sensuconfigs.foo.urls... | Numerical-Brass/sensu-configs | sensuconfigs/urls.py | Python | mit | 566 |
#!/usr/bin/env python
#coding=utf-8
from __future__ import absolute_import
from celery import Celery
app = Celery('lib', include=['lib.tasks'])
app.config_from_object('lib.config')
if __name__ == '__main__':
app.start()
| youqingkui/zhihufav | lib/celery_app.py | Python | mit | 230 |
def execute(options, arguments):
print('Running test command') | manhg/matsumi | task/test.py | Python | mit | 66 |
#!/usr/bin/env python
from counters import __version__
sdict = {
'name' : 'counters',
'version' : __version__,
'description' : 'A Python port of https://github.com/francois/counters',
'long_description' : 'Provides an easy interface to count any kind of performance metrics within a system',
'url': ... | francois/pycounters | setup.py | Python | mit | 1,199 |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import requests
from indra.config import get_config
from indra.literature import pubmed_client
# Python3
try:
from functools import lru_cache
# Python2
except ImportError:
from functo... | johnbachman/belpy | indra/literature/crossref_client.py | Python | mit | 6,381 |
try:
import pandas as pd
except ImportError:
pd = None
if pd is not None:
from tdda.constraints.pd.constraints import (discover_df,
verify_df,
detect_df)
from tdda.constraints.db.constraints import (discover_... | tdda/tdda | tdda/constraints/__init__.py | Python | mit | 455 |
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
if bytes == str: # python2
iseq = lambda s: map(ord, s)
bseq = lambda s: ''.join(map(chr, s))
buffer = lambda s: s
else: # python3
iseq = lambda s: s
bseq = bytes
buffer = lambda s: s.buffer
def b58encode(input):
... | d1ffeq/ecp | ecp/base58.py | Python | mit | 1,183 |
from import_string.base import import_string
class Config(dict):
def apply(self, cfg):
obj = import_string(cfg)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
class BaseConfig(object):
DEBUG = False
APP_ID = 0
IMPLICIT = True
USE... | roman901/vk_bot | vk_bot/config.py | Python | mit | 561 |
import sys
import numpy as np
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from sklearn import metrics
from spherecluster import SphericalKMeans
from spherecluster import VonMisesFisherMixture
from spherecluster import sample_vMF
plt.ion()
'''
Implements "small-mix" example from
"Clusterin... | clara-labs/spherecluster | examples/small_mix.py | Python | mit | 8,179 |
'''
Copyright 2013 Cosnita Radu Viorel
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, distribute... | rcosnita/fantastico | fantastico/oauth2/token.py | Python | mit | 1,400 |
from Hangman import Hangman
def test_check3():
word = "Hello"
attempts = 5
game = Hangman(word, attempts)
for elem in word[:-1]:
game.attempt(elem)
game.attempt("a")
game.check_status()
assert game.status == 0
assert game.number_of_mistakes == 1
game.attempt("a")
assert... | glazastyi/Hangman | tests/test_check3.py | Python | mit | 589 |
from django.shortcuts import render
def page(req):
return render(req, 'en/public/connection.html')
| addisaden/django-tutorials | TasksManager/views/connection.py | Python | mit | 104 |
#!/usr/bin/env nix-shell
#!nix-shell --pure -i python3 -p "python3.withPackages (ps: with ps; [ requests ])"
import json
import re
import requests
import sys
releases = ("openjdk8", "openjdk11", "openjdk13", "openjdk14", "openjdk15", "openjdk16")
oses = ("mac", "linux")
types = ("jre", "jdk")
impls = ("hotspot", "ope... | NixOS/nixpkgs | pkgs/development/compilers/adoptopenjdk-bin/generate-sources.py | Python | mit | 2,198 |
from typing import Dict, List, Union, cast
from asgiref.sync import async_to_sync
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ImproperlyConfigured
from django.db.mode... | boehlke/OpenSlides | openslides/utils/auth.py | Python | mit | 6,857 |
# -*- coding: utf-8 -*-
"""
.. module:: organizations
"""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
... | mlipa/volontulo | backend/apps/volontulo/views/organizations.py | Python | mit | 6,545 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('articles', '0005_auto_20160407_2257'),
]
operations = [
migrations.AlterField(
model_name='spons... | davogler/POSTv3 | articles/migrations/0006_auto_20160408_1532.py | Python | mit | 469 |
"""
Settings.
"""
import importlib
def import_from_string(val):
"""
Attempt to import a class from a string representation.
"""
try:
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
m = importlib.import_module(module_path)
return getattr(... | sensidev/drf-requests-jwt | drf_requests_jwt/settings.py | Python | mit | 637 |
# 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/ENTSOE/Equipment/Meas/MeasurementValueSource.py | Python | mit | 2,757 |
from random import random
import Queue
from shapes import Point
from spatial import convexHull
def randomPoint(k=None):
if k:
return Point(int(k * random()), int(k * random()))
return Point(random(), random())
def randomConvexPolygon(sample, k=None, n=3):
hull = convexHull([randomPoint(k=k) for... | crm416/point-location | geo/generator.py | Python | mit | 1,590 |
from shape import Shape
import random
import numpy
"""
Author: Thomas Elgin (https://github.com/telgin)
"""
class Square(Shape):
"""
Square implementation.
"""
def randomizePoints(self):
"""
Randomizes the points, essentially creating a new small shape
somewher... | telgin/PolygonCompositionImages | square.py | Python | mit | 3,359 |
from rx.disposable import Disposable, SingleAssignmentDisposable
from rx.observable import Producer
from rx.subject import Subject
from threading import RLock
class EventProducer(Producer):
def __init__(self, scheduler):
self.scheduler = scheduler
self.gate = RLock()
self.session = None
def getHandler... | akuendig/RxPython | rx/linq/fromEvent.py | Python | mit | 4,544 |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | LordSputnik/beets | beets/library.py | Python | mit | 49,018 |
# lesson 2.1 - data types
year = 2013 # integer number
age = 13.75 # decimal number
name = "John" # string
# now print them out to screen
#print (year)
#print (age)
#print (name)
year = int(input("Enter the Year "))
age = float(input("Enter your age as a decimal "))
name = input("Enter your name ")
# place a... | paulcockram7/paulcockram7.github.io | 10python/l02/Ex3AddInput.py | Python | mit | 660 |
from igraph import *
from random import sample,random,choice
from core import Algorithm
from egraphs import FBEgoGraph
class AlbatrossSampling(Algorithm):
def update_graph(self, start_node, new_node):
g = self.sampled_graph
start_id = g.vs['name'].index(start_node)
if new_node['name'] not ... | ryaninhust/sampling | albatross_sampling.py | Python | mit | 1,462 |
#!/usr/bin/env python
# Filename:DBCompiler.py
# Edited by chow 2013.09.06
# ChangeList:
# fix a bug which may cause the script can't find the config.xml
import logging
import re
import os
import sys
import getopt
import xml.etree.ElementTree as et
pathList={}
class Compiler:
def main(self,argv):
... | EffectHub/effecthub | scripts/DBCompiler.py | Python | mit | 6,562 |
"""General utilities, such as exception classes."""
import typing
# Titanic-specific exceptions
class TitanicError(Exception):
"""Base Titanic error."""
class RoundingError(TitanicError):
"""Rounding error, such as attempting to round NaN."""
class PrecisionError(RoundingError):
"""Insufficient precisi... | billzorn/fpunreal | titanfp/titanic/utils.py | Python | mit | 2,194 |
import logging
logging.basicConfig()
from serial_handler import SerialHandler, serial_wrapper
BAUDRATE = 9600
class TagHeuer520(SerialHandler):
def __init__(self, port=None):
super(TagHeuer520,self).__init__(port,BAUDRATE)
self.line_buffer = ""
@serial_wrapper
def read(self):
""" Read and parse tim... | LateralGs/rallyx_timing_scoring | software/tag_heuer_520.py | Python | mit | 1,551 |
# from collections import Counter # for my original solution
class Solution(object):
@staticmethod
def singleNumber(nums):
"""
single_number == PEP8 (forced mixedCase by LeetCode)
:type nums: List[int]
:rtype: int
"""
# cnt = Counter(nums)
# return next... | the-zebulan/LeetCode | Easy/single_number.py | Python | mit | 410 |
#!/usr/bin/env python
import pytest
from pytest import fixture
from circuits import handler, Event, Component
from circuits.net.events import read, write
from circuits.protocols.irc import IRC
from circuits.protocols.irc import strip, joinprefix, parseprefix
from circuits.protocols.irc import (
PASS, USER, N... | eriol/circuits | tests/protocols/test_irc.py | Python | mit | 3,696 |
"""
Unittest for GeometryType class.
"""
import unittest
from crystalpy.diffraction.GeometryType import BraggDiffraction, LaueDiffraction, \
BraggTransmission, LaueTransmission
from crystalpy.diffraction.GeometryType import GeometryType
class GeometryTypeTest(unittest.TestCase):... | edocappelli/crystalpy | crystalpy/tests/diffraction/GeometryTypeTest.py | Python | mit | 2,412 |
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Post, Comment
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
class PostSerializer(serializers.ModelSerializer):
comments = CommentSeri... | chatcaos-org/django_rest_framework | src/hdson_rest/blog/serializers.py | Python | mit | 939 |
from PyQt4 import QtGui
class BooksSearcherWidget(QtGui.QWidget):
def __init__(self, label):
super(BooksSearcherWidget, self).__init__()
# Create searcher widgets
self.book_searcher_label = QtGui.QLabel(label)
self.book_searcher_line_edit = QtGui.QLineEdit()
self.book_sea... | franramirez688/Taric-Challange | taric_challange/gui/widgets/books_searcher.py | Python | mit | 932 |
"""Simple FTP Server"""
import argparse
import os
import sys
import threading
import time
import logging
_stash = globals()["_stash"]
try:
import pyftpdlib
except ImportError:
print("Installing pyftpdlib...")
_stash("pip install pyftpdlib")
es = os.getenv("?")
if es != 0:
print(_stash.text_color("Failed to ins... | cclauss/stash | bin/ftpserver.py | Python | mit | 2,452 |
# -*- coding: utf-8 -*-
from time import sleep
from datetime import datetime
import boto
import boto.dynamodb2
from boto.dynamodb2.table import Table
conn = boto.dynamodb2.layer1.DynamoDBConnection()
# tbl = Table("test")
def t():
return conn.query(
"cl-hp-votes",
{
"q_id": {
... | clifflu/headless-poller | test_scripts/gsi_read.py | Python | mit | 756 |
# apis_v1/test_views_organization_suggestion_tasks.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from follow.models import UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW
from twitter.models import TwitterWhoIFol... | jainanisha90/WeVoteServer | apis_v1/tests/test_views_organization_suggestion_tasks.py | Python | mit | 14,255 |
#!/usr/bin/python2
from shell_command import ShellCommand
from source import Directory, File
import os
class Target(object):
def __init__(self, name, sources=None, includes=None):
self.name = name
self.sources = [] if sources is None else sources
self.cflags = []
self.ldflags = []... | goniz/buildscript | build_system/target.py | Python | mit | 2,918 |
#!/usr/bin/python
# -*- coding: utf8 -*-
"""히든커멘드지롱"""
import re
from botlib import BotLib
from util.util import enum
Type = enum(
Nico = 1,
Kkamo = 2,
Japan = 3,
)
def input_to_type(text):
if re.findall(ur"니코", text): return Type.Nico
if re.findall(ur"까모", text): return Type.Kkamo
if te... | storyhe/playWithBot | plugins/say.py | Python | mit | 789 |
"""
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains ... | franklingu/leetcode-solutions | questions/insert-into-a-binary-search-tree/Solution.py | Python | mit | 1,627 |
"""Main package API entry point.
Import core objects here.
"""
from .__pkg__ import (
__description__,
__url__,
__version__,
__author__,
__email__,
__license__
)
from .model import ModelBase, make_declarative_base
from .query import Query, QueryModel
from .manager import Manager, ManagerMixin... | dgilland/alchy | alchy/__init__.py | Python | mit | 491 |
# copyright 2015 by mike lodato (zvxryb@gmail.com)
# this work is subject to the terms of the MIT license
import math
import pyglet
class GrayCode(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(GrayCode, self).__init__(*args, **kwargs)
y0 = 0
y1 = self.height
self.i = 0
self.frames... | zvxryb/3d-scanner | draw.py | Python | mit | 1,140 |
#!/usr/bin/env python
from spider import *
class CaltechSpider(Spider):
def __init__(self):
Spider.__init__(self)
self.school = 'caltech'
self.subject = 'eecs'
def doWork(self):
print "downloading caltech course info"
r = requests.get('http://www.cms.caltech.edu/acade... | roscopecoltran/scraper | .staging/meta-engines/xlinkBook/update/update_caltech.py | Python | mit | 2,382 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import json
import logging
from functools import partial
from tempfile import NamedTemporaryFile
from subprocess import check_output, CalledProcessError, PIPE
from matplotlib import rcParams
from matplotlib.figure... | dfm/savefig | savefig.py | Python | mit | 8,667 |
import lassie
from .base import LassieBaseTestCase
class LassieTwitterCardTestCase(LassieBaseTestCase):
def test_twitter_all_properties(self):
url = 'http://lassie.it/twitter_card/all_properties.html'
data = lassie.fetch(url)
self.assertEqual(data['url'], 'http://www.youtube.com/watch?v=f... | michaelhelmick/lassie | tests/test_twitter_card.py | Python | mit | 1,403 |
# coding=utf8
"""
Module docstrings before __future__ imports can break things...
"""
from __future__ import division
import ast
import json
import os
import random
import re
import sys
import unittest
import weakref
from collections import namedtuple
from copy import copy
from functools import partial
from importli... | alexmojaki/birdseye | tests/test_birdseye.py | Python | mit | 21,909 |
import json
from copy import copy
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.utils.encoding import force_text
from restify.http import status
class PostInBodyMiddleware(MiddlewareMixin):
def _is_json_body_request(self, request):
return len(reque... | lovasb/django-restify | restify/middleware.py | Python | mit | 862 |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1302010047.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
ret... | biomodels/MODEL1302010047 | MODEL1302010047/model.py | Python | cc0-1.0 | 427 |
import numpy as np
import numpy.ma as ma
from armor import pattern
def gaussianFilter(a, sigma=20, newCopy=False):
"""
#adapted from armor.pattern
returns a dbz object
2014-03-07
"""
from scipy import ndimage
a1 = a.copy()
a1.matrix = ndimage.filters.gaussian_filter(a.m... | yaukwankiu/armor | filter/filters.py | Python | cc0-1.0 | 1,054 |
#!/usr/bin/env python3
'''
Weather function
Gives a the text weather forecast. Defaults to today if no argument given. So "tomorrow" is really the only useful argument.
example input: weather_function("tomorrow"):
output: Saturday: Mainly sunny. High 86F. Winds WSW at 5 to 10 mph. Saturday Night: Clear. Low 6... | HarryMaher/dumbphone | weather.py | Python | epl-1.0 | 2,454 |
"""
Library for the robot based system test tool of the OpenDaylight project.
Authors: Baohua Yang@IBM, Denghui Huang@IBM
Updated: 2013-11-14
"""
import collections
'''
Common constants and functions for the robot framework.
'''
def collection_should_contain(collection, *members):
"""
Fail if not every member... | yeasy/robot_tool | libraries/Common.py | Python | epl-1.0 | 935 |
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------
# dpms.py - Manage DPMS settings for X displays
# -----------------------------------------------------------------------
# $Id$
#
# -----------------------------------------------------------------------
# Freevo - A... | freevo/freevo2 | src/plugins/dpms.py | Python | gpl-2.0 | 3,882 |
# -*- 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 'Comment'
db.create_table(u'article_comment', (
... | websbydrew/django-drew | django_demosite/article/migrations/0002_auto__add_comment.py | Python | gpl-2.0 | 2,064 |
import json
import listenbrainz.db.user as db_user
import listenbrainz.db.feedback as db_feedback
from redis import Redis
from flask import url_for, current_app
from listenbrainz.db.model.feedback import Feedback
from listenbrainz.tests.integration import IntegrationTestCase
class FeedbackAPITestCase(IntegrationTest... | Freso/listenbrainz-server | listenbrainz/tests/integration/test_feedback_api.py | Python | gpl-2.0 | 32,317 |
#!/usr/bin/env python3
import sys
import plistlib
if __name__ == "__main__":
assert sys.version_info[0] == 3
# "advene" "3.4.0"
app_id, app_version = sys.argv[1:]
app_id_lower = app_id.lower()
plist = dict(
CFBundleExecutable=app_id_lower,
CFBundleIconFile="%s.icns" % app_id_low... | oaubert/advene | dev/osx_bundle/misc/create_info.py | Python | gpl-2.0 | 1,676 |
# -*- 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),
('scout_group', '__first__'),
]
op... | roberzguerra/scout | registration/migrations/0001_initial.py | Python | gpl-2.0 | 1,089 |
import multiprocessing
import argparse
import os
import perceptron
import codecs
import sys
import StringIO
import tparser
import time
import json
def one_process(model_file_name,g_perceptron,q,q_out,parser_config,no_avg):
"""
g_perceptron - instance of generalized perceptron (not state)
q - queue with exa... | jmnybl/Turku-Dependency-Parser | parse_parallel.py | Python | gpl-2.0 | 5,441 |
#!/usr/bin/env python
# srv_thread.py
# RP(Y)C factory object for QKIT, written by HR,JB@KIT 2016
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | qkitgroup/qkit | qkit/services/qsurveilkit/srv_thread.py | Python | gpl-2.0 | 2,961 |
#!/usr/bin/python
import sys
import importlib
# RedBrick resource wrapper
from rb_setup import RedBrick
testfiles = {
"responsiveness": None,
"remove_all": None,
"stream": None,
"availability": None,
"common": None,
"colormotion": None,
"scenes": None,
}
for name in testfiles:
tes... | philkroos/tinkervision | src/test/red-brick/scripts/main.py | Python | gpl-2.0 | 1,384 |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
StandBrowserDockWidget
A QGIS plugin
Browse forests stand
-------------------
begin : 2017-02-18
git sha : ... | homann/stand-browser | stand_browser_dockwidget.py | Python | gpl-2.0 | 1,979 |
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | windskyer/nova | nova/virt/xenapi/vm_utils.py | Python | gpl-2.0 | 99,845 |
from bs4 import BeautifulSoup
import urllib2
from animapy.helpers.common import functions
class anitube(functions):
'''
thread function
gets:
offset: point in the list
items: search item list
parent: function caller
position: where to set the res... | JWebCoder/animapy | animapy/sources/anitube.py | Python | gpl-2.0 | 4,766 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
from PIL import ImageTk
from Tkinter import Frame, Label, BOTH, TOP, X, BOTTOM, Button, RIGHT, LEFT, SUNKEN
from ttk import Notebook, Style
########################################################################
class About(Frame):
def __init__(self, maste... | PinguinoIDE/pinguino-ide-tk | tkgui/ide/child_windows/about.py | Python | gpl-2.0 | 6,492 |
# Simple Last.fm API crawler to download listening events.
__author__ = 'mms'
# Load required modules
import os
import urllib
import csv
import json
import shutil
from os import listdir
from os.path import isfile, join
# Parameters
LASTFM_API_URL = "http://ws.audioscrobbler.com/2.0/"
LASTFM_API_KEY = ... | hawk23/music-recommender | Lastfm_LE_Fetcher.py | Python | gpl-2.0 | 10,562 |
import multiprocessing
import time
import logging
import queue
import os
import fnmatch
import pprint
import fss.constants
import fss.config
import fss.config.workers
import fss.workers.controller_base
import fss.workers.worker_base
_LOGGER = logging.getLogger(__name__)
_LOGGER_FILTER = logging.getLogger(__name__ + ... | dsoprea/PathScan | fss/workers/generator.py | Python | gpl-2.0 | 7,985 |
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
... | shimpe/frescobaldi | frescobaldi_app/lilydoc/manager.py | Python | gpl-2.0 | 5,554 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#local imports
from modules.page_mount import Principal
page = Principal()
page.mount(
page='traceability',
category='main',
js=('form.default','feedback', 'traceability'),
css=('traceability', 'default.form','default.lists', 'default.detail')
)
| cria/microSICol | py/traceability.py | Python | gpl-2.0 | 310 |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 16:49:53 2015
@author: gideon
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 16:28:29 2015
@author: gideon
### TREE_STATS ###
Description:
This script defines a function that collects some statistic... | jergosh/slr_pipeline | bin/tree_stats.py | Python | gpl-2.0 | 6,921 |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file_... | martadesimone/Protoplanetarydisks | linmix/setup.py | Python | gpl-2.0 | 3,674 |