repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
fujy/ROS-Project
src/rbx2/rbx2_tasks/nodes/patrol_smach_concurrence.py
#!/usr/bin/env python """ patrol_smach_concurrence.py - Version 1.0 2013-04-12 Control a robot using SMACH to patrol around a square a specified number of times while monitoring battery levels using the Concurrence container. Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2013...
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-language-spellcheck/azure/cognitiveservices/language/spellcheck/__init__.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 ...
Pouf/CodingCompetition
CG/medium_skynet-revolution-episode-1.py
# Skynet's network is divided into several smaller networks, in each # sub-network is a Skynet agent tasked with transferring information by moving # from node to node along links and accessing gateways leading to other # sub-networks. # Your mission is to reprogram the virus so it will sever links in such a wa ...
fabiocostapro/fiberappz
mainapp/models/tables.py
from mainapp import db from werkzeug.security import generate_password_hash from werkzeug.security import check_password_hash import datetime class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) name = db.Column(db...
mrsan22/Angular-Flask-Docker-Skeleton
server/tests/base.py
"""Base Unit Test Case""" import unittest from server.main.api import create_app_blueprint from server.main import db from server.tests import config_name class BaseTestCase(unittest.TestCase): """A base class for test setup""" def create_app(self): # create a new instance of app app = create...
eggplant60/temp_bot
am2320.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Todo: ログ出力用のバッファを実装 import smbus import time import datetime import threading address = 0x5c # 1011100(7bit,0x5c) + 0(1bit,R/W bit) = 0xb8 READ_INT = 5 # [sec], each reading interval is to be grater than 2 sec LOG_INT = 600 # [sec] DEBUG_MODE = True # 日時付きでメッセージ表示 def ...
andrewyoung1991/supriya
supriya/tools/ugentools/PauseSelfWhenDone.py
# -*- encoding: utf-8 -*- from supriya.tools.ugentools.UGen import UGen class PauseSelfWhenDone(UGen): r'''Pauses the enclosing synth when `source` sets its `done` flag. :: >>> source = ugentools.Line.kr() >>> pause_self_when_done = ugentools.PauseSelfWhenDone.kr( ... source=sour...
harperreed/cta_clock
cta_clock.py
import time import requests import logging import sys try: import wink except ImportError as e: import sys sys.path.insert(0, "..") import wink from xml.etree import cElementTree as ET import datetime from collections import defaultdict def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} ...
Sirikam/Gravitas
apps/users/migrations/0011_auto_20170405_1051.py
# -*- coding: utf-8 -*- # Generated by Django 1.11rc1 on 2017-04-05 08:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0010_auto_20170403_1315'), ] operations = [ migrations.AlterField...
andrewyoung1991/supriya
supriya/tools/ugentools/TIRand.py
# -*- encoding: utf-8 -*- from supriya.tools.ugentools.UGen import UGen class TIRand(UGen): r'''A triggered integer random number generator. :: >>> trigger = ugentools.Impulse.ar() >>> t_i_rand = ugentools.TIRand.ar( ... minimum=0, ... maximum=127, ... tri...
shawiz/idlebook
idlebook/data/amazon_import.py
from amazonproduct import * import urllib2 from django.core.management import setup_environ import settings setup_environ(settings) from django.db import connection, transaction from book.models import Book AWS_KEY = 'AKIAI6M6RNJTOTRN7M4Q' SECRET_KEY = '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' api = A...
physicalattraction/kerstpuzzel
src/AIVD2020/color_field.py
from collections import Counter from prime import prime_factorize msg = '''gGGbGbBgrgBBggBGGBgbgRbggGgbB GbGgrggGGGRBGGGrgGgbbbBGBGGbb ggBgbgggRbGBGBGgGBrgbgrGBBGGG RGggBgbgggGgGBgGGgGBgRgggGGBg GBbgGrgGrBBGbBbBbgbrbGGGGRBgB GbbbbbBGBGgBbggbBrgbgGGBGgGBb GgBbbggbBRBbGgbrGGgGGGGBBgrgB BgbGgrbbgGBRBBBbgrBbbgbBrBGBG GBb...
aps-parallels/sphinx-eclipse
sphinx_eclipse/ctxhelp.py
import os import warnings import types from docutils import nodes from sphinx.util.compat import Directive, make_admonition from sphinx.util.osutil import os_path class CtxHelpNode(nodes.General, nodes.Element): pass def visit_CtxHelpNode(self, node): self.visit_admonition(node) def depart_CtxHelpNode(sel...
evasilchenko/castle
core/enemy.py
from pygame.sprite import LayeredUpdates from core.character import Character, CharacterManager class EnemyManager(CharacterManager): def __init__(self, *args, **kwargs): super(EnemyManager, self).__init__(*args, **kwargs) self.enemies = [] self.active_enemies = LayeredUpdates() def ...
team-diana/generic_input_controller
scripts/controller.py
#!/usr/bin/env python """controller.py A configurable node that can command many ros topics using different kind of inputs. Usage: controller.py [--config=FILE_NAME] Options: -h --help Show this screen. --config=FILE_NAME Uses the configuration written in FILE_NAME (must be a .yaml file) """ from ...
TheShellLand/pies
v3/scripts/testing/empireofcode/simple-areas.py
def simple_areas(*args): if len(args) == 0: return 0 # Circle if len(args) == 1: for unknown_args in args: diameter = round(unknown_args, 8) radius = round(diameter / 2, 8) pi = round(3.14159265, 8) area_circle = round((radius ** 2) * pi, 8) prin...
djpnewton/beerme
runserver.py
#!/usr/bin/python from beerme import app import os host = os.getenv('HOST', '127.0.0.1') port = int(os.getenv('PORT', 5000)) # get filenames before daemonizing app_log_filename = os.path.realpath('log/beerme.log') access_log_filename = os.path.realpath('log/access.log') def log_app(): import cherrypy from p...
sburnett/seattle
network_semantics_tests/tests/stopcomm/stopcomm_basic2.py
# after stopcomm is called on a recvmess handle # the listener is stopped and stopcomm returns true def echo(rip,rport,sg,lh): sock.close() if callfunc == "initialize": ip = '127.0.0.1' waitport = 12345 # the waitfor conn we will connect to handle = recvmess(ip,waitport,echo) stopped = stopcomm...
pmonta/GNSS-DSP-tools
gnsstools/gps/l2cl.py
# GPS L2CL code construction # # Copyright 2014 Peter Monta import numpy as np chip_rate = 511500 code_length = 767250 # initial-state table from pages 9--11 and pages 62--63 of IS-GPS-200H # index is PRN l2cl_init = { 1: 0o624145772, 2: 0o506610362, 3: 0o220360016, 4: 0o710406104, 5: 0o001143345, ...
vechnoe/clinic
src/settings.py
""" Django settings for src project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths insi...
azogue/hass_config
python_scripts/select_light_profile.py
""" # Python script to select light scenes from an input_select. Hue profiles (x, y, bright): - relax 0.5119 0.4147 144 - energize 0.368 0.3686 203 - reading 0.4448 0.4066 240 - concentrate 0.5119 0.4147 219 <--BAD --> brightness: 254 xy_color: [0.3151, 0.3251] """ INPUT_SELECT = 'input_select.salon_light...
frank-deng/retro-works
telnet-ppp-server/setup.py
#!/usr/bin/env python3 import os,sys; from setuptools import setup; if 'linux'!=sys.platform: print("This package only supports Linux platform."); exit(1); setup( name = 'telnet-ppp-server', # 在pip中显示的项目名称 version = '0.1', author = 'Frank', author_email = '', license = 'MIT', url = ''...
masom/shopify-trois
shopify_trois/models/order_risk.py
# -*- coding: utf-8 -*- ''' shopify_trois.models.order_risk Shopify-Trois OrderRisk :copyright: (c) 2015 Martin Samson :license: MIT, see LICENSE for more details. ''' from .model import Model from .order import Order class OrderRisk(Model): ''' Page http://docs.shopify.com/api/orderrisk ...
dr-rodriguez/The-Divided-States-of-America
scripts/twitter_sampling.py
# Quick plot on when I gathered the data from tweetloader import TweetLoader import matplotlib.pyplot as plt import matplotlib.dates as dates import pandas as pd import matplotlib.patches as mpatches def count_and_plot(raw, ax, start='2016-1-1', end='2016-6-24', freq='D', color='blue'): df = raw.copy() df.ind...
b3j0f/utils
b3j0f/utils/property.py
# -*- coding: utf-8 -*- # -------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2014 Jonathan Labéjof <jonathan.labejof@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
ChristfriedBalizou/jeamsql
adapters/adapter.py
from tabulate.tabulate import tabulate import subprocess import sys import os import re import csv import io import json class Adapter(object): def __init__(self, server=None, port=None, user=None, connection_cmd=None, cmd=None, test_query=...
Azure/azure-sdk-for-python
sdk/containerregistry/azure-containerregistry/samples/sample_hello_world.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. # --------------------------------------------------------------------...
ynop/spych
spych/audio/signal.py
import os import numpy as np import scipy.io.wavfile from spych.assets import audacity def calculate_energy_of_samples(samples): """ Calculate the energy of a signal. :param samples: The samples of the signal. :return: Energy """ values = np.abs(samples).astype(np.int) if type(values) ...
imcomking/Convolutional-GRU-keras-extension-
kerasR/layers/core.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import theano import theano.tensor as T import numpy as np from collections import OrderedDict import copy from .. import activations, initializations, regularizers, constraints from ..utils.theano_utils import shared_zeros, floatX, ndim_tensor...
pysg/pyther
models_eos.py
import numpy as np from eos_selecction import eos, convert_argument from cubic_parameters_1 import Parameter_eos RGAS = 0.08314472 # Definir el significado fisicoquímico A0, B0, C0 = 0.0017, 1.9681, -2.7238 # Definir el significado fisicoquímico A1, B1, C1 = -2.4407, 7.4513, 12.504 # Definir el significado fisicoquí...
nkmk/python-snippets
notebook/pandas_astype.py
import pandas as pd df = pd.read_csv('data/src/sample_header.csv') print(df) # a b c d # 0 11 12 13 14 # 1 21 22 23 24 # 2 31 32 33 34 s = df['c'] print(s) # 0 13 # 1 23 # 2 33 # Name: c, dtype: int64 s_f = s.astype('float64') print(s_f) # 0 13.0 # 1 23.0 # 2 33.0 # Name: c, d...
Arkanosis/Inkludr
inkludr.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import re import sys _version = '0.1' _include = re.compile(r'^\s*?\#\s*?include\s*[<"](?P<path>[a-zA-Z0-9._-]+)[>"]') def getIncludes(fileName): includes = [] with open(fileName) as source: for line in source: include = _include.match(line) if include: in...
nkrode/autopilot
src/www/app.py
#!/usr/bin/env python import logging import tornado.ioloop from tornado.options import define, options import util.settings from controller.static import BaseStaticFileHandler from controller.home import HomeController from controller.reboot import RebootController from controller.article import ArticleController fr...
jhallard/tinyML
controllers/ml/mnist_cnn.py
#!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.conv...
robdobsn/raspicalprinter
Python/sudoku-txt.py
#!/usr/bin/python # # Sudoku Generator and Solver in 250 lines of python # Copyright (c) 2006 David Bau. All rights reserved. # # Can be used as either a command-line tool or as a cgi script. # # As a cgi-script, generates puzzles and estimates their level of # difficulty. Uses files sudoku-template.pdf/.ps/.txt/.htm...
qxf2/qxf2-page-object-model
utils/results.py
""" Tracks test results and logs them. Keeps counters of pass/fail/total. """ import logging from utils.Base_Logging import Base_Logging class Results(object): """ Base class for logging intermediate test outcomes """ def __init__(self, level=logging.DEBUG, log_file_path=None): self.logger = Base_Log...
rorywalsh/csoundSublime
intellitip.py
import sublime_plugin, sublime, json, webbrowser import re, os from time import time settings = {} class IntellitipCommand(sublime_plugin.EventListener): cache = {} region_row = [] lang = None def on_activated(self, view): Pref.time = time() sublime.set_timeout(lambda:self.run(view, ...
cydenix/OpenGLCffi
generate.py
import sys import os import shutil import parser from urllib2 import urlopen, HTTPError, URLError, Request GL_URL = "https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/api/" GL_REGISTRY_FILES = ["egl.xml", "gl.xml", "glx.xml"] GL_DIRS = ["GL", "GLES1", "GLES2", "GLES3", ...
jprine/monitoring-module
src/monitoring_plots.py
# name=Monitoring plots # displayinmenu=true # displaytouser=true # displayinselector=true from monitoring import plot import toolbox as tb from voluptuous import Schema, All, Any, Range, Datetime, Required, Optional, Lower class PlotTool(tb.Tool): defaultColours = [ [166, 206, 227], [ 31, 120, 1...
hauxir/OpenBazaar-Server
dht/crawling.py
""" Copyright (c) 2014 Brian Muller Copyright (c) 2015 OpenBazaar """ from collections import Counter, defaultdict from twisted.internet import defer from log import Logger from dht.utils import deferredDict from dht.node import Node, NodeHeap from protos import objects class SpiderCrawl(object): """ Craw...
Strawhatspirates/databits
fabfile.py
from fabric.api import local def test(): local('python `which nosetests` -v -d') def deploy(version=None): test() if not version: raise Exception("Please specify the version") _str = "'Upgrading to version {}'".format(version) local('git commit -am {}'.format(_str)) local('git tag -a...
Kuldip397/My_Scrapers
imdbRating.py
####Python Script to find the IMDB rating of movies and TV series##### import requests import bs4 as bs ####Function to confirm the name of movie or Tv series to get the correct rating#### def cnfm_page(link): try: name_link = 'https://www.imdb.com'+link req2 = requests.get(name_link) soup2 = bs...
assaabloy-ppi/salt-channel-python
saltchannel/a1a2/a1_client_session.py
import asyncio from . import packets class A1ClientSession: """""" def __init__(self, channel, loop=None): self.loop = loop or asyncio.get_event_loop() self.channel = channel self.a1 = packets.A1Packet() self.a2 = None async def do_a1a2(self): await self.channel.w...
judithfan/pix2svg
generative/tests/compare_test/adaptor_oneside/train.py
from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import sys import shutil import numpy as np from tqdm import tqdm import torch import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from sklearn.metrics imp...
TeamSPoon/logicmoo_workspace
packs_web/butterfly/lib/python3.7/site-packages/uncompyle6/scanners/scanner26.py
# Copyright (c) 2015-2017 by Rocky Bernstein # Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org> # Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publishe...
mabotech/mabo.io
py/vision/test1/vision2.py
import socket import gevent import cv2.cv as cv import cv2 import numpy as np import itertools import sys import traceback import time def findKeyPoints(img, template, distance=200): detector = cv2.FeatureDetector_create("SIFT") descriptor = cv2.DescriptorExtractor_create("SIFT") skp = detector.dete...
ktok07b6/polyphony
tests/pure/nesting03.py
from polyphony import module, pure from polyphony import testbench from polyphony import is_worker_running from polyphony.io import Port from polyphony.typing import int8 from polyphony.timing import clksleep, wait_value @module class Submodule: @pure def __init__(self, param): self.i = Port(int8, 'in...
pytorch/fairseq
fairseq_cli/eval_lm.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Evaluate the perplexity of a trained language model. """ import logging import math import os import sys from a...
Ben0mega/VideoViewer
play.py
#!/bin/python import subprocess import shutil import shlex def vlc_play(vid): print(vid) if vid['VideoFile'] is None: return cmd = shutil.which('vlc') + ' --fullscreen --play-and-exit' if list(vid['VideoFile']) != vid['VideoFile']: vids = [vid['VideoFile']] subfs = [vid['SubtitleFile']] subts = [vid['Subt...
channelcat/sanic
sanic/touchup/meta.py
from sanic.exceptions import SanicException from .service import TouchUp class TouchUpMeta(type): def __new__(cls, name, bases, attrs, **kwargs): gen_class = super().__new__(cls, name, bases, attrs, **kwargs) methods = attrs.get("__touchup__") attrs["__touched__"] = False if meth...
schae234/PonyTools
scripts/crossvalidate.py
#!/usr/bin/env python3 from subprocess import call import sys vcftools = '/home/grad01/schaefer/bin/vcftools' def main(argv): vcffile,id_file = argv # extract the individuals from vcf if not os.path.exists(idfile.replace('.txt','')+'.recode.vcf'): call([vcftools, '--vcf', vcffile...
kevin-brown/six-degrees
data/followers/update.py
import json import os import sqlite3 import sys database_location = sys.argv[1] repo_location = sys.argv[2] json_file_format = repo_location + "/json/%(login)s.json" conn = None try: conn = sqlite3.connect(database_location) cursor = conn.cursor() follower_cursor = conn.cursor() cursor.execute("""...
pythonindia/junction
junction/conferences/migrations/0002_auto_20150109_1527.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("conferences", "0001_initial"), ] operations = [ migrations.AlterModelOptions( name="conferencemoderator", ...
NicholasAsimov/courses
6.00.1x/pset7/ps7.py
import random import math import string class AdoptionCenter: """ The AdoptionCenter class stores the important information that a client would need to know about, such as the different numbers of species stored, the location, and the name. It also has a method to adopt a pet. """ def...
qtile/qtile
libqtile/widget/windowtabs.py
# Copyright (c) 2012-2013 Craig Barnes # Copyright (c) 2012 roger # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 Adi Sieker # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
akleber/ventilation-control
ventilation-control/meteorologist.py
#!/usr/local/bin/python # coding: utf-8 import sys import weathermath import building import database from datetime import datetime def processRoom(room, db): if room.insideSensor.data_available() and room.outsideSensor.data_available(): insideTemp = room.insideSensor.getTemperature() insideRelHum...
Azure/azure-sdk-for-python
sdk/tables/azure-data-tables/samples/sample_query_tables.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. # --------------------------------------------------------------------...
msmathers/SpasmDB
spasm/data/util.py
import time from datetime import datetime def escape(value, field=None): if value is None: return "NULL" elif isinstance(value, bool): return "1" if value else "0" elif field in ['added','created','date']: _format = '%Y-%m-%d %H:%M:%S' if isinstance(value, datetime): ...
emencia/dr-dump
drdump/__main__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import sys import importlib import argparse from drdump.drdump import Drdump, ApplicationsList from drdump.dependancies import DependanciesManager def get_parser(): parser = argparse.ArgumentParser() parser.add_argument( '-m', '...
borkit/scriptdump
AWS/more-aws-scripts/ec2-snap-mgmt.py
#!/usr/bin/env python import sys import boto.ec2 import argparse # List all the snapshots for every volume def snap_x_vol(owner_id): conn = boto.ec2.connection.EC2Connection() snapshots = conn.get_all_snapshots(owner=owner_id) volumes = conn.get_all_volumes() for v in volumes: print "- %s" % (v...
Bhare8972/LOFAR-LIM
LIM_scripts/stationTimings/examples/plot_pulse.py
#!/usr/bin/env python3 from run_Fitter4 import * from LoLIM.stationTimings.timingInspector_4 import plot_all_stations, plot_station #plot_all_stations(40, # # timeID = "D20180809T141413.250Z", # output_folder = "Callibration_1", # pulse_input_folders = ['...
jamesbrobb/django-allauth-ng
allauth_ng/allauth_ng/account/urls.py
from django.conf.urls import patterns, url, include from django.contrib import admin from django.contrib.auth.views import logout from django.views.decorators.http import require_POST from . import views admin.autodiscover() urlpatterns = patterns('', url(r'^logout/$', views.logout), ...
ActiveState/code
recipes/Python/578547_Simple_Method_Compute_Pi/recipe-578547.py
import sys import math def main(argv): if len(argv) != 1: sys.exit('Usage: calc_pi.py <n>') print '\nComputing Pi v.01\n' a = 1.0 b = 1.0/math.sqrt(2) t = 1.0/4.0 p = 1.0 for i in range(int(sys.argv[1])): at = (a+b)/2 bt = math.sqrt(a*b) tt = t - p*(a-at)**2 pt = 2*p a = at;b = bt;t = tt;p...
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_configuration.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 ...
vishnubob/rockit
src/rockit/solid/t_slots.py
#! /usr/bin/python # -*- coding: utf-8 -*- from __future__ import division import os, sys, re # Assumes SolidPython is in site-packages or elsewhwere in sys.path from solid import * from solid.utils import * SEGMENTS = 24 # FIXME: ought to be 5 DFM = 5 # Default Material thickness tab_width = 5 tab_offset = 4 tab_c...
ChrisRackauckas/TBEEF
clean.py
### Cleans the data folder out ### ### Takes an argument, 1 to delete PreProcess folder items ### ### Defaults to 0 ### import os import sys WORK_PATH = os.getcwd() try: delPre = int(sys.argv[1]) == 1 except IndexError: delPre = False os.system("find Data/Effects ! -name README -type f -delete") if delPre: ...
ibogun/complex
process/Dates.py
''' Created on Nov 9, 2013 @author: ivan ''' import re; import numpy as np; import matplotlib as plt import pylab; p = re.compile("\d{4}-\d{1,2}-\d{1,2}"); def ifDate(line): a = p.match(line); if (a is None): return False; else: return True; def getDate(line): ''' If ...
ksamuel/smit
website/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import CustomUser, Settings class CustomUserAdmin(UserAdmin): model = CustomUser fieldsets = [[None, {'fields': ( 'username', 'password', 'is_ac...
sidnarayanan/RelativisticML
old/bdt/vTagging_TMVA.py
#!/usr/bin/env python import numpy as np import ROOT from sys import exit,stderr,stdout from math import isnan loadClassifier=True saveClassifier=False listOfRawVars = ["fjet1QGtagSub1","fjet1QGtagSub2","fjet1QGtag","fjet1PullAngle","fjet1Pull","fjet1MassTrimmed","fjet1MassPruned","fjet1MassSDbm1","fjet1MassSDb2","f...
dshean/pygeotools
pygeotools/replace_ndv.py
#! /usr/bin/env python #David Shean #dshean@gmail.com import sys import os import argparse import numpy as np from osgeo import gdal from pygeotools.lib import iolib #Can use ASP image_calc for multithreaded ndv replacement of huge images #image_calc -o ${1%.*}_ndv.tif -c 'var_0' --output-nodata-value $2 $1 def g...
mpunkenhofer/irc-telegram-bot
telepot/examples/webhook/aiohttp_skeletona.py
import sys import asyncio from aiohttp import web import telepot import telepot.aio """ $ python3.5 aiohttp_skeletona.py <token> <listening_port> <webhook_url> Webhook path is '/abc', therefore: <webhook_url>: https://<base>/abc """ def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg...
OSUrobotics/privacy-interfaces
filtering/probability_filters/scripts/localization_filter/simulate_private_object.py
#!/usr/bin/env python import rospy from geometry_msgs.msg import PointStamped, Point32, PolygonStamped, Vector3Stamped import tf from math import pi class SimulatedObject(): def __init__(self): self.lis = tf.TransformListener() # Init publishers and broadcasters self.br = tf.TransformBro...
danielflower/app-runner
sample-apps/python2/server2.py
"""This is a trivial test script for testing of Python in AppRunner""" import os import platform import flask app = flask.Flask(__name__) app.url_map.strict_slashes = False #Tolerate trailing slashes app_name = os.getenv("APP_NAME", 'python2') HTML = """ <html> <head><title>Python 2 in AppRunner - App {APP_NAME}</tit...
ministryofjustice/cla_backend
cla_backend/apps/legalaid/migrations/0014_personaldetails_contact_for_research_via.py
# coding=utf-8 from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [("legalaid", "0013_auto_20160414_1429")] operations = [ migrations.AddField( model_name="personaldetails", name="contact_for...
Sterncat/opticspy
opticspy/test/test_surface2.py
import numpy as __np__ from numpy import sqrt as __sqrt__ from numpy import cos as __cos__ from numpy import sin as __sin__ import matplotlib.pyplot as __plt__ from matplotlib import cm as __cm__ from matplotlib.ticker import LinearLocator as __LinearLocator__ from matplotlib.ticker import FormatStrFormatter as __Forma...
nitely/Spirit
spirit/comment/migrations/0003_auto_20151115_0400.py
# -*- coding: utf-8 -*- from django.db import migrations, models # todo: remove in Spirit 0.5 def render_comments(apps, schema_editor): # This is due to a changes in the emoji renderer (images -> css) and no-follow links from ...core.utils.markdown import Markdown Comment = apps.get_model("spirit_commen...
bkimo/guacamole
mirt/mirt_engine.py
"""Extend the Engine model to provide a adaptive pretest engine.""" import numpy as np import engine import mirt_util class MIRTEngine(engine.Engine): # ===== BEGIN: Engine interface implementation ===== def __init__(self, model_data): """ Args: model_data: Either a rich object c...
sroehl/python_homeautomation
python_homeautomation/devices/MySensorHumidity.py
import threading import time import queue import paho.mqtt.client as mqtt from python_homeautomation.devices.BaseDevice import BaseDevice class MySensorHumidity(BaseDevice): MODULE = 'MySensorHumidity' UI_FIELDS = [{'name': 'humidity', 'text': 'Humidity', 'type': 'text', 'extra': None}] def monitor(self...
codyhan94/epidemic-graph-inference
scripts/gentree.py
#!/usr/bin/python from __future__ import print_function import sys sys.path.append('.') from graph_inference.graphs.tree import TreeGraph import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument( 'n', help='Number of nodes in tree', type=int) parser.add_argument( ...
darrencheng0817/AlgorithmLearning
Python/leetcode/GuessNumberHigherOrLower.py
''' Created on 1.12.2016 @author: Darren '''''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I ll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns...
piannucci/blurt
blurt_py_80211/streaming/blurt/graph/typing.py
import numpy as np import typing import collections.abc class Cardinal(typing.TypeVar, _root=True): __slots__ = ('__value__') def __init__(self, value): self.__value__ = value if not isinstance(value, int) or value <= 0: raise TypeError("Cardinal must be a positive integer") d...
jesseklein406/data-structures
quick.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals def quick(lst): """ Return a sorted list from an input list using a quicksort algorithm """ if len(lst) < 1: return lst # find median of first, last, and midpoint if lst[-1] < lst[0] == lst[0] < lst...
devrishik/timepost
post_web/post_web/settings/local.py
"""Development settings and globals.""" from os.path import join, normpath from base import * ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG ########## END...
night-crawler/django-docker-helpers
tests/django_settings.py
import os DEBUG = True SECRET_KEY = 'lol' STATIC_URL = '/static/' STATIC_ROOT = './static/' INSTALLED_APPS = [ 'django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.contenttypes', 'django_docker_helpers.cli.django', 'tests.test_app', ] DATABASES = { 'default': { 'EN...
la0rg/Genum
GenumCore/vendor/urllib3/response.py
from __future__ import absolute_import from contextlib import contextmanager import zlib import io from socket import timeout as SocketTimeout from socket import error as SocketError from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ...
dmeklund/asyncdemo
videofeed.py
""" Mock up a video feed pipeline """ import asyncio import logging import sys import cv2 logging.basicConfig(format="[%(thread)-5d]%(asctime)s: %(message)s") logger = logging.getLogger('async') logger.setLevel(logging.INFO) async def process_video(filename): cap = cv2.VideoCapture(filename) tasks = list() ...
chris-void/controller
ryu/adv_L2Switch.py
import struct import logging from ryu.base import app_manager from ryu.controller import mac_to_port from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.lib.mac import haddr_to_bin from ryu.l...
dangerdak/apuniverse
apuniverse/apuniverse/settings/production.py
"""Production settings and globals.""" from __future__ import absolute_import from os import environ from .base import * # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. from django.core.exceptions import ImproperlyConfigured def get_en...
loarabia/DeployUtil
bin/strings.py
#This code is licensed under the "MIT License" see LICENSE.txt """ This contains all of the definitions for the commandline arguments as named tuples. """ from collections import namedtuple argument = namedtuple("argument", ['switch', 'help']) # common options ip = argument(switch='-ip', help='ip args h...
shacknetisp/vepybot
plugins/protocols/irc/core/dispatcher.py
# -*- coding: utf-8 -*- import bot import time import fnmatch import string class Context(bot.Context): def __init__(self, server, text): self.moretemplate = "%s[{n} more message{s}]%s" % ( server.codes.bold, server.codes.bold) bot.Context.__init__(self, server) stext = text.l...
dwhalen/holophrasm
multitrainer.py
import learning_history import data_utils5 as data_utils import random import numpy as np import time import os import sys import pickle as pickle import matplotlib.pyplot as plt #from pathos.multiprocessing import ProcessingPool as Pool from multiprocessing import Pool from multiprocessing import Process, Queue i...
kelvict/Online-GoBang-Center
Server/Server.py
#-*- encoding:UTF-8 -*- __author__ = 'gzs2478' from netstream import nethost import netstream import json import time from Database import Database from Dispatcher import Dispatcher import Player from LoginService import LoginService from HallService import HallService from RoomService import RoomService from Singleto...
lpenz/omnilint
container/omnilint/reporters.py
# Copyright (C) 2017 Leandro Lisboa Penz <lpenz@lpenz.org> # This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source code package. '''Collection of reporter classes''' from collections import OrderedDict import json class Reporter(object): def __init__(self): ...
staticdev/django-sorting-bootstrap
noxfile.py
"""Nox sessions.""" import shutil import sys from pathlib import Path from textwrap import dedent import nox try: from nox_poetry import Session from nox_poetry import session except ImportError: message = f"""\ Nox failed to import the 'nox-poetry' package. Please install it using the following c...
cliffano/swaggy-jenkins
clients/python/generated/test/test_github_repositorylinks.py
""" 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...
comprobo-final-project/comprobo_final_project
comprobo_final_project/scripts/simulator/vector_3.py
""" Custom made vector3 attribute for simulation """ class Vector3: def __init__(self): self.x = 0 self.y = 0 self.z = 0 def __sub__(self, other): result = Vector3() result.x = self.x - other.x result.y = self.y - other.y result.z = self.z - ...
azatoth/pywikipedia
pywikibot/comms/threadedhttp.py
# -*- coding: utf-8 -*- """ Httplib2 threaded cookie layer This class extends httplib2, adding support for: - Cookies, guarded for cross-site redirects - Thread safe ConnectionPool and LockableCookieJar classes - HttpProcessor thread class - HttpRequest object """ # (C) 2007 Pywikipedia bot team, 20...
pannal/Subliminal.bundle
Contents/Libraries/Shared/tld/trie.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = u'Artur Barseghyan' __copyright__ = u'2013-2019 Artur Barseghyan' __license__ = u'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' __all...
unclev/vk.unclev.ru
extensions/status-to-vk.py
# coding: utf-8 # This file is a part of VK4XMPP transport # © simpleApps, 2014 (30.08.14 08:08AM GMT) — 2015. """ This plugin allows users to publish their status in VK """ VK_ACCESS += 1024 GLOBAL_USER_SETTINGS["status_to_vk"] = {"label": "Publish my status in VK", "value": 0} def statustovk_prs01(source, prs, re...
amilstead/unity3d-thrift-twisted
python/app/_thrift/services/user/User.py
# # Autogenerated by Thrift Compiler (0.9.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py:twisted # from thrift.Thrift import TType, TMessageType, TException, TApplicationException import _thrift.services.SharedService from ttypes import * from thrift.Thrift import TProc...