repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/models/_network_management_client_enums.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 ... |
Kore-Core/kore | qa/rpc-tests/forknotify.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Kore Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test -alertnotify
#
from test_framework.test_framework import KoreTestFramework
from test_framework.ut... |
mc706/prog-strat-game | sciences/migrations/0004_auto_20150519_0227.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sciences', '0003_technologycost'),
]
operations = [
migrations.AlterField(
model_name='technology',
... |
danijar/sets | sets/process/word_distance.py | import warnings
import numpy as np
from sets.core import Step
class WordDistance(Step):
def __init__(self, *tags, depth=2):
self._tags = tags
self._depth = depth
def __call__(self, dataset, column):
# pylint: disable=arguments-differ
dataset = dataset.copy()
if 'word_... |
mikeireland/chronostar | benchmarks/emcee_parallel.py | '''
Parallelism tutorial copied from
https://emcee.readthedocs.io/en/latest/tutorials/parallel/
credit: Dan Foreman-Mackey
'''
import os
from multiprocessing import cpu_count
from multiprocessing import Pool
import emcee
import time
import numpy as np
import sys
os.environ["OMP_NUM_THREADS"] = "1"
print(emcee.__versio... |
sahilchinoy/ucpd-crime | ucpd/management/commands/classify.py | import os
import csv
import logging
from django.conf import settings
from django.db import transaction
from django.core.management.base import BaseCommand
from ucpd.models import Incident
logger = logging.getLogger('django')
class Command(BaseCommand):
help = "Assign each incident in the database a classificatio... |
jonschreiber/BB_lockbox | deadbolt/listen2.py | import socket
import sys
import moveto
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8889 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code :... |
nkmk/python-snippets | notebook/shutil_move.py | import shutil
import os
os.makedirs('temp/dir1/dir', exist_ok=True)
os.makedirs('temp/dir2', exist_ok=True)
with open('temp/dir1/file.txt', 'w') as f:
f.write('original')
print(os.listdir('temp/dir1/'))
# ['file.txt', 'dir']
print(os.listdir('temp/dir2/'))
# []
new_path = shutil.move('temp/dir1/file.txt', 'tem... |
weapp/flask-stylus2css | flaskext/stylus2css.py | # -*- coding: utf-8 -*-
"""
flaskext.stylus2css
~~~~~~~~~~~~~~~~~~~
A small Flask extension that makes it easy to use Stylus for CSS
with your Flask application.
:copyright: (c) 2012 by Manuel Albarrán.
:license: MIT, see LICENSE for more details.
"""
import os.path
import codecs... |
ishikawa/python-plist-parser | tools/performance/profiler.py | #!/usr/bin/env python
#
# Measure execution time of various Property List Parsing.
#
import os
import sys
import gc
import time
# From timeit module.
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
timer = time.clock
else:
# On most other platforms the best timer is time.time()
... |
SEA000/uw-empathica | empathica/gluon/widget.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
The widget is called from web2py.
"""
import sys
import cStringIO
import time
import thread
import re
impo... |
thelinuxkid/ripple | ripple/jsonrpc.py | from functools import wraps
unique_options = dict([
('ledger', ['ledger_hash', 'ledger_index']),
])
class RippleRPCError(Exception):
""""
An error in an RPC response.
"""
def __init__(self, name, code, message):
self.name = name
self.code = code
self.message = message
... |
DesertBot/DesertBot | desertbot/modules/commands/weather/BaseWeatherCommand.py | import time
from typing import List, Union, Dict
from desertbot.message import IRCMessage
from desertbot.modules.commandinterface import BotCommand
from desertbot.response import IRCResponse
try:
import re2
except ImportError:
import re as re2
class BaseWeatherCommand(BotCommand):
def __init__(self, nam... |
xcombelle/chaintools | chaintools.py | import fileinput
import sys
import re
import shlex
import subprocess
import asyncio
import selectors
import os
import codecs
import queue
def run(command):
"""
parse the command with help of shlex
and create a generator which feeds the command
with input and read output
Note: only works under... |
TimeWz667/Kamanian | example/Chapter 3.2 Use StSpAgent.py | import complexism as cx
import complexism.agentbased.statespace as ss
import epidag as dag
psc = """
PCore pSIR {
beta = 0.4
gamma = 0.5
Infect ~ exp(beta)
Recov ~ exp(0.5)
Die ~ exp(0.02)
}
"""
dsc = """
CTBN SIR {
life[Alive | Dead]
sir[S | I | R]
Alive{life:Alive}
Dead{life:De... |
mizuy/mizwiki | mizwiki/cache.py | class Cache(object):
def has(self,key):
pass
def get(self,key):
pass
def put(self,key,value):
pass
def get_cachedata(self, key, lazyeval):
try:
v = self.get(key)
except KeyError:
v = lazyeval()
self.put(key,v)
retur... |
CGenie/qwertyui | qwertyui/backups/tests.py | import datetime
import unittest
class PeriodicBackupRemoverTest(unittest.TestCase):
def setUp(self):
from .periodic_backup_remover import PeriodicBackupRemover
BACKUP_RULES = [
{
'upto': (3, 'day'),
'interval': (2, 'hour'),
},
{
... |
paolo215/problems | Euler/21.py | #Amicable numbers
#Slightly optimized
def amicable(j):
a = []
for i in range(1,int(j//2) + 1):
if j % i == 0:
a.append(i)
return sum(a)
assert amicable(220) == 284 and amicable(284) == 220
S = {}
a = []
for i in range(1, 10000):
S[i] = amicable(i)
for i in range(1, 10000):
... |
waneric/PyMapLib | src/gabbs/plugins/drawingtool/qrc_resources.py | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Thu Jun 18 09:29:26 2009
# by: The Resource Compiler for PyQt (Qt v4.4.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x00\xe5\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00... |
tweekmonster/moult | setup.py | import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
try:
from pypandoc import convert
def readme_file(readme):
return convert(readme, 'rst')
except ImportError:
def readme_file(readme):
with open(readme, 'r') as fp:
re... |
rwl/PyCIM | CIM15/IEC61968/PaymentMetering/Cashier.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
vivekiitkgp/gistie | gistie.py | #!/usr/bin/python3
__description__ = """
Gistie - A tiny script to generate quick pasties from terminal stdout
and stdin output.
Requires requests module, and xclip (optional).
"""
__author__ = "Vivek Rai"
__date__ = "18th July, 2014"
import requests
import json
import getpass
import sys
import ar... |
stvkas/django-bakery | bakery/feeds.py | import os
import logging
from django.conf import settings
from bakery.views import BuildableMixin
from django.contrib.syndication.views import Feed
logger = logging.getLogger(__name__)
class BuildableFeed(Feed, BuildableMixin):
"""
Extends the base Django Feed class to be buildable.
"""
build_path = '... |
nitely/django-hooks | hooks/extensions.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
__all__ = [
'autodiscover',
'apps',
'urls'
]
apps = []
urls = []
def autodiscover(import_path, app_config='Extension'):
# Relative path to the extension's package in
# dot notation such as 'my_app.extensions'
global... |
Scratch-Cloud-Services/scratch-cloud-services | st-tweets/st-tweets.py | #!/usr/bin/env python3
import sys
import os
import scratchapi
import urllib.request
import datetime
import time
from getopt import getopt
from getpass import getpass
from bs4 import BeautifulSoup
import config
def usage():
"""Print usage."""
print("usage: python3 %s [-d] [-l log]" % sys.argv[0])
sys.exit... |
heprom/pymicro | examples/ebsd/load_osc.py | import os
from pymicro.crystal.ebsd import OimScan, OimPhase
from pymicro.crystal.lattice import Lattice
from matplotlib import pyplot as plt, cm, image
from config import PYMICRO_EXAMPLES_DATA_DIR
file_path = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'ebsd_ti_beta_crack.osc')
scan = OimScan.from_file(file_path)
# the ... |
davbo/davblog | plugin/davblog.py | """
A basic blog interface for Vim.
Supports basic CRUD functions
Basic UI classes are from Michael Brown's excellent VimTrac Plugin:
http://www.vim.org/scripts/script.php?script_id=2147
"""
import vim, urllib, urllib2, json, webbrowser, base64
########################
# User Interface Base Classes
#################... |
UCSUR-Pitt/wprdc-etl | test/unit/test_extractor.py | import os
import csv
import xlrd
import unittest
import pipeline as pl
HERE = os.path.abspath(os.path.dirname(__file__))
class TestCSVExtractor(unittest.TestCase):
def setUp(self):
self.path = os.path.join(HERE, '../mock/simple_mock.csv')
self.tsv_path = os.path.join(HERE, '../mock/simple_tsv_moc... |
jnovinger/django-ordered-m2m | setup.py | from setuptools import setup, find_packages
PYPI_RESTRUCTURED_TEXT_INFO = \
"""
Adds ordering to Django's many-to-many relations.
Full documentation at http://github.com/markfinger/django-ordered-m2m
"""
setup(
name = 'django-ordered-m2m',
version = '1.0.4-alpha1',
packages = find_packages(),
packag... |
mikeireland/chronostar | scripts/run_chronostar.py | #! /usr/bin/env python
"""
A helper script that performs a brute force Chronostar fit to
some pre-prepared data.
Accepts as a command line argument a path to a parameter file
TODO: Update README.md with description for NaiveFit parameters
(see README.md for how to structure the parameter file and
various available par... |
thk4711/orangepi-radio | test/oledtest.py | #!/usr/bin/python
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
RST = 24
# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize library.
disp.begin()
# Get display width and he... |
lcrees/callchain | callchain/lazy_auto/chain.py | # -*- coding: utf-8 -*-
'''lazy auto-balancing chains appconf'''
from appspace.keys import appifies
from twoq.lazy.mixins import AutoResultMixin
from callchain.chain import ChainQ, inside
from callchain.services.queue import KResults
from callchain.patterns import Pathways, Nameways
class callchain(Pathways):
... |
mattjj/pylds | examples/zeroinflated_bernoulli_lds.py | from __future__ import division
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
# Fancy plotting
try:
import seaborn as sns
sns.set_style("white")
sns.set_context("talk")
color_names = ["windows blue",
"red",
"amber",
... |
kurtraschke/cadors-parse | src/cadorsfeed/cadorslib/parse.py | import re
from datetime import datetime
from itertools import izip_longest
import html5lib
from lxml import etree
from cadorsfeed.cadorslib.xpath_functions import extensions
from cadorsfeed.cadorslib.narrative import process_narrative
from cadorsfeed.cadorslib.locations import LocationStore
from cadorsfeed.aerodb imp... |
makcedward/nlpaug | nlpaug/augmenter/audio/vtlp.py | """
Augmenter that apply vocal tract length perturbation (VTLP) operation to audio.
"""
from nlpaug.augmenter.audio import AudioAugmenter
import nlpaug.model.audio as nma
from nlpaug.util import Action
class VtlpAug(AudioAugmenter):
# https://pdfs.semanticscholar.org/3de0/616eb3cd4554fdf9fd65c9c82f2605a17413... |
BILS/agda | agda/agda/templatetags/agda_tags.py | from django.contrib.messages import DEFAULT_TAGS as message_default_tags
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe, SafeData
from django import template
register = template.Library()
def mailto_link(text, autoescape=None):
if isinstance(text, SafeData):
... |
kazarus/UniEngine-Cli | pascal/UniEngine-VCL/upxit-p2.py | #coding=cp936
import os
import shutil
import win32api
import zipfile
def getFileVersion(file_name):
info = win32api.GetFileVersionInfo(file_name, os.sep)
ms = info['FileVersionMS']
ls = info['FileVersionLS']
version = '%d.%d.%d.%d' % (win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32... |
kklmn/xrt | examples/withRaycing/14_SoftiMAX/Softi_CXIw2D.py | # -*- coding: utf-8 -*-
"""
!!! select one of the two functions to run at the very bottom !!!
!!! select 'rays', 'hybrid' or 'wave' below !!!
!!! select a desired emittance case below !!!
Described in the __init__ file.
"""
__author__ = "Konstantin Klementiev", "Roman Chernikov"
__date__ = "07 Feb 2018"
import os, sy... |
spradeepv/dive-into-python | hackerrank/domain/data_structures/linked_lists/print_in_reverse.py | """
Print elements of a linked list in reverse order as standard output
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
"""
def Reverse(head):
if head:
l = []
... |
SV-Seeker/pi-rov | tests/test_messages.py | import unittest
import pytest
from mock import patch
from rov import messages
class TestMessage(unittest.TestCase):
class NewMessage(messages.Message):
struct_keys = (
('f', 'floaty'),
('?', 'booly'),
)
def test_init(self):
pass
def test_upgrade(self):
... |
anselmobd/fo2 | src/utils/management/commands/hist_100.py | import sys
import datetime
from pprint import pprint, pformat
from django.core.management.base import BaseCommand, CommandError
from fo2.connections import db_cursor, db_cursor_so
import base.models
from utils.functions.models import rows_to_dict_list_lower
import lotes.models as models
class Command(BaseCommand)... |
invisiblehands/django-supasurvey | supasurvey/utils.py | import csv, os, codecs, collections, json, copy
from decimal import Decimal
from django.utils.html import conditional_escape
from django.conf import settings
# # http://stackoverflow.com/questions/1846135/python-csv-library-with-unicode-utf-8-support-that-just-works
class UnicodeCSVReader(object):
def __init__(... |
chinhtle/python_fun | hacker_rank/algorithms/warmup/timeconversion.py | #!/bin/python
# Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
#
# Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour
# clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour
# clock.
#
# Input Format:
# A single string containing a time i... |
texastribune/scuole | scuole/campuses/migrations/0011_auto_20210208_2205.py | # Generated by Django 3.1.4 on 2021-02-08 22:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('campuses', '0010_auto_20190829_1458'),
]
operations = [
migrations.AlterField(
model_name='campusstats',
name='accou... |
ConnectBox/wifi-test-framework | ansible/plugins/mitogen-0.2.3/ansible_mitogen/plugins/connection/mitogen_ssh.py | # Copyright 2017, David Wilson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2.... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/subnet_association.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 ... |
pytlakp/intranetref | src/intranet3/tests/idate_test.py | import unittest
import datetime
from intranet3.utils import idate
class IDateTest(unittest.TestCase):
def test_quarter(self):
months = [datetime.date(2013, x, 1) for x in range(1, 13)]
quarters = [idate.quarter_number(date) for date in months]
self.assertEqual(quarters, [1, 1, 1, 2, 2, 2... |
Trundle/yapyfc | yapyfc/reader.py | import shlex
from gi.repository import Gio, GLib
from pyrepl import commands
from pyrepl.historical_reader import HistoricalReader
from pyrepl.unix_console import UnixConsole
from termcolor import colored
# XXX move completions somewhere else
from .commands import cli
from .completing_reader import CompletingReader
... |
victronenergy/dbus-systemcalc-py | scripts/dummygenset.py | #!/usr/bin/env python3
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
import argparse
import logging
import sys
import os
# our own packages
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '../ext/velib_python'))
from dbusdummyservice import DbusDummyService
from logger import ... |
anamayasullerey/test_net | src/tests/test_grad_x3_fc1_sigm1_sigce.py | import nn_grad_test as nt
import numpy as np
import start.neural_network as nn
import start.layer_dict as ld
import start.weight_update_params as wup
class test_grad_x3_fc1_sigm1_sigce(nt.NnGradTest):
def define_nn(self):
self.net = nn.NeuralNetwork("test_net", 1)
self.layer = ld.hdict["f... |
metacloud/photon | doc/source/conf.py | # -*- coding: utf-8 -*-
#
# Photon documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 17 16:07:47 2015.
#
# 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.
#
# Al... |
joshleeb/CreditCard | creditcard/formatter.py | def is_visa(n):
"""Checks if credit card number fits the visa format."""
n, length = str(n), len(str(n))
if length >= 13 and length <= 16:
if n[0] == '4':
return True
return False
def is_visa_electron(n):
"""Checks if credit card number fits the visa electron format."""
n,... |
ladyson/police-complaints | final_data/stage2WithDumWithDemo.py | import pandas as pd
import psycopg2
import sys
def go(output_fn):
'''Generate dataframe with features from database'''
conn = psycopg2.connect("dbname = police user = lauren password = llc")
#Queries for features
outcome = 'SELECT crid, officer_id, "Findings Sustained" FROM dependent_dum;'
alleg... |
AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/executing_faults_chaos_event.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 ... |
IEEEDTU/CMS | NewsFeed/views/Notice.py | from django.core import serializers
from django.http import HttpResponse,JsonResponse
from NewsFeed.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_POST
def addNotice(request):
response_data = {}
... |
fzheng/codejam | lib/python2.7/site-packages/ipyparallel/apps/winhpcjob.py | # encoding: utf-8
"""
Job and task components for writing .xml files that the Windows HPC Server
2008 can use to start jobs.
Authors:
* Brian Granger
* MinRK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed u... |
Upper-Polo/weather-app | lib.py | # weather-app
# lib.py
# Classes and functions for weather-app.
# Function definitions.
# ---------------------
# Prompt for user input. Accepts a prompt message we want to show.
def prompt(msg):
return input(msg)
def print_data(data_in):
print("Date: {}".format(data_in['dt']))
print("Description: {}".fo... |
flags/Reactor-3 | language.py | from globals import *
import alife
import logging
import random
import os
def prettify_string_array(array, max_length):
"""Returns a human readable string from an array of strings."""
_string = ''
_i = 0
for entry in array:
if len(_string) > max_length:
_string += ', and %s more.' % (_i+1)
break
... |
the-zebulan/CodeWars | tests/beta_tests/test_spanish_class_help.py | import unittest
from katas.beta.spanish_class_help import gender
class SpanishClassHelpTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(gender('genio'), ['el genio'])
def test_equals_2(self):
self.assertEqual(gender('chico', 'esquinas'),
['el chic... |
sabajt/Dinos-In-Space | snack.py | """
snack.py
defines Snack class - collectible objects in puzzles
"""
import pygame
import static56
import groupMods56
import dinosInSpace
import scroller56
import endMessage
import soundFx56
SPIN_STEP = -1
DEFAULT_ALPHA = 190
HIDE_ALPHA = 90
class ImgLib(object):
""" image library to load and access loc... |
micumatei/asciipic | asciipic/api/api_endpoint/echo/__init__.py | """API endpoint for the AsciiPic API."""
import cherrypy
from cherrypy import tools
from asciipic.api import base as base_api
from asciipic.db.managers import user
from asciipic.tasks import base as base_task
from asciipic.tasks import echo_task
class EchoEndpoint(base_api.BaseAPI):
"""Action related to users.... |
FriedrichK/pyCalq | setup.py | #!/usr/bin/env python
from setuptools import setup
import os
import re
base_path = os.path.dirname(__file__)
fp = open(os.path.join(base_path, 'pycalq', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'",
re.S).match(fp.read()).group(1)
fp.close()
version = VERSION
def read(fnam... |
Flowerfan524/TriClustering | reid/models/inception_v3.py | from __future__ import absolute_import
from torch import nn
from torch.nn import functional as F
from torch.nn import init
import torchvision
class Inception_v3(nn.Module):
def __init__(self, pretrained=True, cut_at_pooling=False,
num_features=0, norm=False, dropout=0, num_classes=0):
su... |
orlandi/netcal | internal/networkInference/Connectomics/cnn/prediction.py | # -*- coding: utf-8 -*-
"""
Module for using a trained CNN model to predict network connectivity.
Includes funtions for computing connection scores, generating a null
distribution with surrogate shuffles, and reconstructing the estimated
adjacency matrix of a network.
Created on Wed Aug 23 14:24:32 2017
@author: pau... |
sherinkurian/mani | mani/__init__.py |
from . import util
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
from .scheduler import Scheduler
class Mani:
def __init__(self, redis_url, config = {}):
self.redis = util.redis_conn(redis_url)
self.scheduler = Scheduler(redis=self.redis, config=config)
def e... |
mkauppila/rachel | tests/test_parse.py |
import unittest
import parse
class TestParse(unittest.TestCase):
""" Test parsing server messages.
Test that all the parts of server messages can be parsed properly.
Doesn't include negative tests that ought to fail.
"""
def test_parse_full_message(self):
prefix = 'zelazny.freenode.net'
command = '372'
... |
luwei14/aspen | admin.py | """
The admin App
"""
import os
import web
import settings
import models
from models import render
web.config.debug = settings.DEBUG
urls = (
"/userinfo",'userinfo',
"/postsadmin","postsadmin",
"/edit/(.+)","edit",
"/new","new",
"/view/(.+)","view",
"/delete/(.+)","delete",
"/upload","upload",
"/newpwd","newp... |
michaeldove/abode | chat/onoff.py | import subprocess
PIN_LEVEL_LOW = "0"
PIN_LEVEL_HIGH = "1"
GPIO_COMMAND = "/usr/local/bin/gpio"
AT_COMMAND = "at"
def gpio_queue(gpio_pin):
"""
Returns the name of the at queue for a gpio pin.
"""
queue = '%s%d' % (GPIO_QUEUE, gpio_pin)
return queue
def turn_on(gpio_pin, duration):
"""
Tu... |
keeper-of-data/web-scraper | modules/wallhaven.py | from utils.exceptions import *
from utils.scraper import Scraper
import os
class Wallhaven(Scraper):
def __init__(self, base_dir, url_header, log_file):
super().__init__(log_file)
self._base_dir = base_dir
self._url_header = url_header
def get_latest(self):
"""
Parse ... |
wgmueller1/unicorn | app/util/historical.py | MAX_HIST = 10
def active_history_terms(hist):
terms = []
for q in hist:
if q['active']:
terms.append(q['query'])
return terms
def update_history(hist, query, active):
for q in hist:
if q['query'] == query:
q['active'] = bool(int(active))
return hist
def a... |
reviewboard/rbtools | rbtools/utils/aliases.py | from __future__ import unicode_literals
import logging
import re
import shlex
import sys
import subprocess
import six
from rbtools.commands import RB_MAIN
# Regular expression for matching argument replacement
_arg_re = re.compile(r'\$(\d+)')
# Prior to Python 2.7.3, the shlex module could not accept unicode inpu... |
CodeForAfricaLabs/Scrapengine | tests/test_scraper_ke_gazette.py | """
scrapengine/scrapers/ke_gazette tests
"""
import random
import unittest
from Scrapengine.scrapers import ke_gazette
from Scrapengine.configs import ARCHIVE
class KEGazetteScraperTestCase(unittest.TestCase):
def setUp(self,):
self.foo = True
self.month_resp = self._get_month_html()
... |
drdaeman/destruct | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(
name="destruct",
version="0.1.0",
author="Aleksey Zhukov",
author_email="drdaeman@drdaeman.pp.ru",
url="https://github.com/drdaeman/destruct",
packages=[
"destruct",
"destruct.types",
"destruct.fields",
... |
dotKom/onlineweb4 | apps/events/utils.py | # -*- coding: utf-8 -*-
import logging
from datetime import timedelta
import icalendar
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import... |
NeowithU/Trajectory | Prepare_Ways.py | __author__ = 'Fang'
import json
import os
import datetime
import utilities as util
INIT_DATA_DIR = "Raw"
NODE_DATA = "3n.json"
WAY_DATA = "3w.json"
INER_DATA_DIR = "Intermediate"
GEO_RANGE = '116.318,27.147,122.481,35.178'
LOG_FILE = "Logs/Prepare_ways.log"
def get_nodes():
os.chdir(INER_DATA_DIR)
if not os.... |
bellwethers-in-se/defects | src/metrics/recall_vs_loc.py | from __future__ import print_function, division
import numpy as np
from sklearn.metrics import *
from pdb import set_trace
def get_curve(loc, actual, predicted, distribution):
sorted_loc = np.array(loc)[np.argsort(loc)]
sorted_act = np.array(actual)[np.argsort(loc)]
try:
fpr, tpr, thresholds = r... |
mikefeneley/topcoder | src/SRM-678/the_phantom_menace.py |
class ThePhantomMenace:
def find(self, doors, droids):
greatest_min = -1
best_door = doors[0]
for idx, door in enumerate(doors):
greatest_distance = 9999
for droid in droids:
distance = abs(droid - door)
if distance < greatest_dista... |
marty-sullivan/DockerWRF | runwrf.py | #!/usr/local/bin/python
import ftp
from argparse import ArgumentParser
from datetime import datetime, timedelta
from os import chdir, getcwd, mkdir, system
from shutil import rmtree
from socket import gethostname
from subprocess import call
from sys import exit
from time import localtime, strftime, strptime, time
ar... |
KieranWynn/pyquaternion | demo/demo.py | import pyquaternion
# Create a quaternion representing a rotation of +90 degrees about positive y axis.
my_quaternion = pyquaternion.Quaternion(axis=[0, 1, 0], degrees=90)
my_vector = [0, 0, 4]
my_rotated_vector = my_quaternion.rotate(my_vector)
print('\nBasic Rotation')
print('--------------')
print('My Vector: {}... |
NZSmartie/PyHIDParser | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="hidparser",
version="0.0.7",
description="HID Descriptor Parser",
license="MIT",
author="Roman Vaughan",
url="https://github.com/NZSmartie/PyHIDParser",
classifiers=[
"Development Status :: 2 - Pre-Al... |
bgroff/kala-app | django_kala/django_kala/templatetags/kala_tags.py | from django.template import Library
from django.utils.translation import ugettext as _
register = Library()
@register.filter
def pretty_user(user):
if user is None:
return _('Lost in translation')
else:
return '%s %s' % (user.first_name, user.last_name)
@register.filter
def users_projects(... |
tkwon/dj-stripe | tests/test_mixins.py | """
.. module:: dj-stripe.tests.test_mixins
:synopsis: dj-stripe Mixin Tests.
.. moduleauthor:: Alex Kavanaugh (@kavdev)
"""
from copy import deepcopy
from django.contrib.auth import get_user_model
from django.test.client import RequestFactory
from django.test.testcases import TestCase
from mock import patch
fr... |
asana/python-asana | setup.py | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
assert sys.version_info >= (2, 7), 'We only support Python 2.7+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
setup(
name='asana',
version='0.10.3',
description='Asana API client',
license=... |
gratipay/gratipay.com | gratipay/utils/history.py | """Helpers to fetch logs of payments made to/from a participant.
Data is fetched from 3 tables: `transfers`, `payments` and `exchanges`. For
details on what these tables represent, see :ref:`db-schema`.
"""
from datetime import datetime
from decimal import Decimal
from aspen import Response
from psycopg2 import Inte... |
benoitc/socketpool | socketpool/conn.py | # -*- coding: utf-8 -
#
# This file is part of socketpool.
# See the NOTICE for more information.
import socket
import time
import random
from socketpool import util
class Connector(object):
def matches(self, **match_options):
raise NotImplementedError()
def is_connected(self):
raise NotImpl... |
pmajka/poSSum | possum/pos_wrapper_skel.py | #!/usr/bin/python
# -*- coding: utf-8 -*
import sys
import os
import subprocess as sub
import multiprocessing
import time
import datetime
import logging
from optparse import OptionParser, OptionGroup
import pos_common
import pos_wrappers
CONST_CMD_LINE_OPTIONS_OUTPUT_VOL_SETTINGS = "Output volumes settings"
CONST_... |
dhrone/Raspdac-Display | pages/pages_default.py | # Page Definitions
# See Page Format.txt for instructions and examples on how to modify your display settings
PAGES_Play = {
'name':"Play",
'pages':
[
{
'name':"Artist",
'duration':8,
'hidewhenempty':'any',
'hidewhenemptyvars': [ "artist" ],
'lines': [
{
... |
BSchilperoort/BR-DTS-Processing | data_processing/dataImports.py | ##DTS
def dts(fileName):
'''Takes: filename
Returns: timestamp, distances, temperature'''
print('Importing the DTS file...')
import numpy as np
from datetime import datetime
#Get length of file
with open(fileName) as fileobject:
file_length = sum(1 for line in fileobject)-3
... |
snfactory/pipeline | snfpipe/utils.py | # Various legacy utilities from SNFactory cvs Tasks/Processing/database/SnfObj
from math import pi, sin, cos, acos
class RADec(object):
"Class build a RA DEC object from any kind of RA DEC"
def __init__(self, coorx, xtype):
# Accepted format : HH:MM:SS.s
# in input HH MM SS... |
alexdzul/pyql-weather | pyql/geo/countries.py | # -*- coding: utf-8 -*-
__author__ = 'Alex Dzul'
from pyql.geo.generics import GenericGeoPlace
from pyql.interface import YQLConector
__all__ = ('Country', )
YQL_TABLE = "geo.countries"
class Country(GenericGeoPlace):
@staticmethod
def get(**kwargs):
"""
Realiza una consulta a la base de d... |
wfriesen/flaskfm | api/src/flaskfm/views.py | from flask import abort, jsonify, make_response, request
from humanize import naturaldate
from flask_sqlalchemy import sqlalchemy
from models import db, Scrobbles, Artists, Albums, Tracks
from flaskfm import app
@app.errorhandler(400)
def bad_request(error):
return make_response(jsonify({'error': 'Bad request da... |
utarsuno/quasar_source | deprecated/finance/finance_simulations/models/trading_model.py | # coding=utf-8
"""This module, trading_model.py, represents a trading model used in both training and testing."""
FINANCE_MODEL_TYPE_M0 = 'm0_net_resistance'
class FinanceModel(object):
"""Represents a financial model that can be both trained and tested."""
def __init__(self, model_type, types_of_data_needed):
... |
eladnoor/replace-animals | pareto.py |
# coding: utf-8
# In[27]:
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
import pulp
from matplotlib.backends.backend_pdf import PdfPages
sb.set()
pd.set_option('precision', 2)
macro_nutrients = [
'kcal per 100 g ready to eat',
'Protein_(g)',... |
bilbeyt/ituro_website | ituro_website/gallery/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import models
class Gallery(models.Model):
language_code = models.CharField(choices=settings.LANGUAGES, max_length=2)
title = models.CharField(max_length=50, choices=settings.GALLERY_PAGES)
created_at = models.DateTime... |
restless/django-mptt | tests/settings.py | from __future__ import unicode_literals
import os
DIRNAME = os.path.dirname(__file__)
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contentt... |
Nachtfeuer/concept-py | concept/graph/gnuplot/multiplot.py | """
Gnuplot multiplot class.
.. module:: plot
:platform: Unix, Windows
:synopis: Gnuplot multiplot class.
.. moduleauthor:: Thomas Lehmann <thomas.lehmann.private@googlemail.com>
=======
License
=======
Copyright (c) 2015 Thomas Lehmann
Permission is hereby granted, free of charge, to any ... |
xingzhe25/testLeanCloud | settings.py | # coding: utf-8
import os
DEBUG = os.environ.get('LEANCLOUD_APP_ENV') != 'production'
ROOT_URLCONF = 'urls'
#SECRET_KEY = 'replace-this-with-your-secret-key'
SECRET_KEY = 'i7htv7k^=hxl-8uho4pf$)uurkcc3wfxs((cg6+l#k57vgl4zl'
ALLOWED_HOSTS = ['*']
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTe... |
amberm291/WordCount | reducer.py | #!/usr/bin/env python
import sys
from operator import itemgetter
prev_index = None
value_list = []
for line in sys.stdin:
curr_index, index, value = line.rstrip().split("\t")
index, value = map(int,[index,value])
if curr_index == prev_index:
value_list.append((index,value))
else:
if p... |
marcosmoyano/simple-cart | cart_project/profiles/tests/test_views.py | #-*- coding: utf-8 -*-
from decimal import Decimal
from django.test import TestCase
from django.test.client import Client
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from profiles.models import StoreUser
from profiles.forms import StoreUserForm
from stores.models import S... |
ekwoodrich/python-dvrip | env/lib/python3.5/site-packages/importlib_metadata/tests/test_api.py | import re
import textwrap
import unittest
import itertools
from . import fixtures
from .. import (
Distribution, PackageNotFoundError, __version__, distribution,
entry_points, files, metadata, requires, version,
)
try:
from collections.abc import Iterator
except ImportError:
from collections impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.