repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
Skylion007/popupcad | popupcad_deprecated/keepout2.py | # -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
from popupcad.manufacturing.multivalueoperation2 import MultiValueOperation2
from popupcad_manufacturing_plugins.manufacturing.keepout3 import KeepOut3
class KeepOut2(MultiValueOp... |
MrLokans/MoonReader_tools | tests/test_parsers.py | import sys
import unittest
from unittest.mock import mock_open, patch
from moonreader_tools.conf import STAT_EXTENSION
from moonreader_tools.parsers import FB2NoteParser, PDFNoteParser, StatsAccessor
from tests.base import BaseTest
class TestPDFParserRoutines(BaseTest):
def test_notes_are_correctly_parsed(self):... |
CommonClimate/teaching_notebooks | GEOL351/CoursewareModules/ClimateGraphics.py | #----------Section 3: Plotting utilities-------------------------------
#These need to be localized, for systems that don't support Ngl
#
#This is imported into ClimateUtilities. If you want to use a
#different graphics package (e.g. MatPlotLib) as a graphics driver
#in place of Ngl, you only need to rewrite this modul... |
payplug/payplug-python | payplug/network.py | # -*- coding: utf-8 -*-
import sys
import abc
import json
from six import with_metaclass
from payplug import config, exceptions
from payplug.__version__ import __version__
class HttpRequest(with_metaclass(abc.ABCMeta)):
"""
Generic interface to abstract an HTTP Request.
"""
def _raise_unrecoverable_er... |
ihongs/HongsCode | Python/main/strip.py | #!/usr/bin/python
#coding=utf-8
# 过期文件清理工具
# 用于清理超过一定时间的日志、临时文件
# 作者: kevin.hongs@gmail.com
# 修订: 2016/03/03
import os
import re
import sys
import time
import datetime
from getopt import getopt
def hsClean(dn, tm, ep, op, nm, ne):
"""
清理工具
dn: 待清理的目录
tm: 清除此时间前的文件
ep: 删除空的目录
op: 仅输出不删除
nm... |
browning/tiger-hash-python | sboxes.py | t1 = [ 0x02AAB17CF7E90C5E , 0xAC424B03E243A8EC ,
0x72CD5BE30DD5FCD3 , 0x6D019B93F6F97F3A ,
0xCD9978FFD21F9193 , 0x7573A1C9708029E2 ,
0xB164326B922A83C3 , 0x46883EEE04915870 ,
0xEAACE3057103ECE6 , 0xC54169B808A3535C ,
0x4CE754918DDEC47C , 0x0AA2F4DFDC0DF40C ,... |
clee704/cpucoolerchart | tests/crawler_test.py | from cpucoolerchart import crawler
from cpucoolerchart.models import Maker, Heatsink, FanConfig, Measurement
def test_dictitemgetter():
assert crawler.dictitemgetter('a', 'b', 'c')({
'a': 1, 'b': 2, 'd': 3
}) == (1, 2, None)
def test_fix_existing_data(db):
thermalright = Maker(name='ThermalRight... |
DayGitH/Python-Challenges | DailyProgrammer/DP20141215A.py | """
[2014-12-15] Challenge #193 [Easy] A Cube, Ball, Cylinder, Cone walk into a warehouse
https://www.reddit.com/r/dailyprogrammer/comments/2peac9/20141215_challenge_193_easy_a_cube_ball_cylinder/
#Description:
An international shipping company is trying to figure out how to manufacture various types of containers. G... |
dabercro/CrombieTools | python/CrombieTools/SkimmingTools/FlatSkimmer.py | """ @package CrombieTools.SkimmingTools.FlatSkimmer
Submodule of CrombieTools.SkimmingTools
Contains the constructor and default object for FlatSkimmer.
Also contains the constructor for and a function to return a filled GoodLumiFilter.
@author Daniel Abercrombie <dabercro@mit.edu>
"""
import json
from .. import Lo... |
VaclavDedik/infinispan-py | tests/conftest.py | # -*- coding: utf-8 -*-
import pytest # noqa
import logging
# Set up logging for tests
formatter = logging.Formatter(
'%(asctime)s %(levelname)s [%(name)s] (%(threadName)s): %(message)s')
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
l... |
rjdp/EE-dbmigrate | alembic/versions/37d1722a4621_add_a_column.py | """Add a column
Revision ID: 37d1722a4621
Revises: None
Create Date: 2015-06-26 10:08:07.026259
"""
# revision identifiers, used by Alembic.
revision = '37d1722a4621'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('sites', sa.Column('redis', sa.DateTime))
def... |
bit-bots/bitbots_misc | bitbots_live_tool_rqt/scripts/position_msg.py | from geometry_msgs.msg import PoseWithCovarianceStamped, Point, Pose
from std_msgs.msg import Header
import yaml
import rospy
import tf
from name import Name
class PositionMsg:
label_orientation = "o"
label_pos = "p"
label_yaw = "yw"
title = "position_msg"
def __init__(self):
# the dic... |
fishstamp82/moltools | moltools/test/pdbreader_tests/concaps_level1.py | #!/usr/bin/env python
from applequistbreader import *
import unittest
FILE = os.path.join(os.path.dirname(__file__), 'collagen.pdb')
class TestConcapsLevel1( unittest.TestCase ):
def setUp(self):
""" Default arguments used for program
equivalent of argparser in pdbreader """
self.ch = S ... |
rjusher/djsqla-query-operations | djsqla_query_operations/opcollections/filtering.py | # -*- coding: utf-8 -*-
import copy
from sqlalchemy import or_, and_
from django import forms
from sqlalchemy.orm.attributes import InstrumentedAttribute
from djsqla_query_operations.operationset import Operation
from djsqla_query_operations.opcollections.fields import TypedMultipleField
class OrFilter(Operation):
... |
ristorantino/fiscalberry | Drivers/DummyDriver.py | # -*- coding: iso-8859-1 -*-
import random
from DriverInterface import DriverInterface
class DummyDriver(DriverInterface):
def close(self):
pass
def sendCommand(self, commandNumber=None, parameters=None, skipStatusErrors=None):
print "Enviando Comando DUMMY"
print command... |
iandees/membership | tests/test_config.py | # -*- coding: utf-8 -*-
"""Test configs."""
from members.app import create_app
from members.settings import DevConfig, ProdConfig
def test_production_config():
"""Production config."""
app = create_app(ProdConfig)
assert app.config['ENV'] == 'prod'
assert app.config['DEBUG'] is False
assert app.co... |
SicariusNoctis/dotfiles | ranger/.config/ranger/commands.py | from __future__ import (absolute_import, division, print_function)
from ranger.api.commands import Command
def select_file_by_command(self, command):
import subprocess
import os.path
comm = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE)
stdout, _stderr = comm.communic... |
birdland/dlkit-doc | dlkit/repository/search_orders.py |
from ..osid import search_orders as osid_search_orders
class AssetSearchOrder(osid_search_orders.OsidObjectSearchOrder, osid_search_orders.OsidAggregateableSearchOrder, osid_search_orders.OsidSourceableSearchOrder):
"""An interface for specifying the ordering of search results."""
def order_by_title(self, s... |
qvazzler/Flexget | flexget/utils/sqlalchemy_utils.py | """
Miscellaneous SQLAlchemy helpers.
"""
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from past.builtins import basestring
import logging
import sqlalchemy
from sqlalchemy import ColumnDefault, Sequence, Index
from sqla... |
nschloe/meshio | tests/test_tecplot.py | import pathlib
from copy import deepcopy
import numpy as np
import pytest
import meshio
from . import helpers
@pytest.mark.parametrize(
"mesh",
[
# helpers.empty_mesh,
helpers.tri_mesh,
helpers.quad_mesh,
# Those two tests suddenly started failing on gh-actions. No idea why.... |
mic4ael/indico | indico/core/signals/event/contributions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.signals.event import _signals
contribution_created = _signals.signal('contribution-crea... |
JSeam2/IsoGraph | old/qgate.py | #import tensorflow as tf
import numpy as np
def H():
"""
Returns a H gate
"""
return (1/np.sqrt(2))*(np.matrix([[1,1],[1,-1]]))
def RZ(theta):
"""
Returns R(theta) gate, or rotation matrix
"""
return np.matrix([[exp(-1j * theta /2.0), 0],[0, exp(1j * theta/ 2.0)]])
def CZ():
"""
... |
zvmexporter/zvm_exporter | zvm_exporter/collector.py | # The MIT License (MIT)
# Copyright (c) 2016 IBM Corporation
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... |
pantheon-systems/etl-framework | gcloud/datastores/bigquery.py | """Big query client that wraps google's library"""
#pylint: disable=super-on-old-class
#pylint: disable=too-many-arguments
from etl_framework.datastore_interfaces.datastore_interface import DatastoreInterface
from gcloud.datastores.mixins.project import ProjectMixin
from gcloud.datastores.mixins.client import ClientMi... |
jbhuang0604/WSL | lib/datasets/factory.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Factory method for easily getting imdbs by name."""
__sets = {}
im... |
happyleavesaoc/aoc-mgz | mgz/header/objects.py | """Objects."""
from construct import (Array, Byte, Embedded, Flag, Float32l, If, Int16sl, Int16ub,
Int16ul, Int32ub, Int32ul, Padding, Peek, Struct, Int32sl,
Switch, Pass, RepeatUntil, Bytes, LazyBound, IfThenElse)
from mgz.enums import ObjectEnum, ObjectTypeEnum, Resourc... |
njwilson/nirvana-python | setup.py | #!/usr/bin/env python
import nirvana
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
setup(
name='nirvana',
version=nirvana.__version__,
description=('Library for interacting with the N... |
lancezlin/ml_template_py | lib/python2.7/site-packages/nbconvert/exporters/tests/test_latex.py | """Tests for Latex exporter"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os.path
import textwrap
import re
from .base import ExportersTestsBase
from ..latex import LatexExporter
from nbformat import write
from nbformat import v4
from ipython_genutils.... |
MarkHG/EDD | DataStructuresPython/Examples/exam1.py | #Este es un comentario de una linea
'''
Esto es un comentaruio de varias lineas
'''
#Tipos de datos en python
entero = 12
flotante = 3.14
caracter = 'a'
cadena = "hola"
booleano = True #False
lista1 = [1, 2, 3, 4]
lista2 = []
lista3 = list()
result = entero + flotante
print(result)
print(type(result))
|
drstarry/minidou | minidou/lib/crawl.py | #!env python2.7
#encoding = utf-8
from lxml import html
import urllib2
import re
import os
import sys
import logging
from minidou.config import ROOT_PATH
class DoubanCrawler:
def __init__(self, seeds):
#intialize
self.linkQuence = linkQuence()
self.current_deepth = 1
self.actori... |
seiichisan/HapoItak | html/autocomp_table.py | import sublime, sublime_plugin, re
from ..util import sublime_view_util
############################################################################
# table を取得します。
############################################################################
def get_table(view, tr_count, td_count):
save = ""
save += "<table>\n"
s... |
jinjin123/devops2.0 | devops/ops/migrations/0021_auto_20171114_2126.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-11-14 21:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ops', '0020_auto_20171114_2111'),
]
operations = [
migrations.AlterField(
... |
xiezhen/brilws | utils/testmergejson.py | import numpy as np
from brilws import api
import pandas as pd
def expandrange(element):
'''
expand [x,y] to range[x,y+1]
output: np array
'''
return np.arange(element[0],element[1]+1)
def consecutive(npdata, stepsize=1):
'''
split input array into chunks of consecutive numbers
np.diff(... |
lobocv/crashreporter_hq | crashreporter_hq/config.py |
import os
HQ_FOLDER = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_FOLDER = os.path.join(HQ_FOLDER, 'templates')
STATIC_FOLDER = os.path.join(HQ_FOLDER, 'static')
PYGMENTS_CSS_FILE = os.path.join(TEMPLATE_FOLDER, 'syntax.css')
TMP_FOLDER = os.path.join(HQ_FOLDER, 'tmp')
DB_ABSOLUTE_PATH = os.path.join(HQ_FO... |
juancruzgassoloncan/Udacity-Robo-nanodegree | src/rover/ex_2/warp_perspect.py | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
image_name = '../data/IMG/robocam_2017_10_03_15_35_32_475.jpg'
image = mpimg.imread(image_name)
def perspect_transform(img, src, dst):
# Get transform matrix using cv2.getPerspectivTransform()
M = cv2.getPerspect... |
stefanwebb/tensorflow-models | tensorflow_models/models/avb_concrete_no_learn_prior_iw.py | # MIT License
#
# Copyright (c) 2017, Stefan Webb. All Rights Reserved.
#
# 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 us... |
mavenave/if-touched | if_touched.py | import os
import subprocess
def watch_files(directory, action):
file_contents = store_content(directory)
while True:
new_file_content = store_content(directory)
shared_content = set(file_contents.items()) &
set(new_file_content.items())
i... |
wkentaro/fcn | examples/voc/train_fcn16s.py | #!/usr/bin/env python
import argparse
import datetime
import os
import os.path as osp
os.environ['MPLBACKEND'] = 'Agg' # NOQA
import chainer
import fcn
from train_fcn32s import get_data
from train_fcn32s import get_trainer
here = osp.dirname(osp.abspath(__file__))
def main():
parser = argparse.ArgumentPars... |
MartinThoma/akademie-graph | create_dummy_data.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# EXPLANATION:
# This file fills the folder /data with dummy files (necessary for development
# purposes while we don't have real data yet)
# ---------------------------------------------------... |
RianFuro/vint | dev_tool/show_ast.py | #!/usr/bin/env python
import sys
from argparse import ArgumentParser
from pathlib import Path
from pprint import pprint
vint_root = Path(__file__).resolve().parent.parent
sys.path.append(str(vint_root))
from vint.ast.node_type import NodeType
from vint.ast.traversing import traverse
from vint.ast.parsing import Pars... |
mweb/python | exercises/variable-length-quantity/example.py | EIGHTBITMASK = 0x80
SEVENBITSMASK = 0x7f
def encode_single(n):
bytes = [n & SEVENBITSMASK]
n >>= 7
while n > 0:
bytes.append(n & SEVENBITSMASK | EIGHTBITMASK)
n >>= 7
return bytes[::-1]
def encode(numbers):
return sum((encode_single(n) for n in numbers), [])
def decode(bytes)... |
alvarocesped/01Tarea | Tarea1.py | import numpy as np
import matplotlib.pyplot as plt
import time
from pylab import *
from astropy import constants as cs
from scipy import integrate
UA=1.49597860*10**13
##Pregunta 1
#Guardammos los datos según columna en variables
longitud= np.loadtxt('sun_AM0.dat', usecols = [0])
flujo= np.loadtxt('sun_AM0.dat', usec... |
wolfy1339/Python-IRC-Bot | ansi.py | BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
RESET = '\033[0;0m'
BOLD = '\033[1m'
REVERSE = '\033[2m'
BLACKBG = '\033[40m'
REDBG = '\033[41m'
GREENBG = '\033[42m'
YELLOWBG = '\033[43m'
BLUEBG = '\033[44m'
MAGENTA... |
chenbin11200/AlgorithmInPython | src/6_ZigZagConversion.py | class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
evenColumnIndex = True
result = []
stringLength = len(s)
if numRows >= stringLength or numRows == 1:
return s
fullL... |
conan-io/conan | conans/client/build/compiler_flags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# Visual Studio cl options reference:
# https://msdn.microsoft.com/en-us/library/610ecb4h.aspx
# "Options are specified by either a forward slash (/) or a dash (–)."
# Here we use "-" better than "/" that produces invalid escaped chars using A... |
jakejhansen/minesweeper_solver | minesweeper_pygame.py | import pygame
import math
import numpy as np
import random
import time
import mss
class Minesweeper(object):
def __init__(self, ROWS = 10, COLS = 10, SIZEOFSQ = 100, MINES = 13, display = False):
""" Initialize Minesweeper
Rows, Cols: int - Number of rows and cols on the board
SIZE... |
njanakiev/blender-scripting-intro | scripts/simple_sphere.py | import bpy
import colorsys
from math import sin, cos, pi
from mathutils import Euler
TAU = 2*pi
def rainbow_lights(r=5, n=100, freq=2, energy=100):
for i in range(n):
t = float(i)/float(n)
pos = (r*sin(TAU*t), r*cos(TAU*t), r*sin(freq*TAU*t))
# Create lamp
bpy.ops.object.add(type=... |
Ahmed--Mohsen/leetcode | contains_duplicate.py | """
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
"""
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums)... |
OmnesRes/pan_cancer | paper/cox_regression/HNSC/cox_regression.py | ## A script for finding every cox coefficient and pvalue for every mRNA in HNSC Tier 3 data downloaded Feb. 2015
from rpy2 import robjects as ro
import numpy as np
import os
ro.r('library(survival)')
##This call will only work if you are running python from the command line.
##If you are not running from the command... |
walkr/nanoservice | test/test_pub_sub.py | import unittest
from nanoservice import Subscriber
from nanoservice import Publisher
from nanoservice import Authenticator
class BaseTestCase(unittest.TestCase):
def setUp(self, authenticator=None):
self.addr = 'inproc://test'
self.client = Publisher(self.addr, authenticator=authenticator)
... |
vntarasov/openpilot | selfdrive/controls/radard.py | #!/usr/bin/env python3
import importlib
import math
from collections import defaultdict, deque
import cereal.messaging as messaging
from cereal import car
from common.numpy_fast import interp
from common.params import Params
from common.realtime import Ratekeeper, Priority, config_realtime_process
from selfdrive.confi... |
psnovichkov/narrative | src/biokbase/narrative/jobs/appmanager.py | """
A module for managing apps, specs, requirements, and for starting jobs.
"""
from job import Job
from jobmanager import JobManager
from specmanager import SpecManager
import biokbase.narrative.clients as clients
from biokbase.narrative.widgetmanager import WidgetManager
from biokbase.narrative.app_util import (
... |
Spiderlover/Toontown | toontown/coghq/DistributedBanquetTable.py | import math
import random
from pandac.PandaModules import NodePath, Point3, VBase4, TextNode, Vec3, deg2Rad, CollisionSegment, CollisionHandlerQueue, CollisionNode, BitMask32, SmoothMover
from direct.fsm import FSM
from direct.distributed import DistributedObject
from direct.distributed.ClockDelta import globalClockDel... |
OldPanda/The-Analysis-of-Algorithms-Code | Chapter_1/1.8.py | """
Multiplication:
Input: a base b, a length n, and two n-digit integers X and Y.
Output: a 2n-digit integer Z represented by its digit such that Z = XY.
"""
import random
# This function comes from 1.3.py
def integer_value(b, n, d_list):
v = 0
for i in range(n-1, -1, -1):
v = v*b + d_list[i]
return v
def... |
SoPR/horas | apps/profiles/migrations/0004_auto_20190622_1846.py | # Generated by Django 2.0.13 on 2019-06-22 18:46
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("profiles", "0003_auto_20190614_1214")]
operations = [
migrations.AlterField(
model_name="user",
... |
Roibal/Geotechnical_Engineering_Python_Code | Example-Code/Tunneling_Stresses.py | import math
import matplotlib.pyplot as plt
import numpy as np
#The purpose of this program is to calculate the Radial, Tangential and Shear Stress in a circular tunnel given input parameters.
def RadialStress(Pz, Diameter, k, Theta, r, Pi):
"""
RadialStress Function will Return the Radial Stress at a given p... |
ksmit799/Toontown-Source | toontown/ai/ToontownMagicWordManager.py | from direct.interval.IntervalGlobal import *
from direct.distributed import PyDatagram
from direct.distributed.MsgTypes import MsgName2Id
from pandac.PandaModules import *
from direct.distributed import DistributedObject
from toontown.toon import DistributedToon
from direct.directnotify import DirectNotifyGlobal
from t... |
HadrienG/taxadb | doc/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# taxadb documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 8 12:59:49 2016.
#
# 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
# aut... |
haakenlid/django-extensions | tests/testapp/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django_extensions.db.fields import (
AutoSlugField,
RandomCharField,
ShortUUIDField,
)
from django_extensions.db.fields.json import JSONField
from django_extensions.db.models import ActivatorModel, TimeStampedModel
class Secret(models.Model):
... |
danoneata/video_annotation | add_user.py | import argparse
import pdb
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from models import User
db = SQLAlchemy()
def main():
parser = argparse.ArgumentParser(description='Adds user to the database.')
parser.add_argument(
'-n', '--name',
required=True,
help="Na... |
batuhaniskr/Social-Network-Tracking-And-Analysis | parser/operation/tweet_query.py | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
def setUsername(self, username):
self.username = username
return self
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self... |
jamiebull1/geomeppy | geomeppy/patches.py | # Copyright (c) 2016 Jamie Bull
# Copyright (c) 2012 Santosh Philip
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# ======================================================... |
chill17/pykbart | pykbart/kbartrecord.py | #!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from collections import OrderedDict, MutableMapping
import six
from pykbart.holdings import (coverage_begins, coverage_begins_text,
coverage... |
qateam123/eq | tests/integration/mci/test_empty_questionnaire.py | from tests.integration.create_token import create_token
from tests.integration.integration_test_case import IntegrationTestCase
from tests.integration.mci import mci_test_urls
class TestEmptyQuestionnaire(IntegrationTestCase):
def test_empty_questionnaire(self):
# Get a token
token = create_token... |
tylerclair/py3canvas | py3canvas/apis/webhooks_subscriptions.py | """WebhooksSubscriptions API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
class WebhooksSubscriptionsAPI(BaseCanvasAPI):
"""WebhooksSubscriptions API Version 1.0.""... |
phpython/phpython | demo/sample/004.py | #! python
# operator for:
# Measure some strings:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
#! python
# range function
print range(10)
print range(5, 10)
print range(0, 10, 3)
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]
#! python
# brea... |
rwl/PyCIM | CIM14/CDPSM/Unbalanced/IEC61970/Wires/EnergyConsumer.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... |
tagomatech/ETL | BBG/bbgdailyhistory.py | # *- bbgdailyhistory.py -*
import os
import numpy as np
import pandas as pd
import blpapi
class BBGDailyHistory:
'''
Parameters
----------
sec : str
Ticker
fields : str or list
Field of list of fields ('PX_HIGH', 'PX_LOW', etc...)
start : str
Start date
end : str
... |
AffilaeTech/niav | niav/ssh.py | import logging
import paramiko
class Ssh(object):
"""
SSH utilities
- Execute commands on remote host.
- Copy files from and to remote host.
"""
def __init__(self, host, port=None, user=None, password=None, private_key=None):
"""
:param host: Hostname ... |
tschijnmo/TopologyFromTraceroute | plotpajek.py | #!/usr/bin/env python
"""Plots the graph in Pajek format
It uses networkx for the plotting, which in turn is replied upon the matplotlib
for the actual drawing engine.
"""
import sys
import networkx as nx
import matplotlib.pyplot as plt
def main():
"""The main function"""
try:
file_name = sys.a... |
zarr-developers/numcodecs | numcodecs/tests/test_vlen_bytes.py | import unittest
import numpy as np
import pytest
try:
from numcodecs.vlen import VLenBytes
except ImportError: # pragma: no cover
raise unittest.SkipTest("vlen-bytes not available")
from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array,
ch... |
thebeansgroup/smush.py | smush/optimiser/optimiser.py | import os.path
import os
import shlex
import subprocess
import sys
import shutil
import logging
import tempfile
from scratch import Scratch
class Optimiser(object):
"""
Super-class for optimisers
"""
input_placeholder = "__INPUT__"
output_placeholder = "__OUTPUT__"
# string to place between t... |
yeleman/snisi | snisi_core/management/commands/create-expected-reporting.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
import datetime
from django.core.management.base import BaseCommand
from django.utils import timezone
from optparse ... |
ningirsu/stepmania-server | setup.py | """ Setup script """
import shutil
import os
import sys
import glob
from setuptools import setup, find_packages
try:
import py2exe
except ImportError:
pass
import smserver
for filename in glob.glob("cfg/*.yml*"):
shutil.copy(filename, "smserver/_fallback_conf")
CONF_DIR = None
if os.path.splitdrive(sy... |
lockwooddev/backbone-nasa | src/nasa/conf/dev_settings.py | from nasa.conf.global_settings import *
SECRET_KEY = 'dev'
DEBUG = TEMPLATE_DEBUG = True
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME... |
oblique-labs/pyVM | rpython/flowspace/generator.py | """Flow graph building for generators"""
from rpython.flowspace.argument import Signature
from rpython.flowspace.bytecode import HostCode
from rpython.flowspace.pygraph import PyGraph
from rpython.flowspace.model import (Block, Link, Variable,
Constant, checkgraph, const)
from rpython.flowspace.operation import op... |
charles-cooper/raiden | raiden/encoding/messages.py | # -*- coding: utf-8 -*-
import struct
from ethereum import slogging
from raiden.constants import UINT64_MAX, UINT256_MAX
from raiden.encoding.encoders import integer, optional_bytes
from raiden.encoding.format import (
buffer_for,
make_field,
namedbuffer,
pad,
)
from raiden.encoding.signing import rec... |
brycedrennan/pwdgen | pwdgen/command_line.py | import argparse
from pwdgen import password, ascii, alphanumeric, passphrase, numeric
generators = {"password": password, "ascii": ascii, "alphanumeric": alphanumeric, "passphrase": passphrase, "numeric": numeric}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("length", nargs="?", defaul... |
Ace-Of-Fades/HOST | share/qt/extract_strings_qt.py | #!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format Downloaded by xgettext.
R... |
indico/indico | indico/modules/events/persons/blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.modules.events.persons.controllers import (RHEditEventPerson, RHEmailEventPersons, RHEventPers... |
jhanley634/testing-tools | problem/eda/us_home_sales/group_by_month.py | #! /usr/bin/env python
from collections import defaultdict
from pathlib import Path
import csv
import datetime as dt
from matplotlib.dates import DateFormatter
import matplotlib
matplotlib.use('Agg') # noqa E402
import matplotlib.pyplot as plt # noqa E402
import pandas as pd # noqa E402
def group_by_month(infile... |
maartenbreddels/vaex | tests/ml/pygbm_test.py | import pytest
pytest.importorskip("pygbm")
import os
import numpy as np
import pygbm as lgb
import vaex.ml.incubator.pygbm
import vaex.ml.datasets
from vaex.utils import _ensure_strings_from_expressions
import test_utils
# the parameters of the model
param = {'learning_rate': 0.1, # learning rate
'max_d... |
gtrdotmcs/python-withings | tests/test_withings_sleep.py | import time
import unittest
from withings import WithingsSleep, WithingsSleepSeries
class TestWithingsSleep(unittest.TestCase):
def test_attributes(self):
data = {
"series": [{
"startdate": 1387235398,
"state": 0,
"enddate": 1387235758
... |
Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_cognitive_services_management_client_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 ... |
intelivix/scrapy-venom | docs/source/conf.py | # -*- coding: utf-8 -*-
#
# scrapy-venom documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 28 23:09:44 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.
... |
ministryofjustice/manchester_traffic_offences_pleas | apps/plea/migrations/0032_auto_20160420_1121.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('plea', '0031_case_created'),
]
operations = [
migrations.AddField(
model_name='case',
name='complete... |
bitmazk/cmsplugin-pdf | cmsplugin_pdf/migrations/0002_auto__add_field_pdfpluginmodel_display_type.py | # flake8: noqa
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'PDFPluginModel.display_type'
db.add_column('cmsplugin_pdfpluginmodel', 'displ... |
airportmarc/the416life | src/apps/users/models.py | from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.transl... |
ckaus/pydwd | pydwd/utils/ftphelper.py | # -*- coding: utf-8 -*-
import datetime
import ftplib
import io
import time
import traceback
import urllib2
import zipfile
import logger
def get_modified_time_of_file(host, file_path, file_name):
modified_time = 0
try:
ftp = ftplib.FTP(host)
ftp.login()
ftp.cwd(file_path)
mod... |
tiangolo/fastapi | tests/test_tutorial/test_request_files/test_tutorial003.py | from fastapi.testclient import TestClient
from docs_src.request_files.tutorial003 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/files/": {
"post": {
"summary": "Create Files",
... |
ritviksahajpal/EPIC | read_EPIC_output/constants.py | import os, sys, logging, errno, ast, psutil
from ConfigParser import SafeConfigParser
# Parse config file
parser = SafeConfigParser()
parser.read('../config_EPIC.txt')
###############################################################################
# Constants
#
#
######################################################... |
oubiwann/carapace | carapace/sdk/registry.py | from zope.component import getGlobalSiteManager, getUtility
from zope.interface.interfaces import ComponentLookupError
from carapace.sdk import interfaces
def getConfig():
return getUtility(interfaces.IConfig)
def getLogger():
return getUtility(interfaces.ILogger)
def getTerminalWriter():
return getU... |
PyAbel/PyAbel | abel/tests/test_tools_circularize.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from numpy.testing import assert_allclose
import abel
from abel.tools.circularize import circularize, circularize_image
def test_circularize_image():
IM = abel.tools.analytical.Sample... |
srvanrell/libsvm-weka-python | GridSearch-LibSVM.py | #!/usr/bin/env python
"""
Script to test that needed packages are correctly installed
Tested with:
- python-weka-wrapper 0.3.8
- LibSVM 1.0.8
- GridSearch 1.0.9
"""
import weka.core.jvm as jvm
from weka.core.converters import Loader
from weka.classifiers import Classifier, Evaluation, GridSearch
jvm.logger.setLevel(j... |
PointyDev/discord-bughunternotifs | default_settings.py | # Bug Hunter Notifications - By Pointy#5565
# For more information on configuring this file, check the repo.
# https://github.com/PointyDev/discord-bughunternotifs
# Login Token
token = ""
# New report notifications
# Default: newEnabled = True
newEnabled = True
# Denied report notifications
# Default: deniedEnabled... |
EventBuck/EventBuck | vendors/sendgrid/message.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rfc822
from header import SmtpApiHeader
class Message(object):
"""
Sendgrid Message
"""
def __init__(self, name_from, addr_from, subject, text="", html=""):
"""
Constructs Sendgrid Message object
Args:
... |
tommeagher/alva | v.5/alva.py | #all the imports
import sqlite3
#for a heavier-duty app, we could use sqlalchemy
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
import local_settings
import re
from datetime import date, datetime
#Link to config settings
ALVA_SETTINGS... |
iancze/JudithExcalibur | assets/initialize_walkers.nuker.py | # This notebook is designed to allow you to tweak how you might like your walkers initialized. Edit the cells as you see fit and then proceed to evaluate each cell and save the final `pos0.npy` file.
import numpy as np
# Generally, you want at least a few walkers for each dimension you may be exploring. To start wit... |
JBPennington/SlackBot | unittests/test_rest_api.py | import unittest
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from rest_api import app
class TestRestAPI(unittest.TestCase):
def test_create_bot(self):
app.run(debug=True)
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
|
conan-io/conan | conans/test/unittests/util/test_encrypt.py | import uuid
import pytest
from conans.util import encrypt
def test_encryp_basic():
key = str(uuid.uuid4())
message = 'simple data ascii string'
data = encrypt.encode(message, key)
assert type(message) == type(data)
assert message != data
assert message != data
decoded = encrypt.decode(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.