repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
Sorsly/subtle
google-cloud-sdk/lib/surface/runtime_config/configs/waiters/delete.py
# Copyright 2016 Google Inc. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
bradmwalker/wanmap
setup.py
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.md')) as f: CHANGES = f.read() requires = [ 'arrow', 'celery', 'psycopg2>=2.7.0', # reg...
quchunguang/test
testpy3/testinternet.py
""" Created on 2013-1-19 @author: Administrator """ import urllib.request import smtplib for line in urllib.request.urlopen('http://www.baidu.com'): line = line.decode('gb2312') print(line) server = smtplib.SMTP('localhost') server.sendmail('quchunguang@example.org', 'quchunguang@gmail.com', """To: quchungua...
herove/dotfiles
sublime/Packages/SublimeCodeIntel/libs/codeintel2/util.py
#!python # encoding: utf-8 # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License # Version 1.1 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www....
chapmanb/cloudbiolinux
fabfile.py
"""Main Fabric deployment file for CloudBioLinux distribution. This installs a standard set of useful biological applications on a remote server. It is designed for bootstrapping a machine from scratch, as with new Amazon EC2 instances. Usage: fab -H hostname -i private_key_file install_biolinux which will call...
inclement/kivy
kivy/core/window/window_pygame.py
''' Window Pygame: windowing provider based on Pygame .. warning:: Pygame has been deprecated and will be removed in the release after Kivy 1.11.0. ''' __all__ = ('WindowPygame', ) # fail early if possible import pygame from kivy.compat import PY2 from kivy.core.window import WindowBase from kivy.core impo...
yunojuno/django-onfido
onfido/settings.py
from os import getenv from django.conf import settings def _setting(key, default): return getenv(key, default) or getattr(settings, key, default) # API key from evnironment by default API_KEY = _setting("ONFIDO_API_KEY", None) # Webhook token - see https://documentation.onfido.com/#webhooks WEBHOOK_TOKEN = _s...
Azure/azure-sdk-for-python
sdk/identity/azure-identity/azure/identity/_internal/aadclient_certificate.py
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import base64 from typing import TYPE_CHECKING from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.p...
NedYork/viper
tests/parser/syntax/test_public.py
import pytest from viper import compiler valid_list = [ """ x: public(num) """, """ x: public(num(wei / sec)) y: public(num(wei / sec ** 2)) z: public(num(1 / sec)) def foo() -> num(sec ** 2): return self.x / self.y / self.z """ ] @pytest.mark.parametrize('good_code', valid_list) def test_publ...
datamade/parserator
parserator/manual_labeling.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import str from builtins import range from lxml import etree import sys import os.path from . import data_prep_utils import re import csv from argparse import Ar...
philiparvidsson/pymake2
tests/make_depends_circular.py
#!/usr/bin/env python #--------------------------------------- # IMPORTS #--------------------------------------- import test from pymake2 import * #--------------------------------------- # FUNCTIONS #--------------------------------------- @target @depends_on('my_target_3') def my_target_1(conf): pass @targ...
algorhythms/LeetCode
443 String Compression.py
#!/usr/bin/python3 """ Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of t...
jllanfranchi/phys597_computational2
landau_ch19_problem19.3.2/p9x3x2_v2.py
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <rawcell> # #!/usr/bin/env python # <codecell> from __future__ import division from __future__ import with_statement import numpy as np from pylab import ion import matplotlib as mpl from matplotlib.path import Path from matplotlib import pyplot as plt from matp...
aclowes/yawn
yawn/utilities/cron.py
import datetime from django.core import validators class Crontab: """ Simplified Crontab Support "minute hour weekday" components of a standard cron job. - "*/15 2,7,15 1-5" means "every fifteen minutes, on hours 2 7 15, Monday-Friday" - Minutes are from 0-59, hours from 0-23, and days from 0(Su...
Shuailong/Leetcode
solutions/pascals-triangle-ii.py
#!/usr/bin/env python # encoding: utf-8 """ pascals-triangle-ii.py Created by Shuailong on 2016-02-20. https://leetcode.com/problems/pascals-triangle-ii/. """ class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ lastrow = [] ...
Burning-Man-Earth/iBurn-Data
scripts/2013/playa_data/merge_camp_id_from_events.py
import Levenshtein import json from string_util import cleanString ''' This script merges camp ids into the data from ./data/playaevents-camps-2013.json OR ./results/camp_data_and_locations.json using playaevents-events-2013 (The Playa Events API Events feed) ''' # Threshold under which to discard...
raphaelrpl/portal
backend/test/question_tests/question_edit_tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from base import GAETestCase from datetime import datetime, date from decimal import Decimal from question_app.question_model import Question from routes.questions.edit import index, save from mommygae import mommy from tekton.gae.middlewa...
velfimov/django-countries
django_countries/tests/test_fields.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django from django.forms import Select from django.forms.models import modelform_factory from django.test import TestCase from django.utils import translation from django.utils.encoding import force_text try: from unittest import skipIf except: ...
opencivicdata/scrapers-ca
ca_mb_winnipeg/people.py
from utils import CanadianScraper, CanadianPerson as Person import json import re import requests COUNCIL_PAGE = 'http://winnipeg.ca/council/' class WinnipegPersonScraper(CanadianScraper): def scrape(self): # https://winnipeg.ca/council/wards/includes/wards.js # var COUNCIL_API = 'https://data.w...
rug-compling/hmm-reps
eval/ner/sequences/extended_feature.py
import sys import numpy as np ####################### #### Feature Class ### Extracts features from a labeled corpus ####################### from eval.ner.readers.brown import prepare_cluster_map from eval.ner.sequences.id_feature import IDFeatures class ExtendedFeatures(IDFeatures): def __init__(self, dataset,...
WenmuZhou/cifar-10-cnn
4_Residual_Network/ResNet_keras.py
import keras import numpy as np from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.layers.normalization import BatchNormalization from keras.layers import Conv2D, Dense, Input, add, Activation, GlobalAveragePooling2D from keras.initializers import he_normal fro...
gnott/elife-bot
activity/activity_InvalidateCdn.py
import activity from provider import cloudfront_provider """ activity_InvalidateCdn.py activity """ class activity_InvalidateCdn(activity.activity): def __init__(self, settings, logger, conn=None, token=None, activity_task=None): activity.activity.__init__(self, settings, logger, conn, token, activity_tas...
aronysidoro/django-payasyougo
payg/account/tests/factory.py
import os import time import datetime import random from django.db import models from django.conf import settings from django.test import TestCase, LiveServerTestCase, RequestFactory from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User, Group fr...
tylerturk/beeswithmachineguns
beeswithmachineguns/main.py
#!/bin/env python """ The MIT License Copyright (c) 2010 The Chicago Tribune & Contributors 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 ...
jgaul/python-oauth2
oauth2/__init__.py
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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 ...
LukeB42/Emissary
emissary/controllers/parser.py
# This file implements routines for extracting links from response objects. import re import lxml import urlparse import feedparser # We have sought to disperse power, to set men and women free. # That really means: to help them to discover that they are free. # Everybody's free. The slave is free. # The ultimate weapo...
talon-one/talon_one.py
talon_one/models/account_additional_cost.py
# coding: utf-8 """ Talon.One API The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #...
sait-berkeley-infosec/pynessus-api
nessusapi/utils.py
# coding=utf-8 import inspect def multiton(cls): """ Class decorator to make a class a multiton. That is, there will be only (at most) one object existing for a given set of initialization parameters. """ instances = {} def getinstance(*args, **kwargs): key = _gen_key(cls, *args, *...
onqtam/doctest
scripts/update_stuff.py
#!/usr/bin/python2.7 import os import fileinput # the version of the release with open("version.txt") as f: version = f.read() def getVersionTuple(v): return tuple(map(int, (v.split(".")))) version_major = str(getVersionTuple(version)[0]) version_minor = str(getVersionTuple(version)[1]) version_patch = str(getV...
martinkozak/pyircgate-daemon
modules/ircgate/ircgate.py
#! /usr/bin/python # -*- coding: utf-8 -*- # from application import module from application import agent as _agent from libraries import irclib import threading import time import sys import Queue class Module(module.AbstractModule): thread = None channels = None targets = None __password = None def __in...
lamperi/aoc
2016/10/solve.py
with open("input.txt") as f: data = f.read() bots = 1000 inputs = [[False] for i in range(bots)] outputs = [[] for i in range(bots)] maps = [[] for i in range(bots)] for line in data.splitlines(): if line.startswith("value"): p = line.split() val = int(p[1]) bot = int(p[-1]) in...
zrzka/blackmamba
blackmamba/lib/rope/base/utils/__init__.py
import sys import warnings def saveit(func): """A decorator that caches the return value of a function""" name = '_' + func.__name__ def _wrapper(self, *args, **kwds): if not hasattr(self, name): setattr(self, name, func(self, *args, **kwds)) return getattr(self, name) re...
hexhex/hexlite
java-api/src/test/python/test-jpype.py
import sys, logging logging.basicConfig(level=15, stream=sys.stderr, format="%(levelname)1s:%(filename)10s:%(lineno)3d:%(message)s") # make log level names shorter so that we can show them logging.addLevelName(50, 'C') logging.addLevelName(40, 'E') logging.ad...
afonsoduarte/ansible-stacey
roles/letsencrypt/templates/renew-certs.py
#!/usr/bin/env python import os import sys import time from subprocess import CalledProcessError, check_output, STDOUT certs_dir = '{{ letsencrypt_certs_dir }}' failed = False sites = {{ sites }} sites = (k for k, v in sites.items() if 'ssl' in v and v['ssl'].get('enabled', False) and v['ssl'].get('provider', 'manua...
philipbjorge/WTA-Bus-Routing
WTA App.py
from graph_tool.all import * from sets import Set import random from geopy import geocoders, distance from decimal import * def randomize(iterable, bufsize=1000): ''' generator that randomizes an iterable. space: O(bufsize). time: O(n+bufsize). ''' buf = [None] * bufsize for x in iterable: i = random.r...
luftdanmark/fifo.li
fifo/users/models.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy...
luwei0917/awsemmd_script
pulling.py
#!/usr/bin/env python3 import os import argparse import sys from time import sleep import subprocess import imp import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib import datetime import pickle matplotlib.style.use('fivethirtyeight') # print(plt.style.available) # mypath = os.envi...
sridhar912/Self-Driving-Car-NanoDegree
CarND-Advanced-Lane-Lines/CameraCalibration.py
import numpy as np import cv2 import pickle import os import matplotlib.pyplot as plt class cameraCalib(): def __init__(self, calib_image_path = 'camera_cal/'): self.mtx = None self.dist = None self.calib_image_path = calib_image_path self.calib_file = self.calib_image_path + 'cam...
getodacu/eSENS-eDocument
profiles/e_confirmation/xb_request/_sac.py
# ./_sac.py # -*- coding: utf-8 -*- # PyXB bindings for NM:bd794131cb7c2b1e52ff4e6220a49c5d8509c55c # Generated 2015-02-11 21:35:49.975586 by PyXB version 1.2.4 using Python 2.6.9.final.0 # Namespace urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2 [xmlns:sac] from __future__ import unicode_...
rtfd/readthedocs.org
readthedocs/api/v2/views/model_views.py
"""Endpoints for listing Projects, Versions, Builds, etc.""" import json import logging from allauth.socialaccount.models import SocialAccount from django.conf import settings from django.db.models import BooleanField, Case, Value, When from django.shortcuts import get_object_or_404 from django.template.loader import...
wurstfabrik/wurst-cli
wurstc/cli/utils.py
# -- encoding: UTF-8 -- import sys from click import echo from colorama import Fore, Style can_use_real_emoji = ( sys.stdout.isatty() and sys.platform != "win32" ) def success(msg): if can_use_real_emoji: sign = "\U0001F44C" else: sign = "[+] " echo(Fore.GREEN + Style.BRIGHT + si...
WaltonSimons/PhoneBot
smsd.py
import gammu.smsd import thread class smsd(object): """Starts gammu in another thread so the bot can interpret incoming sms""" def __init__(self, configpath): self.sms = gammu.smsd.SMSD(configpath) self.thread = None def start(self): self.thread = thread.start_new_thread(self.sms...
doriancoins/doriancoin
test/functional/interface_zmq.py
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Doriancoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the ZMQ notification interface.""" import configparser import os import struct from test_frame...
sigmunjr/VirtualPetFence
runSegmentation.py
import cv2 import skimage.io import skimage.transform import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from CatFinder import CatFinder from CatPlayer import CatPlayer from DrawGui import DrawArea def load_image(path, size=224): img = skimage.io.imread(path) short_edge = min(img.sha...
pisskidney/leetcode
medium/406.py
#!/usr/bin/python class Solution(object): def reconstructQueue(self, people): print people people = sorted(people, key=lambda x: x[1]) print people people = sorted(people, key=lambda x: -x[0]) print people res = [] for p in people: res.insert(p[1...
kjellmf/blend2tikz
tikz_export.py
#!BPY """ Name: 'TikZ (.tex)...' Blender: 245 Group: 'Export' Tooltip: 'Export selected curves as TikZ paths for use with (La)TeX' """ __author__ = 'Kjell Magne Fauske' __version__ = "1.0" __url__ = ("Documentation, http://www.fauskes.net/code/blend2tikz/documentation/", "Author's homepage, http://www.fausk...
jorisroovers/pymarkdownlint
pymarkdownlint/cli.py
import pymarkdownlint from pymarkdownlint.filefinder import MarkdownFileFinder from pymarkdownlint.lint import MarkdownLinter from pymarkdownlint.config import LintConfig import os import click DEFAULT_CONFIG_FILE = ".markdownlint" def echo_files(files): for f in files: click.echo(f) exit(0) def ge...
ducted/duct
duct/protocol/sflow/protocol/counters.py
""" .. module:: counters :synopsis: SFlow counter object interfaces .. moduleauthor:: Colin Alston <colin@imcol.in> """ from construct import Struct, UBInt32, Array, Bytes class InterfaceCounters(object): """Counters for network interfaces """ def __init__(self, u): self.if_index = u.unpack_ui...
cthit/CodeIT
src/level/Level.py
import configparser import importlib.util import random from pdb import set_trace from warnings import warn import numpy as np import pygame from PIL import Image import os from behaviours.Collide import Collide from src.utils.CodeItWarning import CodeItWarning from tiles.base.Tile import Tile level_paths = {} leve...
letops/django-sendgrid-parse
django_sendgrid_parse/migrations/0002_auto_20160729_1816.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-29 18:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_sendgrid_parse', '0001_initial'), ] operations = [ migrations.RenameF...
pmcnett/pmcalendar
pmcalendar/ui.py
import datetime import calendar import dabo dabo.ui.loadUI("wx") from dabo.ui import dForm, dPanel, dSizer, dGridSizer, dButton, dEditBox, \ dTextBox, dControlMixin, callAfterInterval, dKeys, \ dLabel, dHyperLink from dabo.lib.dates import goMonth, goDate import biz __all__ = ["...
DavidFnck/Python_Stock_Github
news/news/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class NewsItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() # pass news_thread=scrapy.Field() ...
bradfeehan/SublimePHPCoverage
php_coverage/command.py
import sublime_plugin from php_coverage.data import CoverageDataFactory from php_coverage.finder import CoverageFinder from php_coverage.matcher import Matcher class CoverageCommand(sublime_plugin.TextCommand): """ Base class for a text command which has a coverage file. """ def __init__(self, view...
msscully/datamart
tests/test_roles.py
from tests import TestCase from werkzeug.urls import url_quote from datamart.models import Role from flask.ext.security import current_user class TestRoles(TestCase): def test_show_roles_anon(self): """Verify unathenticated users can't see the roles page.""" response = self.client.get('/roles/', f...
nada-labs/sitemap-generator
spider.py
# # Walks every page that it can find in a website # # It's an excuse to play with BeautifulSoup import re from io import BytesIO from bs4 import BeautifulSoup from pycurl import Curl from queue import Queue, Empty as QueueEmpty from urllib.parse import urlsplit, urlunsplit, urljoin from sys import stdout class PageF...
jwinzer/OpenSlides
server/tests/integration/motions/test_polls.py
from decimal import Decimal import pytest from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from openslides.core.config import config from openslides.motions.models import Motion, ...
geojames/Dart_EnvGIS
Week6-1_Pandas.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------ __author__ = 'James T. Dietrich' __contact__ = 'james.t.dietrich@dartmouth.edu' __copyright__ = '(c) James Dietrich 2016' __license__ = 'MIT' __date__ = 'Wed Nov 16 11:33:39 2016' __version__ = ...
DesertBot/DesertBot
desertbot/modules/commands/Splatoon.py
""" Created on Sep 01, 2017 @author: StarlitGhost """ import datetime import time from twisted.plugin import IPlugin from twisted.words.protocols.irc import assembleFormattedText, attributes as A from zope.interface import implementer from desertbot.message import IRCMessage from desertbot.moduleinterface import IMo...
zaqwes8811/micro-apps
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/experiments/bicycle.py
# -*- coding: utf-8 -*- """ Created on Tue Apr 28 08:19:21 2015 @author: Roger """ from math import * import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Polygon wheelbase = 100 #inches vel = 20 *12 # fps to inches per sec steering_angle = radians(1) t = 1 # second orientation = 0. #...
hstorm/nn_spatial
notebooks/test_spatial.py
# -*- coding: utf-8 -*- import numpy as np from scipy.spatial import distance_matrix from scipy import sparse import pandas as pd from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout, Activation, Flatten from keras.optimizers import SGD,RMSprop #from keras.wrapper...
seerjk/reboot06
arch_pre_work/mtsleep1.py
import thread from time import sleep, ctime def loop0(): print 'start loop 0 at: ', ctime() sleep(4) print 'loop 0 done at: ', ctime() def loop1(): print 'start loop 1 at: ', ctime() sleep(2) print 'loop 1 done at: ', ctime() def main(): print 'starting at: ', ctime() thread.start_n...
robinedwards/neomodel
test/test_issue283.py
""" Provides a test case for issue 283 - "Inheritance breaks". The issue is outlined here: https://github.com/neo4j-contrib/neomodel/issues/283 More information about the same issue at: https://github.com/aanastasiou/neomodelInheritanceTest The following example uses a recursive relationship for economy, but the ide...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.2/Lib/distutils/command/build_py.py
"""distutils.command.build_py Implements the Distutils 'build_py' command.""" # created 1999/03/08, Greg Ward __revision__ = "$Id: build_py.py,v 1.34 2001/12/06 20:59:17 fdrake Exp $" import sys, string, os from types import * from glob import glob from distutils.core import Command from distutils.errors import * ...
andriibekker/django-swaps
swaps/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.template import RequestContext from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django...
Koisell/SmartCoffeeMachine
python/recognitionService_api/flask_app.py
from os import remove from flask import jsonify, request from sqlalchemy import create_engine from sqlalchemy.schema import MetaData from sqlite3 import dbapi2 as sqlite from cv2 import imread, COLOR_RGB2GRAY, cvtColor from cv2.face import LBPHFaceRecognizer_create from faces_recognizer import Recognizer engine = cr...
ncullen93/pyBN
pyBN/classes/_tests/test_bayesnet.py
""" ******** UnitTest BayesNet ******** Method Checks that assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIs(a, b) a is b assertIsNot(a, b) a is not b assertIsNone(x) x is None assertIsNotNone(x) x is not None assertIn(a, b) a in b asser...
shriyanka/daemo-forum
crowdsourcing/validators/utils.py
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from rest_framework.compat import unicode_to_repr from rest_framework.exceptions import ValidationError from rest_framework.utils.representation import smart_repr from csp import settings class EqualityValidator(object): ...
lukassup/python-cli
crud_cli/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """An example CRUD CLI app.""" from __future__ import ( absolute_import, print_function, unicode_literals ) import argparse import json import logging import sys TAGS = ( 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'bla...
PedrosWits/smart-cameras
smartcameras/speedcamera.py
import uuid import datetime import time import numpy as np import threading import vehicle import azurehook import json class SpeedCamera(object): TOPIC = "speedcamera" EVENT_ACTIVATION = "ACTIVATION" EVENT_DEACTIVATION = "DEACTIVATION" EVENT_VEHICLE = "OBSERVATION" def __init__(self, street, cit...
IT-PM-OpenAdaptronik/Webapp
apps/register/forms.py
""" License MIT License Copyright (c) 2017 OpenAdaptronik 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,...
WittscraftStudios/business-card-raytracer
python/card.py
#!/usr/bin/env python3 import sys from math import sqrt, hypot from random import randint from array import array class Vector3d: ''' //Define a vector class with constructor and operator: 'v' struct v{ f x,y,z; // Vector has three float attributes. v operator+(v r){return v(x+r.x,y+r.y,z+...
ikarutoko/Tradercoin
Contrib/Spendfrom/spendfrom.py
#!/usr/bin/env python # # Use the raw transactions API to spend bitcoins received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a bitcoind or Bit...
xtompok/uvod-do-prg
cv12/cv12.py
from operator import itemgetter points = [{"coords":[14,48]},{"coords":[15,50]}, ] s = [p["coords"] for p in points] s = [p["coords"] for p in points if p["coords"][0]>14] print(s) def twice(n): return 2*n numbers = ["12","14","23"] nums = list(map(int,numbers)) doubled = list(map(twice,nums)) print(nums)...
paolo-losi/msgbox
msgbox/http.py
import time import urllib import urllib2 from Queue import Queue, Empty from functools import partial from threading import Thread, Lock import tornado.httpserver import tornado.ioloop from tornado.web import HTTPError, RequestHandler, Application, asynchronous from msgbox import logger from msgbox.sim import sim_man...
hakancelik96/coogger
core/cooggerapp/models/common.py
from django.contrib.contenttypes.models import ContentType from django.db import models from django_page_views.templatetags.django_page_views import views_count from django_vote_system.templatetags.vote import downvote_count, upvote_count class Common(models.Model): class Meta: abstract = True @prope...
namaggarwal/splitwise
tests/test_getCurrentUser.py
from splitwise import Splitwise import unittest try: from unittest.mock import patch except ImportError: # Python 2 from mock import patch @patch('splitwise.Splitwise._Splitwise__makeRequest') class GetCurrentUserTestCase(unittest.TestCase): def setUp(self): self.sObj = Splitwise('consumerkey', ...
neiltest/neil_learn_python
src/learn_python/python_other/neil_06_txt_split.py
#coding: utf-8 """ @Author: Well @Date: 2014 - 04 - 14 """ """ 求某一个英文文本中完整句子的数目, 文本中只包含大小写字母、空格、“,”和“.”, 完整的句子是指以“.”结束,且“.”号前必须出现至少一个字母。 """ import os # 文件名 name_ = os.path.basename(__file__).split('.')[0] dir_ = os.path.dirname(__file__) # 绝对文件夹路径 # file2 = os.path.dirname(__file__) # print file2 # # # 绝对路径 #file...
tvd-dataset/tvd
tvd/rip/avconv.py
#!/usr/bin/env python # encoding: utf-8 # # The MIT License (MIT) # # Copyright (c) 2013-2015 CNRS # # 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 li...
lukeyeager/compare-versions
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages # Get version with open('compare_versions/version.py') as f: exec(f.read()) # Get documentation def readme(): with open('README.rst') as f: return f.read() setup( name='compare_versions', version=__version__, author='Luke...
danhuss/faker
faker/providers/ssn/lb_LU/__init__.py
from .. import Provider as BaseProvider class Provider(BaseProvider): """ A Faker provider for the Luxembourgish VAT IDs """ vat_id_formats = ( 'LU########', ) def vat_id(self): """ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11 :return: a random L...
brunosmmm/hdltools
hdltools/vcd/__init__.py
"""Value change dump stuff.""" class VCDObject: """Abstract VCD object class.""" class VCDScope(VCDObject): """VCD scope.""" def __init__(self, *scopes: str): """Initialize. Parameters ---------- scopes List of scope names """ self._scopes = []...
arielmakestuff/loadlimit
test/unit/stat/test_flushtosql.py
# -*- coding: utf-8 -*- # test/unit/stat/test_flushtosql.py # Copyright (C) 2016 authors and contributors (see AUTHORS file) # # This module is released under the MIT License. """Test flushtosql()""" # ============================================================================ # Imports # ===========================...
FeatherCoin/Feathercoin
test/functional/p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
adriansoghoian/security-at-home
models.py
import datetime import os from time import strftime from reportlab.lib.colors import black from reportlab.lib.pagesizes import letter from reportlab.lib.enums import TA_JUSTIFY from reportlab.pdfbase import pdfmetrics from reportlab.platypus import Paragraph, Spacer, Table, PageTemplate, \ BaseDocTemplate, Frame, ...
q1x/zabbix-gnomes
ztmplimport.py
#!/usr/bin/env python # # import needed modules. # pyzabbix is needed, see https://github.com/lukecyca/pyzabbix # import argparse import ConfigParser import os import os.path import sys import distutils.util from xml.etree import ElementTree as ET from pyzabbix import ZabbixAPI # define config helper function def Conf...
ilblackdragon/pymisc
pymisc/abstract.py
__author__ = 'ilblackdragon@gmail.com' from pymisc import log, decorators class RegisterSystem(object): interfaces = [] classes = [] @classmethod @decorators.logprint(log) def register(self, cls): if cls.__name__[0] == 'I': print("Regirstring interface `%s`" % cls.__name__) ...
mjlong/openmc
examples/python/lattice/nested/build-xml.py
import openmc ############################################################################### # Simulation Input File Parameters ############################################################################### # OpenMC simulation parameters batches = 20 inactive = 10 particles = 10000 #########...
lunixbochs/sublimelint
sublimelint.py
# sublimelint.py # SublimeLint is a code checking framework for Sublime Text # # Project: https://github.com/lunixbochs/sublimelint # License: MIT import sublime import sublime_plugin import os from threading import Thread import time import json from .lint.edit import apply_sublimelint_edit from .lint.edit import E...
LionelDupuy/ARCHI_PHEN
ImageJ/DatabaseInput_deprecated.py
import time from datetime import date import numpy from PIL import Image import zbar import os,sys import wx # GUI # Handle time lapse! scanner = zbar.ImageScanner() # configure the reader scanner.parse_config('enable') #scanner.set_config(0, zbar.Config.ENABLE, 0) #scanner.set_conf...
enkore/i3pystatus
i3pystatus/coin.py
import requests import json from decimal import Decimal from i3pystatus import IntervalModule from i3pystatus.core.util import internet, require class Coin(IntervalModule): """ Fetches live data of all cryptocurrencies available at coinmarketcap <https://coinmarketcap.com/>. Coin setting should be equal ...
ptrsxu/snippetpy
shdisplay/progressbar.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """from python cookbook 2rd edition""" import sys class Progressbar(object): def __init__(self, finalcount, block_char = "."): self.finalcount = finalcount self.blockcount = 0 self.block = block_char self.f = sys.stdout if not s...
onitu/onitu
docs/examples/driver.py
import os from onitu.api import Plug, ServiceError, DriverError # A dummy library supposed to watch the file system from fsmonitor import FSWatcher plug = Plug() @plug.handler() def get_chunk(metadata, offset, size): try: with open(metadata.filename, 'rb') as f: f.seek(offset) r...
OmegaDroid/django-model-monitor
src/test_app/test/unit/test_monitored_model_get_changes.py
from django.test import TestCase from test_app.models import MonitorAllFields, MonitorSomeFields class MonitoredModelGetChanges(TestCase): def test_monitor_all_fields_no_changes___result_is_empty_dict(self): m = MonitorAllFields(first_field=1) self.assertEqual({}, m.get_changes()) def test_m...
levilucio/SyVOLT
UMLRT2Kiltera_MM/graph_MT_post__Model_T.py
""" __graph_MT_post__Model_T.py___________________________________________________________ Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION _____________________________________________________________________________ """ import tkFont from graphEntity import * from GraphicalForm i...
ryan413/gotem
web_html_pdf_zip/html_to_pdf.py
import win32com.client.makepy import win32com.client import os # Generate type library so that we can access constants win32com.client.makepy.GenerateFromTypeLibSpec('Acrobat') # Use Unicode characters instead of their ascii psuedo-replacements UNICODE_SNOB = 0 def convertHTML2PDF(htmlPath, pdfPath): 'Convert an...
rwl/godot
godot/common.py
#------------------------------------------------------------------------------ # Copyright (c) 2008 Richard W. 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 restricti...
scottbecker/autolims
autolims/models.py
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import JSONField from django.utils.encoding import python_2_unicode_compatible from transcriptic_tools import utils from transcriptic_tools.utils import _CONTAINER_TYPES ...
kelvinxu/representation-learning
generate_dataset.py
import numpy from os import listdir from os.path import isfile, join import h5py import numpy from scipy import misc rng = numpy.random.RandomState(123522) path = '/data/lisatmp3/xukelvin/' if __name__ == "__main__": files = [f for f in listdir(join('train')) if isfile(join('train', f))] # Shu...
perna/podigger
migrations/versions/dde8a74cfffa_.py
"""empty message Revision ID: dde8a74cfffa Revises: 0c2841d4cfcd Create Date: 2016-07-29 17:42:17.142867 """ # revision identifiers, used by Alembic. revision = 'dde8a74cfffa' down_revision = '0c2841d4cfcd' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
timlapluie/gldsprnt
classes/pre_game/pre_game.py
# -*- coding: utf-8 -*- # !/usr/bin/python import pygame from classes.pre_game.pre_game_item import PreGameItem class PreGame(): def __init__(self, screen, actions, players): # Screen für Instanz definieren self.screen = screen self.screen_width = self.screen.get_rect().width self....