repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
EndyKaufman/django-postgres-angularjs-blog
app/account/migrations/0002_fill_from_mock.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-31 17:41 from __future__ import unicode_literals from django.db import migrations from ..models import User import json import os def fill_from_mock(apps, schema_editor): try: with open(os.path.join('mock', 'account', 'users.json')) as f: ...
pombredanne/metamorphosys-desktop
metamorphosys/META/test/MetaPyUnit/xmlrunner.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
TheAlgorithms/Python
web_programming/instagram_crawler.py
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script...
hmartiro/selfgraph
selfgraph/core/db.py
""" Module that interfaces with the Neo4j graph database. """ import logging from py2neo import neo4j, rel, node class GraphDB(): """ """ BATCH_SIZE = 500 DB_URL = 'http://localhost:7474/db/data/' db = neo4j.GraphDatabaseService(DB_URL) def __init__(self): self.batch = neo4j.Wri...
parmarmanojkumar/MITx_Python
6001x/week6/L11p6.py
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 21:40:18 2016 @author: VirKrupa """ class Queue(object): """An Queue is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once. It is implemented as FIFO""" def __init__(se...
Diti24/python-ivi
ivi/rigol/rigolDP832A.py
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2013-2016 Alex Forencich 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...
unosviluppatore/antlr-mega-tutorial
antlr-python/HtmlChatListener.py
import sys from antlr4 import * from ChatParser import ChatParser from ChatListener import ChatListener class HtmlChatListener(ChatListener) : def __init__(self, output): self.output = output self.output.write('<html><head><meta charset="UTF-8"/></head><body>') def enterName(self, ctx:ChatPars...
alisaifee/mock-matchers
setup.py
""" setup.py for mock.matchers """ __author__ = "Ali-Akber Saifee" __email__ = "ali@indydevs.org" __copyright__ = "Copyright 2014, Ali-Akber Saifee" from setuptools import setup, find_packages import os this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter(None, open( os.path.join(this_dir,...
nitely/http-lazy-headers
tests/tests_fields_/tests_content_location.py
# -*- coding: utf-8 -*- import http_lazy_headers as hlh from . import utils class ContentLocationTest(utils.FieldTestCase): field = hlh.ContentLocation def test_raw_values(self): self.assertFieldRawEqual( ['/rfc7231.html'], ('/rfc7231.html',)) self.assertFieldRawEq...
dstenb/pylaunchr-emulator
emulator/data.py
from pygametk.filter import CombinedFilter from pygametk.store import CombinedStore, FilteredStore, Store from pylaunchr.builder.factory import StoreFactory from pylaunchr.persistent.bookmark import BookmarkStore from pylaunchr.persistent.mru import MostRecentlyUsedStore from .filter import EmulatorRomTitleFilter fro...
isudox/leetcode-solution
python-algorithm/leetcode/problem_129.py
"""129. Sum Root to Leaf Numbers https://leetcode.com/problems/sum-root-to-leaf-numbers/ Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. ...
z33pX/Stock-Price-Prediction-With-Indicators
mpl_finance_ext/mpl_finance_ext.py
import matplotlib.pyplot as plt import matplotlib.transforms as mtrans import numpy as np import pandas as pd from matplotlib.collections import LineCollection, PolyCollection from matplotlib.patches import BoxStyle from six.moves import xrange, zip from angled_box_style import AngledBoxStyle from candlestick_pattern_...
homeworkprod/better-bomb-defusal-manual
bombdefusalmanual/ui/console.py
# -*- coding: utf-8 -*- """ Console user interface to ask questions and collect answers. :Copyright: 2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from .models import Choice class ConsoleUI(object): def ask_for_text(self, question_label): display_question(question_label) ...
timatooth/yahs
setup.py
from setuptools import setup setup( name='yahs', version='1.1', # packages=[''], package_dir={'': 'src'}, py_modules=['yahs'], keywords = ["http", "rest", "json", "decorator"], url='https://github.com/timatooth/yahs', license='MIT', author='Tim Sullivan', author_email='tsullivan...
MrJarv1s/FEMur
FEMur/__init__.py
""" FEMur.py This module introduces a few concepts of the Finite Element Method (FEM) and aims at providing a number of tools for solving FEM-related problems. Its development was started in order to solve problems and projects related to the SYS806 'Application of the Finite Element Method' Class at 'Ecole de techno...
bash/status_codes
status_codes/transform.py
# # (c) 2016 Ruben Schmidmeister # import csv import io def transform(data): reader = csv.DictReader(io.StringIO(data), fieldnames=['Value', 'Description', 'Reference'], dialect='unix') document = {} # skip headers next(reader) for row in reader: description = row['Description'] ...
yoe/veyepar
dj/scripts/process.py
#!/usr/bin/python # abstract class for processing episodes import optparse import configparser import os,sys,subprocess,socket import datetime,time import fixunicode os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj.settings") sys.path.insert(0, '..' ) sys.path.insert(0, '../lib' ) from django.conf import settin...
jpiper/pyDNase
pyDNase/scripts/dnase_to_JSON.py
#!/usr/bin/env python import argparse, pyDNase from clint.textui import puts, progress parser = argparse.ArgumentParser(description='Writes a JSON file of DNase I cuts for regions from a BED file') parser.add_argument("-w", "--window_size", help="Resize all regions to a specific length",default = 0, type=int) parser.ad...
andela-hoyeboade/bucketlist-api
app/helpers.py
import jwt from flask import current_app from flask_restful import abort from .models import User, BucketListItem, db def get_current_user_id(token): '''Returns current user_id based on the token supplied ''' try: secret_key = current_app.config.get('SECRET_KEY') decoded = j...
ta2xeo/python3-kii
kii/acl/scope/application.py
from kii.acl.base import ( ACLBaseRequest, ACLVerbMixin, ACLVerbType, SubjectType, SubjectTypeMixin, ) class RetrieveTheCurrentACLEntries(ACLBaseRequest, ACLVerbMixin): paths = { ACLVerbType.all: '/apps/{appID}/acl', ACLVerbType.acl_verb: '/apps/{appID}/acl/{ACLVerb}' } def __init...
variable/django-rest-framework-queryset
rest_framework_queryset/pagination.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination class HybridPagination(PageNumberPagination): """ Basically allows both pagination method to work within a single pagination class. By default it uses the PageN...
eigenn/flaskengine
tests/views/test_list.py
from .base import BaseTest, TestModel, BpAppRegister, test_bp from flaskengine import ModelList class ListTestView(ModelList): model = TestModel admin = False view_actions = [] ListTestView.register_bp(test_bp) class ListTestViewCustom(ModelList): model = TestModel admin = False view_action...
yigitbasalma/EQL
source/eql.py
#!/usr/bin/python # -*- coding: utf-8 -*- from couchbase.bucket import Bucket from multiprocessing import Process from geoip import geolite2 import requests import datetime import ConfigParser import couchbase import sqlite3 import time import os import hashlib as h class Db(object): def __init__(self, method)...
blondegeek/pymatgen
pymatgen/io/lobster.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License import re import numpy as np import warnings import collections import os from monty.io import zopen from monty.serialization import loadfn from monty.json import MSONable import fnmatch import itertools import...
vovanbo/aiohttp_json_api
examples/simple/main.py
#!/usr/bin/env python """Simple JSON API application example with in-memory storage.""" import asyncio import logging from collections import defaultdict, OrderedDict import time from aiohttp import web from aiohttp_json_api import setup_jsonapi from aiohttp_json_api.common import JSONAPI def setup_fixtures(app): ...
plaid/plaid-python
plaid/model/numbers_eft.py
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
twisted/twistedchecker
twistedchecker/functionaltests/docstring_fail.py
# enable: W9201,W9202,W9203,W9204,W9205,W9206,W9207,W9208,W9209 """ A docstring with a wrong indentation. Docstring should have consistent indentations. """ class foo: '''The opening/closing of docstring should be on a line by themselves''' def a(self): """ A docstring with a wrong indenta...
evfredericksen/gmapsbounds
gmapsbounds/llpx.py
import math # Constants # ========= # My knowledge of what these mean is undefined. CBK = [128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296, 85899345...
rpschill/vanessaschill
blog/models.py
from __future__ import unicode_literals from datetime import datetime from django.db import models from django.conf import settings from django.urls import reverse from model_utils import Choices from model_utils.fields import StatusField, MonitorField, SplitField from model_utils.models import TimeStampedModel, Sta...
markuskiller/textblob-de
textblob_de/blob.py
# -*- coding: utf-8 -*- # Code adapted from the main `TextBlob`_ library. # # :repo: `https://github.com/sloria/TextBlob`_ # :source: textblob/blob.py # :version: 2013-10-21 (a88e86a76a) # # :modified: 2014-09-17 <m.killer@langui.ch> # """Wrappers for various units of text. This includes the main :class:`TextBlobDE <t...
jdurbin/sandbox
python/plotting/matrix_with_track.py
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np; np.random.seed(0) Z = np.random.poisson(lam=6, size=(64,64)) x = np.mean(Z, axis=0) y = np.mean(Z, axis=1) fig, ax = plt.subplots() ax.imshow(Z) # create new axes on the right and on the top of the current axe...
hgamboa/novainstrumentation
novainstrumentation/panthomkins/panthomkins.py
# pylint: disable=C0103 import numpy as np from novainstrumentation.panthomkins.butterworth_filters import butter_bandpass_filter from novainstrumentation.panthomkins.detect_panthomkins_peaks import detect_panthomkins_peaks from novainstrumentation.panthomkins.rr_update import rr_1_update, rr_2_update, sync def pan...
pycontw/pycontw2016
src/reviews/migrations/0014_auto_20160326_0240.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-26 02:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reviews', '0013_auto_20160322_1100'), ] operations = [ migrations.AlterField...
Great-Li-Xin/PythonDev
ClassRoom/Experiment/sy1/start.py
# # start.py # Experiment I # # Created by 李欣 on 2017/4/26. # Copyright © 2017年 李欣. All rights reserved. # # imports ============================================================================================================== import math from pprint import pprint import time import random # Factories && UI =...
chrisforrette/django-social-content
social_content/services/facebook_service.py
import json import urllib2 import dateutil.parser from social_content.conf import settings from .base import BaseSocialContentService class Service(BaseSocialContentService): """Accessing Facebook page public feeds requires a facebook 'app_id' and 'app_secret'.""" social_content_type = 'facebook' grap...
CERNatschool/fast-cluster-analysis
cernatschool/test_dataset.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #...the usual suspects. import os, inspect #...for the unit testing. import unittest #...for the logging. import logging as lg #...for the dataset wrapper. from dataset import Dataset class DatasetTest(unittest.TestCase): def setUp(self): pass def tea...
ppnchb/django-board
django_board/api_v1/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-14 08:37 from __future__ import unicode_literals import autoslug.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): initial...
chrismattmann/trec-dd.org
s3-data-sets/local-politics-read-example-script.py
#!/bin/env python '''This script illustrates how to download and access the `local politics` subcorpus within TREC DD This particular corpus is a selection of the TREC KBA 2014 StreamCorpus that has already been tagged with Serif NER, and is organized into hourly directories based on the origination time stamp on each...
DenXX/web_search_api
web_search_api/search_provider.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implements base SearchResult and Serp (search engine results page) classes. Copyright (C) 2013 Denis Savenkov <denissavenkov@gmail.com> """ from abc import abstractmethod class SearchResult: """ Represents one web search result """ def __init__(self...
nkmk/python-snippets
notebook/pandas_to_csv.py
import pandas as pd df = pd.read_csv('data/src/sample_pandas_normal.csv', index_col=0) print(df) # age state point # name # Alice 24 NY 64 # Bob 42 CA 92 # Charlie 18 CA 70 # Dave 68 TX 70 # Ellen 24 CA 88 # Frank 30 NY ...
fbcom/project-euler
027_quadratic_primes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # A Solution to "Quadratic primes" – Project Euler Problem No. 27 # by Florian Buetow # # Sourcecode: https://github.com/fbcom/project-euler # Problem statement: https://projecteuler.net/problem=27 # def is_prime(n): if n < 2: return False if n == 2: ...
kaltsimon/crypto-challenges
src/fixed_xor.py
"""Perform fixed length XOR operations.""" from encode_decode import decode_hex, encode_hex def xor_hex(hex_1, hex_2): """XOR two fixed length hex strings.""" return encode_hex(xor(decode_hex(hex_1), decode_hex(hex_2))) def xor(bytes_1, bytes_2): """XOR two bytearrays of the same length.""" l1 = le...
lorien/grab
tests/grab_redirect.py
from test_server import Response from grab.error import GrabTooManyRedirectsError from tests.util import BaseGrabTestCase, build_grab def build_location_callback(url, counter): meta = { "counter": counter, "url": url, } def callback(): if meta["counter"]: status = 30...
derrickyoo/python-jumpstart
apps/06_cat_factory/program.py
import os import cat_service import platform import subprocess def main(): print_header() folder = get_or_create_output_folder() print('Found or created folder: {}'.format(folder)) download_cats(folder) display_cats(folder) def print_header(): print('-----------------------------------------...
tommasoberlose/p2p_kazaa
Package.py
import Constant as const import Function as func # PKT SN def request_sn(ip, port): pk_id = func.random_pktid(const.LENGTH_PKTID) port = func.format_string(port, const.LENGTH_PORT, "0") step = func.format_string(const.TTL_SN, const.LENGTH_TTL, "0") pack = bytes(const.CODE_SN, "ascii") + bytes(pk_id, "ascii") + by...
rozifus/TeamStrong13_4
setup.py
import os # usage: python setup.py command # # sdist - build a source dist # py2exe - build an exe # py2app - build an app # cx_freeze - build a linux binary (not implemented) # # the goods are placed in the dist dir for you to .zip up or whatever... APP_NAME = 'por' DESCRIPTION = open('README.txt').read() CHANGES =...
xjlin0/cs246
w2015/hw1/q2_browsing_spark_t2.py
# Under the PySpark shell, type: # execfile('q2_browsing_spark.py') import itertools def parseSingle(line): return [ (single, 1) for single in line.split() ] def parseSet(line, itemSetSize=2): return [ ((itemSet[0], itemSet), 1) for itemSet in list(itertools.permutations(line.split(), itemSetSize))] s ...
bworrell/cutiestix
setup.py
#!/usr/bin/env python # Copyright (c) 2015 - Bryan Worrell # For license information, see the LICENSE file import os import setuptools BASE_DIR = os.path.dirname(os.path.abspath(__file__)) VERSION_FILE = os.path.join(BASE_DIR, "cutiestix", 'version.py') README_FILE = os.path.join(BASE_DIR, "README.md") def norm...
jefftc/changlab
Betsy/Betsy/modules/create_realign_targets.py
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, out_path): import os from genomicode import filelib from genomicode im...
Yu-Yan/autumn
autumn/autumn/models.py
from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType # Create your models here. #model for author, using onetoonefield to link user object class Author(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=5...
hswhite33/picturegame-bot
src/utils/Retry.py
import logging from time import sleep import traceback from prawcore import exceptions def retry(action): def actionWithRetry(*args, **kwargs): '''Perform the given action. If an exception is raised, retry every ten seconds Return the return value of the action, if any''' failCount = 0 ...
arvindkandhare/mosaicme
mosaicme/collector/collector.py
from __future__ import absolute_import, print_function import argparse from boto.s3.connection import S3Connection import boto import pika from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream from tasks import process_image import json import logging import logging.co...
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_04_01/aio/operations/_resource_skus_operations.py
# 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 ...
vasili-v/percolator
test/test_runner.py
import unittest from percolator.runner import Runner from percolator.parsers.null import Null from percolator.parsers.collector import Collector class TestRunner(unittest.TestCase): def test_creation_default(self): Runner() def test_creation_environment(self): Runner(Null, Null, {'PATH': '/ho...
flav-io/flavio
flavio/physics/scattering/test_ee_ww.py
import unittest from flavio import sm_prediction, np_prediction import wilson import numpy as np Es = np.array([161.3, 172.1, 182.7, 188.6, 191.6, 195.5, 199.5, 201.6, 204.9, 206.6]) class TestEEWW(unittest.TestCase): def test_ee_ww_SM(self): for E in Es: self.assertEqual(sm_prediction('R(e...
1tush/reviewboard
reviewboard/webapi/tests/mixins_review.py
from __future__ import unicode_literals from reviewboard.webapi.tests.mixins import test_template from reviewboard.webapi.tests.mixins_extra_data import (ExtraDataItemMixin, ExtraDataListMixin) class ReviewListMixin(ExtraDataListMixin): @test_template d...
RossLote/cloudplayer
music/migrations/0011_album_cover_image.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('music', '0010_auto_20150118_2110'), ] operations = [ migrations.AddField( model_name='album', name='...
lucafon/DesignPatterns
lucafontanili.designpatterns.python/src/creational/abstractfactory/WidgetFactory.py
''' Created on Nov 3, 2016 @author: Admin ''' from Window import * class MSWindowWidgetFactory: @staticmethod def make_diagram(width, height): return MSWindow() class MacOSXWindowWidgetFactory: @staticmethod def make_diagram(width, height): return MacOSXWindow()
iandennismiller/gthnk
src/scripts/gthnk-config-init.py
#!/usr/bin/env python3 import os import sys import click import random template = """ # Gthnk Configuration WEB_JOURNAL_FILE = "{gthnk_path}/journal-web.txt" INPUT_FILES = "{gthnk_path}/journal-web.txt,{gthnk_path}/journal.txt" BACKUP_PATH = "{gthnk_path}/backup" EXPORT_PATH = "{gthnk_path}/export" SQLALCHEMY_DATA...
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
""" Module containing BestFit abstract class """ import numpy as np from abc import ABCMeta, abstractmethod class BestFit(object): """ Base class for bestfit """ __metaclass__ = ABCMeta # variables needed to do bestfit important_variables = set(['x', 'y']) def __init__(self, **kwargs): ...
spirit-code/spirit
core/python/spirit/hamiltonian.py
""" Hamiltonian ==================== Set the parameters of the Heisenberg Hamiltonian, such as external field or exchange interaction. """ import spirit.spiritlib as spiritlib import ctypes ### Load Library _spirit = spiritlib.load_spirit_library() ### DM vector chirality CHIRALITY_BLOCH = 1 """DMI Bloch c...
TeamHG-Memex/agnostic
agnostic/postgres.py
import os import subprocess import pg8000 from agnostic import AbstractBackend class PostgresBackend(AbstractBackend): ''' Support for PostgreSQL. ''' def backup_db(self, backup_file): ''' Return a ``Popen`` instance that will backup the database to the ``backup_file`` handle. ...
neilLasrado/frappe
frappe/core/doctype/doctype/doctype.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import six import re, copy, os, subprocess import frappe from frappe import _ from frappe.utils import now, cint from frappe.model import no_value_fields, default_fields from f...
ofek/hatch
tests/conftest.py
import os import subprocess import sys from functools import lru_cache from io import BytesIO from typing import Generator import pytest from click.testing import CliRunner as __CliRunner from platformdirs import user_cache_dir, user_data_dir from hatch.config.constants import AppEnvVars, ConfigEnvVars, PublishEnvVar...
TEJESH/gandhi
tests/user_test.py
from goodreads import apikey from goodreads.client import GoodreadsClient from goodreads.user import GoodreadsUser from goodreads.group import GoodreadsGroup from goodreads.owned_book import GoodreadsOwnedBook from goodreads.review import GoodreadsReview from goodreads.shelf import GoodreadsShelf from nose.tools import...
oksuz/html2pdf
pdfservice.py
from flask import Flask, request, make_response from tempfile import NamedTemporaryFile from wkhtmltopdf import wkhtmltopdf import os ip, port = "0.0.0.0", 8080 app = Flask(__name__) app.debug = False @app.route("/ping", methods=["GET"]) def ping(): return "PONG!" @app.route("/makepdf", methods=["POST"]) def m...
xebialabs-community/xlr-servicenow-plugin
src/main/resources/servicenow/Server.py
# # Copyright 2019 XEBIALABS # # 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, subli...
qeedquan/misc_utilities
math/abel-polynomial.py
""" https://en.wikipedia.org/wiki/Abel_polynomials """ from sympy import * from sympy.abc import * import sys import os def memoize(f, a): memo = {} def helper(x): if x not in memo: memo[x] = expand(simplify(f(a, x))) return memo[x] return helper def abel(a, n): ...
robertsj/poropy
pyqtgraph/examples/test_ImageItem.py
# -*- coding: utf-8 -*- ## Add path to library (just for examples; you do not need this) import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) from PyQt4 import QtCore, QtGui import numpy as np import pyqtgraph as pg app = QtGui.QApplication([]) ## Create window with GraphicsView wi...
vicky002/Charmander
charmander/extensions/log.py
""" Log all messages to the database only active If the CHARMANDER_LOG environment variable is set. """ import os DO_LOG = os.environ.get("CHARMANDER_LOG", False) def on_message(msg, server): if DO_LOG: server.query("INSERT INTO log VALUES (?, ?, ?, ?)", msg["text"], msg["user"], ...
pwgn/microtut
commentservice/comments.py
import time class Comments(): def __init__(self): self.threads = {} def add(self, thread_id, data): message_id = str(time.time()).replace('.', '') message = { 'id': message_id, 'message': data['message'] } if thread_id in self.threads: ...
UASLab/ImageAnalysis
scripts/3e-show-features.py
#!/usr/bin/env python3 import sys import argparse import cv2 import fnmatch import os.path from lib import project # for all the images in the project image_dir, detect features using the # specified method and parameters parser = argparse.ArgumentParser(description='Load the project\'s images.') parser.add_argume...
rusty1s/embedded_gcnn
lib/layer/embedded_gcnn_test.py
import tensorflow as tf import numpy as np from numpy import pi as PI from numpy.testing import assert_almost_equal import scipy.sparse as sp from .embedded_gcnn import conv, EmbeddedGCNN from ..tf.convert import sparse_to_tensor class EmbeddedGCNNTest(tf.test.TestCase): def test_conv_K2_P4(self): featur...
icymorn/magnetic-info-process
graph/Basic.py
from matplotlib import pyplot as plt from matplotlib import style style.use('ggplot') class BasicGraph(object): def __init__(self, name = "chart", xlabel = "X axis", ylabel = "Y axis"): self.title = name self.xlabel = xlabel self.ylabel = ylabel plt.figure() def show(self): ...
DavidSchott/ChatBot
chatbot/cornelldata.py
#!/usr/bin/env python3 # Copyright 2015 Conchylicultor. 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 req...
spatialaudio/panorama
Python/createPtFile.py
from sys import stderr import configparser import argparse from python_core_components.ptfile_creator import PtCreator from python_core_components.batfile_creator import BatCreator from python_core_components.varisphear import VariSphear def arg_options(): # init options parser = argparse.ArgumentParser( ...
matus-chochlik/various
qt_course/examples/.ycm_extra_conf.py
# Copyright Matus Chochlik. # Distributed under the Boost Software License, Version 1.0. # See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt import os import ycm_core def default_opts(): qtdir = 'qt5' result = [ '-pedantic', '-Wall', '-Weverything', '-Werror', '-Wno...
AgapiGit/RandomPasswordGenerator
RandomPasswordGenerator/generate/views.py
from django.shortcuts import render import random, string from random import shuffle from django.template.response import SimpleTemplateResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. def RandomPasswordGenerator(request): return render(request, 'RandomPasswordGen...
gosom/matrix-multiplication-benchmark
ijk-algorithm.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script is (almost) copied from http://martin-thoma.com/matrix-multiplication-python-java-cpp/ """ import argparse import sys import time import dummy_matrix_mul def read(f): lines = f.read().splitlines() A = [] B = [] matrix = A for line in lines...
codelv/enaml-native
src/enamlnative/android/android_radio_button.py
""" Copyright (c) 2017-2022, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on May 20, 2017 @author: jrm """ from atom.api import Typed from enamlnative.widgets.radio_button import ProxyRadioButton from .android_compoun...
ComputerScienceHouse/conditional
conditional/blueprints/housing.py
import structlog from flask import Blueprint, request, jsonify from conditional import db, auth from conditional.models.models import FreshmanAccount from conditional.models.models import InHousingQueue from conditional.util.auth import get_user from conditional.util.flask import render_template from conditional.util....
tobier/yace
tests/test_memory.py
# Copyright (c) 2019 Tobias Eriksson # # 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...
gisce/sii
sii/models/basic_models.py
# -*- coding: utf-8 -*- from sii.utils import VAT class Period: def __init__(self, name): self.name = name class Company: def __init__(self, partner_id): self.partner_id = partner_id class Country: def __init__(self, code): self.code = code class ComunidadAutonoma: def __...
charettes/django-sundial
tests/test_fields/tests.py
import pytz from django.conf import settings from django.core.exceptions import ValidationError from django.test import TestCase from sundial.fields import TimezoneField from sundial.zones import COMMON_GROUPED_CHOICES from .models import TimezoneModel default_timezone = pytz.timezone(settings.TIME_ZONE) class Tim...
Aurora0000/descant
forums/migrations/0006_auto_20150515_1754.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('forums', '0005_auto_20150515_1731'), ] operations = [ migrations.CreateModel( name=...
jtimon/bitcoin
test/functional/wallet_basic.py
#!/usr/bin/env python3 # Copyright (c) 2014-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 the wallet.""" from decimal import Decimal import time from test_framework.test_framework import ...
AutorestCI/azure-sdk-for-python
azure-batch/azure/batch/models/pool_resize_parameter.py
# 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 ...
ciarams87/PyU4V
PyU4V/utils/console.py
# Copyright (c) 2020 Dell Inc. or its subsidiaries. # # 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...
DevicePilot/synth
synth/devices/helpers/wind/whitelees.py
#!/usr/bin/env python # # Co-ordinates and utility functions for simulating # Whitelees windfarm near Ayr, Scotland # # Copyright (c) 2017 DevicePilot Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # i...
leanix/leanix-sdk-python
src/leanix/models/FactSheetHasRequires.py
#!/usr/bin/env python """ The MIT License (MIT) Copyright (c) 2017 LeanIX GmbH 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,...
foodsnag/foodsnag-web
app/auth/views.py
from flask import render_template, redirect, request, url_for, flash, jsonify from flask.ext.login import login_user, logout_user, login_required, current_user from . import auth from ..extensions import db from ..models import User, Location from .forms import LoginForm, RegistrationForm from autocomplete.views import...
ctasims/Dive-Into-Python-3
ch06-closures-generators/plural4.py
import re def build_match_and_apply_functions(pattern, search, replace): """ Build match and apply functions based on given re pattern, search text, and replacement. """ def matches_rule(word): """ Check if word contains pattern. """ return re.search(pattern, word) def ap...
PostCenter/botlang
botlang/evaluation/evaluator.py
from functools import reduce from botlang.ast.ast_visitor import ASTVisitor from botlang.evaluation.values import * class ExecutionStack(list): def print_trace(self): from botlang.macros.default_macros import DefaultMacros return reduce( lambda a, n: a + n + '\n', [ ...
AntonHerrNilsson/the-dungeon
utils.py
import numpy # Transform matrices IDENTITY = numpy.array(((1,0), (0,1))) ROTATE_LEFT = numpy.array(((0,-1), (1, 0))) ROTATE_RIGHT = numpy.array((( 0,1), (-1,0))) def rotate_back_matr...
ToonTownInfiniteRepo/ToontownInfinite
toontown/ai/NewsManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI class NewsManagerAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("NewsManagerAI") def setPopulation(self, todo0): pass def setBingoWin(self, todo...
FelixWolf/pyverse
pyverse/packet.py
from . import messages from . import zerocode import struct class packet: """Load a packet""" #Body byte data, incase we need it bytes = b"" body = None MID = 0 sequence = 0 extra = b"" acks = [] #Flags flags = 0 zero_coded = 0 reliable = 0 resent = 0 ack = T...
shunw/pythonML_code
mushroom_wen.py
import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sns from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.learning_curve import validation_curve from sklearn.linear_model import LogisticRegression from sk...
MircoT/AI-Project-PlannerEnvironment
agents_dir/errorObjs.py
""" This contains all error handling functions for the logistic Environment Module. """ class Error(Exception): """Base class for exceptions in this module.""" pass class ActionNotAList(Error): """Exception raised when goal is not plausible.""" def __str__(self): return "Actions p...
cyberdelia/atomic
docs/conf.py
# -*- coding: utf-8 -*- # # atomic documentation build configuration file, created by # sphinx-quickstart on Thu Mar 22 11:39:06 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
Unidata/netcdf4-python
test/tst_chunk_cache.py
import unittest, netCDF4, tempfile, os file_name = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name cache_size = 10000 cache_nelems = 100 cache_preempt = 0.5 cache_size2 = 20000 cache_nelems2 = 200 cache_preempt2 = 1.0 class RefCountTestCase(unittest.TestCase): def setUp(self): nc = netCDF4....