repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
edgedb/edgedb | edb/pgsql/dbops/composites.py | Python | apache-2.0 | 4,645 | 0 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | NotImplemented
return tuple(self) == tup
def __getitem__(self, index):
return getattr(self, self.__class__._fields___[index])
def __iter__(self):
for name in self.__class__._fields___:
yield getattr(self, name)
def __len__(self):
return len(self.__clas | s__._fields___)
def items(self):
for name in self.__class__._fields___:
yield name, getattr(self, name)
def keys(self):
return iter(self.__class__._fields___)
def __str__(self):
f = ', '.join(str(v) for v in self)
if len(self) == 1:
f += ','
... |
dongweiming/speakerdeck | tornado/sleep_task.py | Python | apache-2.0 | 282 | 0.007092 | import time
from celery import Celery
celery = Celery("tasks", broker="amqp://guest:guest@localhost:5672")
celery. | conf.CELERY_RESULT_BACKEND = "amqp"
@celery.task
def sleep(seconds):
time.sleep(float(seconds))
return sec | onds
if __name__ == "__main__":
celery.start()
|
SYSC-3010-F5/AVA-SH | src/coffee-maker/WeightStub.py | Python | gpl-3.0 | 274 | 0.018248 | class WeightSensor:
weight | = 0 #weight in grams
def __init__(self):
self.weight = 0
def getWeight(self):
if(self.weight < 700):
self.weight = self.weight + 5
|
return self.weight
|
ryota-sugimoto/hackerrank | dynamic_programming/stock_maximize/stock_maximize_2.py | Python | gpl-2.0 | 359 | 0.038997 | #!/usr/bin/env python
def main(l):
maximum = l[-1]
profits = []
for i in range(len( | l)-1, -1, -1):
if l[i] > maximum:
maximum = l[i]
else:
| profits.append(maximum - l[i])
return sum(profits)
import sys
T = int(sys.stdin.next())
for i in range(T):
N = int(sys.stdin.next())
l = map(int,sys.stdin.next().split())
print main(l)
|
yossisolomon/ITGController | plot_from_stats.py | Python | gpl-3.0 | 1,136 | 0.035211 | #!/usr/bin/python
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#from matplotlib.backends.backend_pdf import PdfPages
import sys
def stats_file_as_matrix(file_name):
with open(file_name, 'r') as f:
return [ map( | float,line.strip().split(' ')) for line in f ]
#pdfTitle = 'results.pdf'
#pp = PdfPages(pdfTitle)
titles = ["Bitrate", "Delay", "Jitter", "Packet loss"]
for f in sys.argv[1:]:
print("Starting work on "+f+", converting stats to matrix!")
mat = stats_file_as_matrix(f)
| x = range(len(mat))
#define the figure size and grid layout properties
figsize = (10, 8)
cols = 2
rows = 2
gs = gridspec.GridSpec( rows, cols)
fig = plt.figure(num=1, figsize=figsize)
fig.suptitle(f)
ax = []
for i in range(4):
y = map(lambda r:r[i+1],mat)
row = (i // cols)
col = i % cols
ax.append(... |
pcecconi/mapground | fileupload/apps.py | Python | mit | 160 | 0 | # -*- coding: utf-8 -*-
from | __future__ import unicode_literals
from django | .apps import AppConfig
class FileuploadConfig(AppConfig):
name = 'fileupload'
|
victor-estrade/datawarehouse | datawarehouse/baldi2016.py | Python | mit | 2,192 | 0.014181 | # -*- coding: utf-8 -*-
import sys
import os
import pandas as pd
import h5py
from .download import maybe_download
from .download import get_data_dir
def load_ba | ldi2016_train_no_pile():
"""
Loads data from the baldi2016 dataset, and downloads it if necessary.
Return
------
X, y : as Dataframe, where X is the data and y is the labels
"""
url = "http://mlphysics.ics.uci.edu/data/hepjets/highlevel/train_no_pile_10000000.h5"
filename = os.path.... | |
codedcolors/pygrow | grow/commands/filter_test.py | Python | mit | 892 | 0.003363 | from . import filter
from click import testing as click_testing
from grow.testing import testing
import unittest
class FilterTestCase(unittest.TestCase):
def setUp(self):
self.test_pod_dir = testing.create_test_pod_dir()
self.runner = click_testing.CliRunner()
def test_filter(self):
args = [self.tes... | voke(filter.filter, args, catch_exceptions=False)
self.assertEqual(0, result.exit_code)
args = [self.test_pod_dir, '--locale=de', '-o', 'missing.po']
result = self.runner.invoke(filter.filter, args, catch_exceptions=False)
self.assertEqual(0, result.exit_code)
args = [self.test_pod_dir, '--out_dir=m... | :
unittest.main()
|
eka/pygrabbit | pygrabbit/parser.py | Python | mit | 1,924 | 0.00104 | import requests
from lxml import html
from ._compat import urljoin
from ._helpers import cached_attribute
class PyGrabbit:
headers = {'User-agent': 'PyGrabbit 0.1'}
def __init__(self, url):
self.url = url
self._tree = None
self._content = requests.get(url, headers=self.headers).text
... | text[0].strip()
@cached_attribute
def images(self):
nodes = self.select(
'//meta[@property="og:image"]/@content',
'//meta[@name="twitter:imag | e"]/@content',
'//img[@id="main-image" or @id="prodImage"]/@src',
'//img[not(ancestor::*[contains(@id, "sidebar") or contains(@id, "comment") or contains(@id, "footer") or contains(@id, "header")]) and ancestor::*[contains(@id, "content")]]/@src',
'//img[not(ancestor::*[contains(@id,... |
twz915/django | tests/builtin_server/tests.py | Python | bsd-3-clause | 4,631 | 0.000216 | import sys
import traceback
from io import BytesIO
from unittest import TestCase
from wsgiref import simple_server
# If data is too large, socket will choke, so write chunks no larger than 32MB
# at a time. The rationale behind the 32MB can be found in #5596#comment:4.
MAX_SOCKET_CHUNK_SIZE = 32 * 1024 * 1024 # 32 MB... | env = {'SERVER_PROTOCOL': 'HTTP/1.0'}
handler = FileWrapperHandler(None, BytesIO(), BytesIO(), env)
handler.run(wsgi_app_file_wrapper)
self.ass | ertTrue(handler._used_sendfile)
self.assertEqual(handler.stdout.getvalue(), b'')
self.assertEqual(handler.stderr.getvalue(), b'')
def test_file_wrapper_no_sendfile(self):
env = {'SERVER_PROTOCOL': 'HTTP/1.0'}
handler = FileWrapperHandler(None, BytesIO(), BytesIO(), env)
hand... |
nonZero/OpenCommunity | src/issues/south_migrations/0008_upgrade_issue_comments.py | Python | bsd-3-clause | 16,348 | 0.007524 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for c in orm['issues.IssueComment'].objects.all():
if c.issue.is_closed:
c.meeting = c.issue... | ted'", 'to' | : u"orm['users.OCUser']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_upcoming_meeting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
... |
mozaik-association/mozaik | mozaik_virtual_partner_involvement/models/__init__.py | Python | agpl-3.0 | 183 | 0 | # Copyright 201 | 8 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import distribution_list_line | _template
from . import virtual_partner_involvement
|
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_textbox38.py | Python | bsd-2-clause | 1,661 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | 300032]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column(' | A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
worksheet.insert_chart('E9', c... |
setten/pymatgen | pymatgen/io/abinit/netcdf.py | Python | mit | 17,296 | 0.002891 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""Wrapper for netCDF readers."""
from __future__ import unicode_literals, division, print_function
import os.path
import warnings
import numpy as np
from collections import OrderedDict
from monty.dev import r... | for children in self.walk_tree():
for child in children:
print(child)
def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT):
"""
Returns the value of a dimension.
Args:
dimname: Name | of the variable
path: path to the group.
default: return `default` if `dimname` is not present and
`default` is not `NO_DEFAULT` else raise self.Error.
"""
try:
dim = self._read_dimensions(dimname, path=path)[0]
return len(dim)
exce... |
greatmazinger/programming-interview-code | Python/comb.py | Python | gpl-2.0 | 382 | 0.036649 | def comb(xs):
if len(xs) == 0:
return [""]
else:
return comb2(xs) + [""]
def comb2(xs):
if len(xs) == 1:
| return [ xs ]
else:
subwo = comb2( xs[1:] )
head = xs[0]
subwit | h = [ head + zs for zs in subwo ]
return subwo + subwith + [ head ]
result = comb( "abcde" )
result.sort()
print result
print len( result )
|
brainstorm-ai/DIGITS | digits/job.py | Python | bsd-3-clause | 7,819 | 0.002046 | # Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import os
import os.path
import pickle
import shutil
import threading
import time
import flask
from .status import Status, StatusCls
from digits.config import config_value
from digits.utils import sizeof_fmt, ... | e'
@classmethod
def load(cls, job_id):
"""
Loads a Job in the given job_id
Returns the Job or throws an exception
"""
from digits.model.tasks | import TrainTask
job_dir = os.path.join(config_value('jobs_dir'), job_id)
filename = os.path.join(job_dir, cls.SAVE_FILE)
with open(filename, 'rb') as savefile:
job = pickle.load(savefile)
# Reset this on load
job._dir = job_dir
for task in job.ta... |
Sonblind/orchestra | simple_workflow/workflow.py | Python | apache-2.0 | 1,200 | 0 | from orchestra.workflow import Step
from orchestra.workflow import Workflow
from simple_workflow.crawl import crawl_page
crawl_step = Step(
slug='crawl',
name='Web Crawling',
description='Find an awesome image on a website',
worker_type=Step.WorkerType.MACHINE,
creation_depends_on=[],
function... | includes': [
'/static/simple_workflow/rate/js/modules.js',
'/static/simple_workflow/rate/js/controllers.js',
'/static/simple_workflow/rate/js/directives.js',
],
'stylesh | eet_includes': [],
'angular_module': 'simple_workflow.rate.module',
'angular_directive': 'rate',
}
)
simple_workflow = Workflow(
slug='simple_workflow',
name='Simple Workflow',
description='Crawl a web page for an image and rate it'
)
simple_workflow.add_step(crawl_step)
simple_workflo... |
liuqr/edx-xiaodun | common/djangoapps/student/views.py | Python | agpl-3.0 | 101,263 | 0.003328 | # encoding=utf-8
"""
Student Views
"""
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import datetime
import json
import logging
import re
import urllib
import uuid
import time
import base64
import socket
import urllib2
import hashlib
from suds.client import Client
import xmltodict
from django.utils import ti... | ["CTec", "通用那全技术"],
["CManage", "安全管理"],
["SPTec", "专项安全技术"],
],
"level": [
["J", "初级"],
["M", "中级"],
["S", "高级"],
],
"org": uniq_filter_org(crude_courses)
}
... | get("org", "")
con_col.update({"orgCon": org_con.split(',')})
subject_con = request.GET.get("subject", "")
con_col.update({"subCon": subject_con.split(',')})
level_con = request.GET.get('level', "")
con_col.update({"levelCon": level_con.split(',')})
for course in crude_courses:
# ... |
wjwwood/open-robotics-platform | template.py | Python | mit | 1,949 | 0.009236 | #!/usr/bin/env python -OO
# encoding: utf-8
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# 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 Softwa... | , let them know...
sys.stderr.write(str(PKG_ERROR)+"\nYou might not have the "+PKGN | AME+" \
module, try 'easy_install "+PKGNAME+"', else consult google.")
### Class ###
### Functions ###
def main():
pass
### IfMain ###
if __name__ == '__main__':
main()
|
SK-011/AF_DNS | AF_DNS.py | Python | gpl-2.0 | 7,971 | 0.048551 | #!/usr/bin/python
#~ from pprint import pprint
import getopt
import sys
import signal
import yaml
import socket
from dnslib import *
def usage (progName):
""" Print the program's usage and then sys.exit() """
print ("Usage: %s -c <configuration file> -l <listening address> -p <listening port> -r <remote resolver IP... |
handleArgs (sys.argv)
# Try to open the YAML configuration file
try:
f = open (confFile)
except:
print ("[!]\tCan't open %s" % confFile)
sys.stdout.flush ()
sys.exit (1)
# Try to load the YAML | configuration into an dictionnary
try:
confMap = yaml.safe_load (f)
except:
print ("[!]\tError while importing YAML configuration from %s" % confFile)
sys.stdout.flush ()
sys.exit (1)
# Try to close the YAML configuration file
try:
f.close ()
except:
print ("[!]\tError while closing %s" % confFile)
sys.stdout... |
JeroenDeDauw/teg | python/client/gui/tfont.py | Python | gpl-3.0 | 655 | 0.027481 | # $Id: tfont.py,v 1.2 2003/09/14 04:31:39 riq Exp $
#
# Tenes Empanadas Graciela
# Copyright 2000,2003 Ricardo Quesada (riq@coresecurity.com)
#
import pygame
if not pygame.font.get_init():
pygame.font.init()
TFont = {
'helvetica 8' : pygame.font.SysFont('helvetica',8),
'helvetica 10' : pygame.font... | t('helvetica',10),
'helvetica 12' : pygame.font.SysFont('helvetica',12),
'helvetica 16' : pygame.font.SysFont('helvetica',16,0),
'helvetica 16b' : pygame.font.SysFont('helvetica',16,1),
'helvetica 20' : pygame.font.SysFont('helvetica',20,0), |
'helvetica 20b' : pygame.font.SysFont('helvetica',20,1)
}
|
jonkrohn/study-group | weekly-work/week1/softmax_vs_convolutional_nn.py | Python | mit | 3,870 | 0.001809 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
def softmax():
# Model variables
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zer... | al_network():
# Model variables
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
# Layer 1
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x | _image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# Layer 2
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x... |
bblacey/FreeCAD-MacOS-CI | src/Mod/TemplatePyMod/Commands.py | Python | lgpl-2.1 | 8,820 | 0.020295 | # FreeCAD TemplatePyMod module
# (c) 2007 Juergen Riegel LGPL
#
# import FreeCAD modules
import FreeCAD, FreeCADGui,inspect
# helper -------------------------------------------------------------------
def addCommand(name,cmdObject):
(list,num) = inspect.getsourcelines(cmdObject.Activated)
pos = 0
... | N")
pos = info["Position"]
if (down):
pnt = self.av.getPoint(pos[0],pos[1])
FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[0])+")")
msg = " -> (%f,%f,%f)\n" % (pnt.x, pnt.y, pnt.z)
FreeCAD.Console.PrintMessage(msg)
sph=self.pt.makeSpher | e(1.0, pnt)
self.pt.show(sph)
def exit(self, info):
esc = (info["Key"] == "ESCAPE")
if (esc):
self.leave()
class TemplatePyMod_Cmd4:
def __init__(self):
self.sc = SphereCreator()
def __del__(self):
FreeCAD.Console.PrintError('TemplatePyMod_Cmd4 was destroyed\n')
def Activated(self... |
kahvel/VEP-BCI | src/Robot.py | Python | mit | 4,342 | 0.001152 | import constants as c
from gui.windows import VideoStream
import socket
import cv2
import urllib
import numpy as np
class Robot(object):
def __init__(self, connection):
self.connection = connection
""" @type : Connections.ConnectionProcessEnd.RobotConnection """
self.socket = None
... | bled:
if self.stream is not None:
self.bytes += self.stream.read(1024)
a = self.bytes.find('\xff\xd8')
b = self.bytes.find('\xff\xd9')
if a != -1 and b != -1:
jpg = self.bytes[a:b+2]
self.bytes = self.byt... | 8), cv2.CV_LOAD_IMAGE_COLOR)
if self.psychopy_disabled is not None:
if self.psychopy_disabled:
self.window.updateStream(i)
else:
self.connection.sendMessage(i)
def updateWindow(self):
... |
pankajn17/intern | web/__init__.py | Python | gpl-3.0 | 716 | 0.005587 | #!/usr/bin/env python
"""web.py: makes web apps (http://webpy.org)"""
from __future__ import generators
| __version__ = "0.36"
__author__ = [
"Aaron Swartz <me@aaronsw.com>",
"Anand Chitipothu <anandology@gmail.com>"
]
__license__ = "public domain"
__contributors__ = "see http://webpy.org/changes"
import utils, db, net, wsgi, http, webapi, httpserver, debugerror
import template, form
impor | t session
from utils import *
from db import *
from net import *
from wsgi import *
from http import *
from webapi import *
from httpserver import *
from debugerror import *
from application import *
from browser import *
try:
import webopenid as openid
except ImportError:
pass # requires openid module
|
jeremiahyan/odoo | addons/mrp_repair/__manifest__.py | Python | gpl-3.0 | 329 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. Se | e LICENSE file for full copyright and licensing details.
{
'name': 'Mrp Repairs',
'version': '1.0',
'category': 'Inventory/Inventory',
'depends': ['repair', 'mrp'],
'installable': True,
'auto_install': True,
'application': False,
'license': 'LGPL-3',
}
| |
AlexanderLang/OpenAutomatedFarm | FarmGUI/farmgui/models/ParameterType.py | Python | gpl-3.0 | 1,237 | 0.000809 | """
Created on Feb 15, 2014
@author: alex
"""
from sqlalchemy import Column
from sqlalchemy.types import SmallInteger
from sqlalchemy.types import Unicode
from .meta import Base
class ParameterType(Base):
"""
classdocs
"""
__tablename__ = 'ParameterTypes'
_id = Column(SmallInteger, primary_key... | llable=False, unique=True)
unit = Column(Unicode(250), nullable=False)
def __init__(self, name, unit):
self.name = name
self.unit = unit
@property
def id(self): |
return self._id
@property
def serialize(self):
"""Return data in serializeable (dictionary) format"""
ret_dict = {
'id': self.id,
'name': self.name,
'unit': self.unit
}
return ret_dict
def __repr__(self):
return str(self.... |
dlintott/gns3-converter | gns3-converter.py | Python | gpl-3.0 | 715 | 0 | # Copyright (C) 2014 Daniel Lintott.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la | ter version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Li... | rter.main import main
main()
|
UPB-FILS/SE | TD3/time_server.py | Python | apache-2.0 | 730 | 0.00274 | """
Le premier serveur en Python
* Serveur
Ce serveur accepte 5 clients concurents et indique l'heure de serveur.
@author Dragos STOICA
@version 0.1
@date 19.feb.2017
"""
import socket
import time
# create a socket object
serversocke | t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 6666
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print... | e(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close() |
rustychris/stompy | stompy/spatial/interp_orthogonal.py | Python | mit | 11,003 | 0.020994 | """
Anisotropic orthogonal interpolation
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from .. import utils
from . import linestring_utils, interp_4d, wkb2shp, field
from ..grid import unstructured_grid
from ..model import unstructured_diffuser
import stompy.grid.quad_laplacian as quads
f... | ry.contains(geometry.Point(xy))
for xy in samples[['x' | ,'y']].values]
samples=samples.iloc[sel,:]
self.samples=samples
else:
self.samples=pd.DataFrame()
if self.background_field is not None:
self.add_background_samples()
for geom,Kxy in self.overrides:
# Which samples to drop:
... |
shams169/pythonProject | env/lib/python3.6/site-packages/app/person.py | Python | mit | 298 | 0.07047 | class Person(object):
def __init__(self,pid,name,age,sex):
self.pid=pid
se | lf.name=name
self.age=age
self.sex=sex
def eating(self):
return 'People | need to eat!'
def sleeping(self):
return 'People need to sleep!'
def walking(self):
return 'People can walk!'
|
hex7c0/EncryptoPy | core/utility.py | Python | gpl-3.0 | 4,093 | 0.001955 | '''
Common functions
Created on 10/set/2013
@package EncryptoPy
@subpackage core
@version 0.5
@author 0x7c0 <0x7c0@teboss.tk>
@copyright Copyright (c) 2013, 0x7c0
@license http://www.gnu.org/licenses/gpl.html GPL v3 License
'''
try:
from re import match
from os import urandom
from getpass import getpass
... | enable getpass module
@return: string
'''
while True:
temp = getpass(question)
if(match(regex, te | mp)):
return u_ut_crypto(temp)
print('Provide a correct alfanum password.')
def u_user_input(question):
'''
question about action
yes or no question
@param string question: output question
@return: bool
'''
while True:
action = input(question)
i... |
antoinecarme/pyaf | tests/artificial/transf_Integration/trend_MovingMedian/cycle_7/ar_/test_artificial_128_Integration_MovingMedian_7__100.py | Python | bsd-3-clause | 270 | 0.085185 | import pyaf.Bench.TS_datasets as tsds
import tests.arti | ficial.process_artificial_da | taset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 7, transform = "Integration", sigma = 0.0, exog_count = 100, ar_order = 0); |
xuru/pyvisdk | pyvisdk/do/iscsi_migration_dependency.py | Python | mit | 1,185 | 0.010127 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def IscsiMigrationDependency(vim, *args, **kwargs):
'''Provides migration dependency info... | raise InvalidArgume | ntError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
|
kevinnguyeneng/django-uwsgi-nginx | app/naf_autoticket/__init__.py | Python | gpl-3.0 | 270 | 0.003704 | from __future__ import absolute_import, unicode_literals
__author__ = 'admin'
# T | his will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery imp | ort appautoticket as celery_app
__all__ = ['celery_app'] |
tuskar/tuskar-ui | openstack_dashboard/dashboards/project/images_and_snapshots/images/tests.py | Python | apache-2.0 | 10,547 | 0.001233 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
image = self.images.list()[2]
api.glance.image_get(IsA(http.HttpRequest), str(image.id)) \
.AndReturn(image)
self.mox.ReplayAll()
res = self.client.get(
reverse('horizon:project:images_and_snapshots:images:detail',
args=... | nd_snapshots/images/detail.html')
self.assertEqual(res.context['image'].protected, image.protected)
@test.create_stubs({api.glance: ('image_get',)})
def test_image_detail_get_with_exception(self):
image = self.images.first()
api.glance.image_get(IsA(http.HttpRequest), str(image.id)) \
... |
djkonro/client-python | kubernetes/client/models/apps_v1beta1_deployment_status.py | Python | apache-2.0 | 10,171 | 0.001868 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | [AppsV1beta1DeploymentCondition]
"""
self._conditions = conditions
@property
def observed_generation(self):
"""
Gets the observed_generation of this AppsV1beta1DeploymentStatus.
The generation observed by the deployment controller.
:return: The observed_generat... | ed_generation
@observed_generation.setter
def observed_generation(self, observed_generation):
"""
Sets the observed_generation of this AppsV1beta1DeploymentStatus.
The generation observed by the deployment controller.
:param observed_generation: The observed_generation of this ... |
kalefranz/auxlib | auxlib/_vendor/five.py | Python | isc | 7,109 | 0.000281 | # -*- coding: utf-8 -*-
"""
amqp.five
~~~~~~~~~~~
Compatibility implementations of features
only available in newer Python versions.
"""
from __future__ import absolute_import
import io
import sys
try:
from collections import Counter
except ImportError: # pragma: no cover
from collections ... | if key not in skip_attrs)
return Type(Class.__name__, Class.__bases__, attrs)
return _clone_with_metaclass
# ############# threading.TIMEOUT_MAX ########################################
try:
from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX
except ImportError:
| THREAD_TIMEOUT_MAX = 1e10 # noqa
# ############# format(int, ',d') ############################################
if sys.version_info >= (2, 7): # pragma: no cover
def format_d(i):
return format(i, ',d')
else: # pragma: no cover
def format_d(i): # noqa
s = '%d' % i
groups = []
... |
SVladkov/Numismatic | database/database_tests.py | Python | gpl-3.0 | 310 | 0.048387 | import u | nittest |
import idatabase
import sqlite_database
import country
import coin
class DatabaseTest(unittest.TestCase):
def test_database_connection(self):
#test_database = sqlite_database.SQLiteDatabase()
#test_database.enter_coin(test_coin)
pass
if __name__ == '__main__':
unittest.main() |
Cadene/pretrained-models.pytorch | pretrainedmodels/models/inceptionresnetv2.py | Python | bsd-3-clause | 12,055 | 0.001659 | from __future__ import print_function, division, absolute_import
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import os
import sys
__all__ = ['InceptionResNetV2', 'inceptionresnetv2']
pretrained_settings = {
'inceptionresnetv2': {
'imagenet': {
'url': 'http://da... | nedmodels/inceptionresnetv2-520b38e4.pth',
'input_space': 'RGB',
'input_size': [3, 299, 299],
'input_range': [0, 1],
'mean': [0.5, 0.5, 0.5],
'std': [0.5, 0.5, 0.5],
'num_classes': 1001
}
}
}
class BasicConv2d(nn.Module):
def __i... | lanes, out_planes, kernel_size, stride, padding=0):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=False) # verify bias false
self.bn = nn.B... |
BILS/agda | agda/datisca/admin.py | Python | mit | 118 | 0 | from models import DatiscaNoduleBlastJob
from django.c | ontrib import | admin
admin.site.register(DatiscaNoduleBlastJob)
|
kovidgoyal/html5-parser | test/html5lib_adapter.py | Python | apache-2.0 | 10,101 | 0.002376 | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import codecs
import os
import re
import subprocess
import unittest
from html5_parser import check_bom, check_... | d-doctype-name-but' in line or 'unknown-doctyp | e' in line:
return 'gumbo auto-corrects malformed doctypes'
if fragment_context and ':' in fragment_context:
return 'Fragment parsing with non HTML contexts not supported'
def implementation(self, fragment_context, html, expected, errors, test_name):
if fragment_context:... |
MSeifert04/numpy | numpy/doc/subclassing.py | Python | bsd-3-clause | 28,624 | 0.000349 | """=============================
Subclassing ndarray in python
=============================
Introduction
------------
Subclassing ndarray is relatively simple, but it has some complications
compared to other Python objects. On this page we explain the machinery
that allows you to subclass ndarray, and the implicati... | pe(obj)
<class 'C'>
The definition of ``C`` is the same as before, but for ``D``, the
``__new__`` method returns an instance of class ``C`` rather than
``D``. Note that the ``__init | __`` method of ``D`` does not get
called. In general, when the ``__new__`` method returns an object of
class other than the class in which it is defined, the ``__init__``
method of that class is not called.
This is how subclasses of the ndarray class are able to return views
that preserve the class type. When taking... |
ftranschel/evoMPS | evoMPS/tdvp_common.py | Python | bsd-3-clause | 36,455 | 0.008696 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 11:49:32 2012
@author: ash
TODO:
- Sane implementation of sanity checks (return the info to the caller)
"""
import scipy as sp
import scipy.linalg as la
import numpy as np
import matmul as mm
import nullspace as ns
import logging
log = logging.getLogger(__nam... | n]).
This is (E_op(A1,A2)).conj().T.dot(x.ravel()) where x and the output are kets.
Alternatively, this is the same as x.conj().T.ravel().dot(E_(op.conj().T)(A2, A1))
where x is a bra.
See eps_l_noop().
Parameters
----------
x : ndarray
The argument matrix.
A1: nd... | The MPS ket tensor for the current site.
A2: ndarray
The MPS bra tensor for the current site.
op: ndarray
Single-site operator matrix elements op[s, t] = <s|op|t>
Returns
------
res : ndarray
The resulting matrix.
"""
op = op.conj()
out = np.zeros((A1.shape[... |
andersardo/gedMerge | simplepyged/docs/examples/LatexReport.py | Python | mit | 5,191 | 0.010981 | #this code is used from latex.py
import locale
import os
from mako.template import Template
def push(stack, item):
if item == None:
return stack
if item in stack:
return stack
stack.append(item)
return stack
class LatexReport:
def __init__(self, gedcom):
self.templa... | amily:
stack = push(stack, e)
return stack
def latex_index(self, stack):
""" Create an index of all individuals printed in report """
individuals = []
for family in stack:
for p in family.parents():
individuals = push(individuals, p)... | l(self.name(x), self.name(y)))
return individuals
def pages(self, individual):
""" Return list of xrefs of families in which a person can be found """
pages = []
if individual.parent_family() is not None:
return [individual.parent_family().xref()] # Person's pa... |
ohduran/CrowdFinanceInfographic | virtualenv/lib/python3.5/site-packages/setuptools/__init__.py | Python | mit | 5,440 | 0.000919 | """Extensions to the 'distutils' for large or complex distributions"""
import os
import functools
import distutils.core
import distutils.filelist
from distutils.core import Command as _Command
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools.extern.six.moves import filterfalse, ... | return list(out)
@staticmethod
def require_parents(packages):
"""
Exclude any apparent package that | apparently doesn't include its
parent.
For example, exclude 'foo.bar' if 'foo' is not present.
"""
found = []
for pkg in packages:
base, sep, child = pkg.rpartition('.')
if base and base not in found:
continue
found.append(pkg)... |
ahmedbodi/terracoin | contrib/seeds/generate-seeds.py | Python | mit | 4,378 | 0.00868 | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory tha... | ,'nodes_main.txt'),'r') as f:
process_nodes(g, f, 'pnSeed6_main', 13333)
g.write('\n' | )
with open(os.path.join(indir,'nodes_test.txt'),'r') as f:
process_nodes(g, f, 'pnSeed6_test', 2333)
g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n')
if __name__ == '__main__':
main()
|
thinksource/angularbigquery | lib/bigquery/__init__.py | Python | gpl-2.0 | 430 | 0 | from client import get_client
fr | om client import (
BIGQUERY_SCOPE,
BIGQUERY_SCOPE_READ_ONLY,
JOB_CREATE_IF_NEEDED,
JOB_CREATE_NEVER,
JOB_SOURCE_FORMAT_NEWLINE_DELIMITED_JSON,
JOB_SOURCE_FORMAT_DATASTORE_BACKUP,
JOB_SOURCE_FORMAT_CSV,
JOB_WRITE_TRUNCATE,
JOB_WRITE_APPEND,
JOB_WRITE_EMPTY,
JOB_ENCODING_UTF_8, |
JOB_ENCODING_ISO_8859_1
)
from schema_builder import schema_from_record
|
GoogleChromeLabs/chromeos_smart_card_connector | third_party/webports/src/src/build_tools/partition.py | Python | apache-2.0 | 11,123 | 0.012407 | #!/usr/bin/env python
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Manage partitioning of port builds.
Download historical data from the naclports builders, and use it to
partition all of th... | sorted_project_names = []
def Helper(project):
for dep_name in project.dep_names:
if dep_name not in sorted_project_names:
Helper(project | s[dep_name])
sorted_project_names.append(project.name)
for project in self.projects:
Helper(project)
return sorted_project_names
def Partition(projects, dims):
# Greedy algorithm: sort the projects by slowest to fastest, then add the
# projects, in order, to the shard that has the least work... |
watchdogpolska/feder | feder/letters/migrations/0002_auto_20151025_2345.py | Python | mit | 1,574 | 0.000635 | import django
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("letters", "0001_initial"),
("cases", "0004_case_user"),
]
operations = [
... | ver | bose_name="Author (if user)",
blank=True,
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
null=True,
),
),
migrations.AddField(
model_name="letter",
name="case",
fiel... |
teamfx/openjfx-9-dev-rt | modules/javafx.web/src/main/native/Tools/Scripts/webkitpy/codegen/main.py | Python | gpl-2.0 | 5,779 | 0.001557 | # Copyright (C) 2011 Google Inc. All rights reserved.
# Copyright (C) 2014 Apple Inc. All rights reserved.
#
# 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 c... | rent_scm.checkout_root, 'Source'))
all_tests_passed = True
input_directory = os.path.join('JavaS | criptCore', 'Scripts', 'tests', 'builtins')
reference_directory = os.path.join('JavaScriptCore', 'Scripts', 'tests', 'builtins', 'expected')
if not self.run_tests(input_directory, reference_directory):
all_tests_passed = False
print ''
if all_tests_passed:
print ... |
thorgate/django-esteid | esteid/session.py | Python | bsd-3-clause | 1,981 | 0.003029 | # pragma: no cover
import os
import warnings
from io import BytesIO
from typing import List, Union
from pyasice import Container
from esteid.types import DataFile
warnings.warn("This module is deprecated. Please use the new API", DeprecationWarning)
SESSION_KEY = "__esteid_session"
class EsteidSessionError(Exce... | session[SESSION_KEY] = data # Django session object requires setting keys explicitly
def delete_esteid_session(request):
session_data = request.session.pop(SESSION_KEY, {})
temp_signature_file = session_data.get("temp_signature_file")
if temp_signature_file:
try:
os.unlink(temp_sign... | mp_container_file:
try:
os.unlink(temp_container_file)
except OSError:
pass
def open_container(container_path: Union[str, BytesIO] = None, files_to_sign: List[DataFile] = None):
"""Open an existing BDoc container, or create a container with files to sign"""
if container... |
whyflyru/django-seo | tests/runtests.py | Python | bsd-3-clause | 533 | 0 | #!/usr/bin/env python
from __future__ import unicode_literals
import os
import sys
# Setup the path (could have been PYTHONPATH)
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
def runtests():
os.e | nviron["DJANGO_SETTINGS_MODULE"] = "tests.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
from django.core.management import ca | ll_command
result = call_command('test', 'userapp')
sys.exit(result)
if __name__ == "__main__":
runtests()
|
ricardodeazambuja/BrianConnectUDP | examples/HTML_Javascript_Smartphone_Python_Interface/pitch_yaw.py | Python | cc0-1.0 | 818 | 0.012225 | #!/usr/bin/env python
import cgi
print "Content-type: text/html\n\n"
form = cgi.FieldStorage()
pitch = form.getfirst("pitch", "0") # get the form value associated with form
# name 'x'. Use default "0" if there is none.
yaw = form.getfirst("yaw", "0") # similarly for name 'y'
pitch_... | f.write(str(pitch)+'\n')
f.write(str(yaw)+'\n')
except IOError:
print "IOError"
pass
print pitch + " " + yaw # Return to the webpage the values read
# # To read the file
# try:
# with open('/Users/Guest/Sites/temp.dat','r') as f:
# data1 = f.readline()
# data2 = f.readline()
# ex... | ta1)
# data2 = int(data2)
|
scikit-learn-contrib/imbalanced-learn | imblearn/under_sampling/_prototype_selection/_one_sided_selection.py | Python | mit | 7,093 | 0.000423 | """Class to perform under-sampling based on one-sided selection method."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
from collections import Counter
import numpy as np
from sklearn.base import clone
from sklearn.neighbors import KNeighborsClassifier
from sklear... | date_estimator()
| random_state = check_random_state(self.random_state)
target_stats = Counter(y)
class_minority = min(target_stats, key=target_stats.get)
idx_under = np.empty((0,), dtype=int)
for target_class in np.unique(y):
if target_class in self.sampling_strategy_.keys():
... |
gvinet/pynfcreader | tests/tests_iso_14443_a_card_1_hydranfc_v2.py | Python | apache-2.0 | 1,077 | 0.003714 | import time
from pynfcreader.sessions.iso14443.iso14443a import Iso14443ASession
def test_iso_14443_a_card_1_generic(hydranfc_connection):
hn = Iso14443ASession(drv=hydranfc_connection, block_size=120)
hn.connect()
hn.field_off()
time.sleep(0.1)
hn.field_on()
hn.polling()
r = hn.send_ap... | ert b'oW\x84\x0e2PAY.S.DDF01\xa5E\xbf\x0cBO\x07\xa0\x00\x00\x00B\x10\x10P\x02\x87\x01\x01\x9f(\x08@\x02\x00\x00\x00\x00a#O\x07\xa0\x00\x00\x00\x04\x10\nMASTERCARD\x02\x9f(\x08@\x00 \x00\x00\x00\x00' == r
r = hn.send_apdu("00 a4 04 00 07 A0 00 00 00 42 10 10 00")
assert b'o?\x84\x07\xa0\x00\x00\x00B\x104P\... | `\x02\x0b\x14\x9fM\x02\x0b\x14\xdf\x04' == r
r = hn.send_apdu("00 a4 04 00 07 A0 00 00 00 04 10 10 00")
assert b'o?\x84\x07\xa0\x00\x00\x00\x04\x104P\nMASTERCA\x87\x01\x02\x9f\x11\x01\x01\x9f\x12\nMTERCARD_-\x04fn\xbf\x0c\n\xdf`\x02\x0b\x14\x9fM\x14' == r
hn.field_off()
|
garyservin/python-zfm20x | pyzfm20x/__init__.py | Python | mit | 56 | 0.017857 | #! | /usr/bin/env python
i | mport pyzfm20x
VERSION = '0.1'
|
eubr-bigsea/tahiti | tahiti/workflow_history_api.py | Python | apache-2.0 | 3,691 | 0.001084 | # -*- coding: utf-8 -*-}
import logging
from flask import request, g
from flask_babel import gettext
from flask_restful import Resource
from marshmallow.exceptions import ValidationError
from tahiti.app_auth import requires_auth
from tahiti.schema import *
from tahiti.workflow_api import get_workflow
log = logging.g... | kflow_id == workflow_id,
WorkflowHistory.version == version).one()
# return json.load(history.content), 200
old = json.loads(history.content)
old['platform_id'] = old['platform']['id']
old['user_id'] = g.user.id
old['use... | old['user_name'] = g.user.name
del old['user']
for i, task in enumerate(old['tasks']):
task['operation_id'] = task['operation']['id']
if not task.get('name'):
task['name'] = f"{task['operation']['name']} {i}"
... |
VitalPet/c2c-rd-addons | report_crm_helpdesk/report/report_crm_helpdesk.py | Python | agpl-3.0 | 602 | 0.013289 | import time
from openerp.report import report_sxw
from openerp.osv import osv
class report_webkit_html(report_sxw.rml_parse):
def _ | _init__(self, cr, uid, name, context):
super(report_webkit_html, self).__init__(cr, uid | , name, context=context)
self.localcontext.update({
'time': time,
'cr':cr,
'uid': uid,
})
report_sxw.report_sxw('report.crm_helpdesk',
'crm.helpdesk',
'addons/report_crm_helpdesk/report/report_crm_helpdesk.mako',... |
apache/incubator-airflow | tests/providers/google/cloud/transfers/test_azure_fileshare_to_gcs_system.py | Python | apache-2.0 | 2,824 | 0.001416 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | st(GoogleSystemTest, AzureSys | temTest):
def setUp(self):
super().setUp()
@pytest.mark.usefixtures('provide_gcs_bucket_basic', 'provide_azure_fileshare_with_directory')
@provide_gcp_context(GCP_GCS_KEY)
def test_run_example_dag_azure_fileshare_to_gcs(self):
self.run_dag('azure_fileshare_to_gcs_example', CLOUD_DAG_FOL... |
stefanv/scipy3 | scipy/io/info.py | Python | bsd-3-clause | 828 | 0 | """
Data input and output
=====================
Functions
loadmat -- read a MATLAB style m | at file (version 4 through 7.1)
savemat -- write a MATLAB (version through 7.1) style mat file
netcdf_file -- read NetCDF files (version of ``pupynere`` package)
This version cannot write NetCDF files.
save_as_module -- simple storing of Python dictionary into module
that can then ... | attributes of the module.
mminfo -- query matrix info from Matrix Market formatted file
mmread -- read matrix from Matrix Market formatted file
mmwrite -- write matrix to Matrix Market formatted file
wavfile -- module to read / write wav files using numpy arrays
arrf -- read files i... |
Clarity-89/clarityv2 | src/clarityv2/accounts/apps.py | Python | mit | 101 | 0 | from dj | ango.apps import AppConfig
class AccountsConfig | (AppConfig):
name = 'clarityv2.accounts'
|
Elleo/rockwatch | pebble/pebble.py | Python | gpl-3.0 | 33,192 | 0.033231 | #!/usr/bin/env python
import array
import binascii
import glob
import itertools
import json
import logging
import os
import serial
import signal
import stm32_crc
import struct
import threading
import time
import traceback
import uuid
import zipfile
try:
from collections import OrderedDict
except:
from ordereddict i... | = LightBluePebble(self.id, pair_first)
else:
devicefile = "/dev/tty.Pebble"+id+"-SerialPortSe"
log.debug("Attempting to open %s as Pebble device %s" % (devicefile, id))
self._ser = serial.Serial(devicefile, 115200, timeout=1)
log.debug("Initializing reader thread")
| self._read_thread = threading.Thread(target=self._reader)
self._read_thread.setDaemon(True)
self._read_thread.start()
log.debug("Reader thread loaded on tid %s" % self._read_thread.name)
except PebbleError:
raise PebbleError(id, "Failed to connect to Pebble")
except:
raise
def _exit_signal_handler... |
GaretJax/lancet | lancet/commands/harvest.py | Python | mit | 1,408 | 0 | import re
import click
from lancet.utils import hr
@click.command()
@click.argument("query", required=False)
@click.pass_obj
def projects(lancet, query):
"""List Harvest projects, optionally filtered with a regexp."""
projects = lancet.timer.projects()
if query:
regexp = re.compile(query, flags... | )
)
@click.command()
@click.argument("project_id", type=int)
@click.pass_obj
def tasks(lancet, project_id):
"""List Harvest tasks for the given project ID."""
for task in lancet.timer.tasks(project_id):
click.echo(
" | {:>9d} {} {}".format(
task["id"], click.style("‣", fg="yellow"), task["name"]
)
)
|
Fillll/reddit2telegram | reddit2telegram/channels/pythondaily/app.py | Python | mit | 822 | 0.009732 | #encoding:utf-8
from utils import weighted_random_subreddit
t_channel = '@pythondaily'
subreddit = weighted_random_subreddit({
'flask': 3,
'Python': 6,
'django': 4,
'MachineLearning': 1,
'djangolearning': 1,
'IPython': 5,
'pystats': 4,
'JupyterNotebooks': 3
})
def send_post(submissi... | turn r2t.send_simple(submission,
text='{title}\n\n{words}\n\n/r/{subreddit_name}\n{short_link}',
gif='{title}\n\n/r/{subreddit_name}\n{short_link}',
img='{title}\n\n/r/{subreddit_name}\n{short_link}',
| album='{title}\n{link}\n\n/r/{subreddit_name}\n{short_link}',
other='{title}\n{link}\n\n/r/{subreddit_name}\n{short_link}',
words=words
)
|
mzdaniel/oh-mainline | vendor/packages/celery/celery/tests/test_events/test_events_state.py | Python | agpl-3.0 | 10,779 | 0.000928 | from __future__ import absolute_import
from time import time
from itertools import count
from celery import states
from celery.events import Event
from celery.events.state import State, Worker, Task, HEARTBEAT_EXPIRE
from celery.utils import uuid
from celery.tests.utils import unittest
class replay(object):
d... | ostname, "utest1")
self.assertEqual(task.exception, "KeyError('foo')")
self.assertEqual(task.traceback, "line 1 at main")
# SUCCESS
r.next()
self.assertEqual(task.state, states.SUCCESS)
self.assertTrue(task.succeeded)
self.assertEqual(task.timestamp, task.succeed... | assertEqual(task.runtime, 0.1234)
def assertStateEmpty(self, state):
self.assertFalse(state.tasks)
self.assertFalse(state.workers)
self.assertFalse(state.event_count)
self.assertFalse(state.task_count)
def assertState(self, state):
self.assertTrue(state.tasks)
s... |
Hyunakyu/FFR | LineAlpha/LineApi/LineCallback.py | Python | gpl-3.0 | 435 | 0.004598 | # -*- coding: utf-8 -*-
class LineCallback(object):
| def __init__(self, callback):
self.callback = callback
def Pinverified(self, pin):
self.callback("Enter PinCode '" + pin + "' to your mobile phone in 2 minutes")
def QrUrl(self, url):
self.callback( | "Login qrcode to your smartphone in 2 minutes\nModify By Hyunakyu\n" + url)
def default(self, str):
self.callback(str)
|
georgetown-analytics/classroom-occupancy | SensorDataCollection/Sensors/DBLogger.py | Python | mit | 421 | 0.009501 | import datetime
import MySQLdb
from os import sys
c | lass DBLogger:
def __init__(self, loc='default-location'):
self.usr = '<user>'
self.pwd = '<password>'
self.dbase = '<database>'
self.location = loc
self.conn = MySQLdb.connect(host="localhost", user=self.usr, passwd=self.pwd, db=self.dbase)
| self.cursor = self.conn.cursor()
def cleanUp(self):
self.conn.close()
self.cursor.close()
|
kotfu/netcontrol | netcontrol/operator.py | Python | mit | 642 | 0.006231 | # Copyright (c) 2017 Jared Crapo, K0TFU
# serialization options http://stackoverflow.com/questions/2627555/how-to-deserialize-an-object-with-pyyaml-using-safe-load
import persistent
class Operator(persistent.Persistent):
"""Model class for a ham radio operator
Attributes
----- | -----
callsign: str
The operators FCC issued call sign
firstname: str
The operator's given name(s)
lastname: str
The operator's surname or family name
"""
def __init__(self, callsign=None, firstname=None):
self.callsign = call | sign
self.firstname = None
self.lastname = None
|
livingenvironmentslab/UniCAVE | Python-Cluster-Launcher/ClusterLauncher.py | Python | mit | 1,680 | 0.007738 | import os
import sys
import time
import subprocess
import yaml
import pathlib
class ClusterLauncher:
def __init__(self, config_yaml):
self.Config = config_yaml
def Launch(self):
#read config
with open(self.Config, 'r') as yf:
config = yaml.safe_load(yf)
#launch... | ng child nodes
if config["head-wait"] is not None:
time.sleep(config["head-wait"])
#launch child nodes
children = []
for child_node in config["child-nodes"]:
children.append(ClusterLauncher | .LaunchUniCAVEWindow(config["build-path"], child_node))
#wait a bit between launching each child
if config["child-wait"] is not None:
time.sleep(config["child-wait"])
#poll head node process
done = False
while not done:
... |
wglass/zoonado | tests/test_iterables.py | Python | apache-2.0 | 1,016 | 0 | import collections
import unittest
from zoonado import iterables
class IterablesTests(unittest.TestCase):
def test_drain_on_list(self):
data = ["foo", 1, "bar", 9]
result = list(iterables.drain(data))
self.assertEqual(len(data), 0)
self.assertEqual(result, [9, "bar", 1, "foo"])... | "foo": 1, "bar": 9}
result = {key: value for key, value in iterables.drain(dat | a)}
self.assertEqual(len(data), 0)
self.assertEqual(result, {"foo": 1, "bar": 9})
|
kschmeckpeper/multiworld | multiworld/core/wrapper_env.py | Python | mit | 3,874 | 0.001549 | from gym.spaces import Box
from multiworld.core.serializable import Serializable
import numpy as np
class ProxyEnv(Serializable):
def __init__(self, wrapped_env):
self.quick_init(locals())
self._wrapped_env = wrapped_env
@property
def wrapped_env(self):
return self._wrapped_env
... | y] = np.zeros_like(env.observation_space[key].low)
else:
obs_means = dict()
for key in self.obs_to_normalize_keys:
obs_means[key] = np.array(obs_means[key])
if obs_stds is None:
| obs_stds = dict()
for key in self.obs_to_normalize_keys:
obs_stds[key] = np.zeros_like(env.observation_space[key].low)
else:
obs_stds = dict()
for key in self.obs_to_normalize_keys:
obs_stds[key] = np.array(obs_st... |
kalikaneko/bitmask-dev | src/leap/bitmask/bonafide/_protocol.py | Python | gpl-3.0 | 5,978 | 0 | # -*- coding: utf-8 -*-
# _protocol.py
# Copyright (C) 2014-2015 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | Protocol(object):
"""
Expose the protocol that interacts with the Bonafide Service API.
"""
_apis = defaultdict(None)
_sessions = defaultdict(None)
def _get_api(s | elf, provider):
# TODO should get deferred
if provider.domain in self._apis:
return self._apis[provider.domain]
# TODO defer the autoconfig for the provider if needed...
api = Api(provider.api_uri, provider.version)
self._apis[provider.domain] = api
return ap... |
titilambert/alignak | alignak/trigger_functions.py | Python | agpl-3.0 | 10,006 | 0.0002 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, ei... | irelinux.com
# Hartmut Goebel, h.goebel@goebel-consult.de
# Nicolas Dupeux, nicolas@dupeux.net
# Andrus Viik, andrus@a7k.pri.ee
# Sebastien Coavoux, s.coavoux@free.fr
# Thibault Cohen, titilambert@gmail.com
# Jean Gabes, naparuba@gmail.com
# This | file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope... |
dhylands/Bioloid | setup.py | Python | mit | 432 | 0 | from distutils.core import setup
setup(
name='Biolo | id',
version='0.1.0',
author='Dave Hylands',
author_email='dhylands@gmail.com',
packages=['bioloid'],
scripts=[],
| url='http://pypi.python.org/pypi/Bioloid/',
license='LICENSE',
description='Provides access to bioloid devices.',
long_description=open('README.md').read(),
install_requires=[
'pyyaml',
'pyserial'
],
)
|
nesi/easybuild-framework | easybuild/tools/toolchain/linalg.py | Python | gpl-2.0 | 13,669 | 0.004828 | ##
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | d. If not, see <http://www.gnu.org/licenses/>.
##
"""
Toolchain linalg module. Contains all (scalable) linear algebra related classes
@author: Stijn De Weirdt (Ghent Univer | sity)
@author: Kenneth Hoste (Ghent University)
"""
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.toolchain.toolchain import Toolchain
class LinAlg(Toolchain):
"""General LinearAlgebra-like class
can't be used without creating new class S(LinAlg)
To provide the BLAS/LA... |
mattdennewitz/hash-ring-ctypes | docs/conf.py | Python | mit | 8,253 | 0.006058 | # -*- coding: utf-8 -*-
#
# hash-ring-ctypes documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 2 18:10:26 2013.
#
# 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 fi... | umentclass [howto/manual]).
| latex_documents = [
('index', 'hash-ring-ctypes.tex', u'hash-ring-ctypes Documentation',
u'Matt Dennewitz', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts... |
pferreir/indico | indico/modules/categories/models/principals.py | Python | mit | 1,366 | 0.000732 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 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 sqlalchemy.ext.declarative import declared_attr
from indico.core.db import db
from indico.core.db.sq... | co.core.db.sqlalchemy.util.models import auto_table_args
from indico.util.string import format_repr
class CategoryPrincipal(PrincipalPermissionsMixin, db.Model):
__tablename__ = 'principals'
principal_backref_name = 'in_category_acls'
principal_for = 'Category'
unique_columns = ('category_id',)
al... | _attr
def __table_args__(cls):
return auto_table_args(cls, schema='categories')
#: The ID of the acl entry
id = db.Column(
db.Integer,
primary_key=True
)
#: The ID of the associated event
category_id = db.Column(
db.Integer,
db.ForeignKey('categories.cate... |
somini/gpodder | src/gpodder/util.py | Python | gpl-3.0 | 54,845 | 0.002753 | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2014 Thomas Perl and the gPodder Team
# Copyright (c) 2011 Neal H. Walfield
#
# gPodder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fr... | eds.feedburner.com/%s',
'yt:': 'http://www.youtube.com/rss/user/%s/videos.rss',
'sc:': 'http://soundcloud.com/%s', |
# YouTube playlists. To get a list of playlists per-user, use:
# https://gdata.youtube.com/feeds/api/users/<username>/playlists
'ytpl:': 'http://gdata.youtube.com/feeds/api/playlists/%s',
}
for prefix, expansion in PREFIXES.iteritems():
if url.startswith(prefix):
... |
eayunstack/nova | nova/tests/network/test_neutronv2.py | Python | apache-2.0 | 148,482 | 0.000653 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | True)
client1.list_networks(retrieve_all=False)
self.assertEqual('new_token1', token_store.admin_auth_token)
def test_admin_token_updated(self):
self.flags(url='http://anyhost/', group='neutron')
self.flags(url_timeout=30, group='neutron')
token_store = neutronv2.Adm... | context.RequestContext('userid', 'my_tenantid',
auth_token='token')
with contextlib.nested(
mock.patch.object(client.Client, "list_networks",
side_effect=mock.Mock),
mock.patch.object(client.Client, 'get_auth_info'... |
yandexdataschool/crayimage | examples/quick_track_preview.py | Python | mit | 2,313 | 0.031561 | import numpy as np
def sure_noise(patches):
return np.max(patches, axis=(1, 2, 3)) <= 4
def sure_track(patches):
return np.max(patches, axis=(1, 2, 3)) > 50
if __name__ == '__main__':
from sys import argv, exit
from crayimage.runutils import *
from crayimage.imgutils import plot_grid
try:
data_root ... | [1000, 1.0],
w | indow = 40,
step = 20
)
print(noise.shape)
print(tracks.shape)
plot_grid(noise, plot_title='Noise samples').show()
plot_grid(tracks[:, 1], plot_title='Track samples').show()
import matplotlib.pyplot as plt
import scipy.stats as stats
### selecting green channel
tracks = tracks[:, 1, :, :]
... |
gic888/MIEN | nmpml/parameters.py | Python | gpl-2.0 | 14,200 | 0.050634 | #!/usr/bin/evn python
## Copyright (C) 2005-2006 Graham I Cummins
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 2 of the License, or (at your option) any later version.
##... | or k in d.keys():
self[k]=d[k]
class ParameterSet(NmpmlObject):
'''This class acts as a container for an ordered list of numerical parameters. All the children of this clas | s must be ElementReferences to Number, and all targets must have Range and Precision specified. Adding other ElementReference children results in legal XML, but serious runtime errors in many of the methods.
The class is primarily used by Optimizers, consequently the interface is optimized for speed. It will not "pla... |
alienlike/courier | courier/keygen.py | Python | gpl-3.0 | 1,097 | 0.005469 | from Crypto.Random import random
from Crypto.Hash import SHA, SHA256
from Crypto import Random
from Crypto.PublicKey import RSA
class KeyGen:
# generate an RSA key pair
@staticmethod
def generate_rsa_key():
rand_gen = Random.new().read
k = RSA.generate(1024, rand_gen)
return k
... | k = sha.digest()
return | k
# generate a user-friendly recovery key
@staticmethod
def generate_recovery_key():
# hash a random 256-bit long integer
rand_nbr = random.getrandbits(256)
sha = SHA.new(str(rand_nbr))
# get the hex digest (40 alphanumeric characters)
k = sha.hexdigest()
# t... |
palankai/pyrs-resource | setup.py | Python | lgpl-3.0 | 1,432 | 0 | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pyrs-resource',
author='Csaba Palankai',
author_email='csaba.palankai@gmail.com',
packages=find_packages(),
include_pa... | net :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=('service', 'rest', 'restful', 'swagger', 'resource'),
zip_safe=False,
install_requires=[r for r in read("requireme | nts.txt").split("\n") if r],
)
|
QANSEE/partner-contact | base_location/models/partner.py | Python | agpl-3.0 | 3,295 | 0.000607 | # -*- coding: utf-8 -*-
#
#
# Author: Nicolas Bessi. Copyright Camptocamp SA
# Contributor: Pedro Manuel Baeza <pedro.baeza@serviciosbaeza.com>
# Ignacio Ibeas <ignacio@acysos.com>
# Alejandro Santana <alejandrosantana@anubia.es>
#
# This program is free software: you can redist... | censes/>.
#
#
from openerp import models, fields, api
class ResPartner(models.M | odel):
_inherit = 'res.partner'
zip_id = fields.Many2one('res.better.zip', 'City/Location')
@api.one
@api.onchange('zip_id')
def onchange_zip_id(self):
if self.zip_id:
self.zip = self.zip_id.name
self.city = self.zip_id.city
self.state_id = self.zip_id.st... |
tonyganchev/maven-deps | setup.py | Python | mit | 2,073 | 0.000482 | #!/usr/bin/env python
# from distutils.core import setup
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import mavendeps
__author__ = 'Tony Ganchev'
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_a... | cmdclass={'test': Tox},
packages=['mavendeps'],
include_package_data=Tru | e,
platforms='any',
classifiers=[
'Programming Language :: Python',
'Development Status :: 5 - Production/Stable',
'Natural Language :: English',
'Environment :: CLI Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: The M... |
jayceyxc/hue | apps/security/src/security/conf.py | Python | apache-2.0 | 1,255 | 0 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | p://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions... | slation import ugettext_lazy as _
from desktop.lib.conf import Config, coerce_bool
HIVE_V1 = Config(
key="hive_v1",
help=_("Use Sentry API V1 for Hive."),
default=True,
type=coerce_bool)
HIVE_V2 = Config(
key="hive_v2",
help=_("Use Sentry generic API V2 for Hive."),
default=False,
type=coerce_bool)
... |
jmtchllrx/pyMuse | src/hsaudiotag/id3v1.py | Python | mit | 2,528 | 0.008703 | # Created By: Virgil Dupras
# Created On: 2004/12/07
# Copyright 2010 Hardcoded Software (http://www.hard | coded.net)
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import struct
from .util | import FileOrPath
from .genres import genre_by_index
TAG_VERSION_1_0 = 1
TAG_VERSION_1_1 = 2
#id3v1 specs
#0-2:"TAG"
#3-32:Title
#33-62:Artist
#63-92:Album
#93-96:Year
#97-126:Comment
#127:Genre
def _arrange_id3_field(raw_field):
"""Format the read field properly
This function takes only the part of the... |
katchengli/tech-interview-prep | hackerrank/ctci-big-o.py | Python | apache-2.0 | 410 | 0.009756 | from math import sqrt, ceil
def isPrime(number):
if number < 2:
return False
if number == 2:
return True
for i in range(2, int(ceil(sqrt(number)))+1):
if number%i == 0:
r | eturn False
return True
p = int(input().strip())
for a0 in range(p):
n = int(input().strip())
if isPrime(n) == True:
print("Prime")
else:
print("Not prim | e")
|
vipulroxx/sympy | sympy/tensor/tensor.py | Python | bsd-3-clause | 133,023 | 0.001346 | """
This module defines tensors with abstract index notation.
The abstract index notation has been first formalized by Penrose.
Tensor indices are formal objects, with a tensor type; there is no
notion of index range, it is only possible to assign the dimension,
used to trace the Kronecker delta; the dimension can be... | tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
return tensors
def get_components_with_free_indices(self):
"""
Get a list of components with their associated indices.
Examples
========
>>> from sympy.tensor.tensor imp | ort TensorIndexType, tensor_indices, TIDS, tensorhead
>>> Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
>>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
>>> T = tensorhead('T', [Lorentz]*4, [[1]*4])
>>> A = tensorhead('A', [Lorentz], [[1]])
>>> t = TIDS.from_comp... |
google/TensorNetwork | examples/wavefunctions/wavefunctions_test.py | Python | apache-2.0 | 4,311 | 0.009743 | # Copyright 2019 The TensorNetwork Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | for the specific language governing permissions and
# limitations under the License.
import pytest
import numpy as np
import tensorflow as tf
import tensornetwork as tn
from examples.wavefunctions import wavefunctions
@pytest.mark.parametrize("num_sites", [2, 3, 4])
def test_expval(num_sites):
op = np.kron(np.arr... | 1.0]]), np.eye(2)).reshape([2] * 4)
op = tf.convert_to_tensor(op)
for j in range(num_sites):
psi = np.zeros([2] * num_sites)
psi_vec = psi.reshape((2**num_sites,))
psi_vec[2**j] = 1.0
psi = tf.convert_to_tensor(psi)
for i in range(num_sites):
res = wavefunctions.expval(psi, op, i, pbc=True... |
FrancoisRheaultUS/dipy | doc/examples/sfm_reconst.py | Python | bsd-3-clause | 6,318 | 0.001741 | """
.. _sfm-reconst:
==============================================
Reconstruction with the Sparse Fascicle Model
==============================================
In this example, we will use the Sparse Fascicle Model (SFM) [Rokem2015]_, to
reconstruct the fiber Orientation Distribution Function (fODF) in every voxel.
... | o.image import load_nifti, save_nifti
from dipy.io.gradients import read_bvals_bvecs
from dipy.core.gradients import grad | ient_table
from dipy.viz import window, actor
"""
For the purpose of this example, we will use the Stanford HARDI dataset (150
directions, single b-value of 2000 $s/mm^2$) that can be automatically
downloaded. If you have not yet downloaded this data-set in one of the other
examples, you will need to be connected to t... |
Friz-zy/captainhook | captainhook/checkers/frosted_checker.py | Python | bsd-3-clause | 629 | 0 | # # # # # # # # # # # # # #
# CAPTAINHOOK IDENTIFIER #
# # # # # # # # # # # # # #
from .utils import bash, filter_python_files |
DEFAULT = 'off'
CHECK_NAME = 'frosted'
NO_FROSTED_MSG = (
"frosted is required for the frosted plugin.\n"
"`pip install frosted` or turn it off in your tox.ini file.")
REQUIRED_FILES = ['tox.ini']
def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NO... | .join(py_files))
return bash(cmd).value()
|
willrowe/sublime-sass-compile | SassCompile.py | Python | mit | 13,518 | 0.026631 | import sublime
import sublime_plugin
import json
import os
import traceback
from threading import Thread
from subprocess import PIPE, Popen
dirtyFiles = []
pluginSettings = None
pluginProjectSettings = None
basicPluginProjectSettings = None
defaultPluginProjectSettings = None
pluginPath = None
userPath = None
upgradeC... | irname(getPluginPath()), "User"])
if appendPath:
return os.sep.join([userPath, appendPath])
return userPath
def logError(errorMessage):
# outputPanel = sublime.active_window().create_output_panel("sasscompile")
# outputPanelEdit = outputPanel.begin_edit()
# outputPanel.in | sert(outputPanelEdit, outputPanel.size(), "SassCompile Encountered an Error:\n")
print("Sass Compile Encountered an Error:")
# outputPanel.insert(outputPanelEdit, outputPanel.size(), err + "\n")
# outputPanel.end_edit(outputPanelEdit)
print(errorMessage)
# outputPanel.
# sublime.active_window().run_command("show_... |
gabrielf10/Soles-pythonanywhere | productos/admin.py | Python | bsd-3-clause | 378 | 0.013228 | from productos.models import Categoria, Imagen
from django.contrib import admin
from imagekit.a | dmin import AdminThumbnail
# Register your models here.
class ImagenAdmin(admin.ModelAdmin):
imagen = AdminThumbnail(image_ | field='imagen_miniatura')
list_display = ('nombre', 'categoria','imagen')
admin.site.register(Categoria)
admin.site.register(Imagen,ImagenAdmin)
|
simonprickett/flappypi | flappypigpio.py | Python | mit | 6,232 | 0.046374 | #####
# Filename: flappypigpio.py
# Description: Flappy bird type game in Python for Pimoroni Unicorn Hat
# Uses 2 buttons connected to GPIO 19 (start) and 6 (flap)
# Author: Simon Prickett
#####
from collections import deque
from random import randint
import time
import thread
import unicornhat a... | r, 0, 0)
UH.show()
time.sleep(1)
GPIO.remove_event_detect(19)
#####
# Game ended, display score and end screen
#####
def gameEnded():
if (score == 0):
# Render a big 0
| screen = [[ 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 1, 0, 0, 0 ],
[ 0, 0, 1, 0, 0, 1, 0, 0 ],
[ 0, 1, 0, 0, 0, 0, 1, 0 ],
[ 0, 1, 0, 0, 0, 0, 1, 0 ],
[ 0, 0, 1, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 1, 1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0 ]
]
for y in range(8):
for x in ran... |
FireBladeNooT/Medusa_1_6 | lib/github/tests/IssueEvent.py | Python | gpl-3.0 | 2,785 | 0.009695 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# ... | #
# ##############################################################################
import Framework
import datetime
class IssueEvent(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.event = self.g.get_user().get_r... |
pv/mediasnake | mediasnake_sendfile/backends/nginx.py | Python | bsd-3-clause | 280 | 0.003571 | from django.http import HttpResponse
from _int | ernalredirect import _convert_file_to_url
def sendfile(request, filename, **kwargs):
response = HttpResponse()
url = _convert_file_to_url(filename)
response['X-Accel-Redirect'] = url.encode('utf-8')
return respon | se
|
kastnerkyle/pylearn2 | pylearn2/datasets/dense_design_matrix.py | Python | bsd-3-clause | 55,686 | 0.000144 | """
The DenseDesignMatrix class and related code. Functionality for representing
data that can be described as a dense matrix (rather than a sparse matrix)
with each row containing an example and each column corresponding to a
different feature. DenseDesignMatrix also supports other "views" of the data,
for example a d... | learning system can make predictions on it, or an unsupervised
learning system can be trained on it.
- 1D ndarray of integers:
This format may be used w | hen the targets are class labels.
In this format, the array should have one entry for each
example. Each entry should be an integer, in the range
[0, N) where N is the number of classes.
This is the format that the `SVM` class expects.
- 2D ndarray, data type opti... |
openstack/heat | heat/tests/common.py | Python | apache-2.0 | 13,978 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | generic_rsrc.Gener | icResource)
resource._register_class('MultiStepResourceType',
generic_rsrc.MultiStepResource)
resource._register_class('ResWithShowAttrType',
generic_rsrc.ResWithShowAttr)
resource._register_class('SignalResourceType',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.