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 |
|---|---|---|---|---|---|---|---|---|
ekivemark/my_device | bbp/bbp/member/models.py | Python | apache-2.0 | 548 | 0.00365 | __author__ = 'mark'
"""
User Profile Extension based on One-to-One fields code in Djan | go Docs here:
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/
"""
from django.db import models
from django.contrib.auth.models import User
from uuid import uuid4
class Member(models.Model):
user = models.OneToOneField(User)
member_guid = models.CharField(max_length=100, null=True, blank=True)
... | = models.CharField(max_length=100, null=True, blank=True)
user_token = models.CharField(max_length=100, null=True, blank=True)
|
DedMemez/ODS-August-2017 | pets/PetBase.py | Python | apache-2.0 | 778 | 0.006427 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.pets.PetBase
from toontown.pets.PetConstants import AnimMoods
from | toontown.pets import PetMood
class PetBase:
def getSetterName(self, valueName, prefix = 'set'):
return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:])
def getAnimMood(self):
if self.mood.getDominantMood() in PetMood.PetMood.ExcitedMoods:
return AnimMoods.EXCITED... | self):
return self.getAnimMood() == AnimMoods.EXCITED
def isSad(self):
return self.getAnimMood() == AnimMoods.SAD |
TheMutley/openpilot | selfdrive/car/honda/interface.py | Python | mit | 23,054 | 0.013794 | #!/usr/bin/env python
import os
import numpy as np
from cereal import car
from common.numpy_fast import clip, interp
from common.realtime import sec_since_boot
from selfdrive.swaglog import cloudlog
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import create_event, EventTypes ... | * min(speedLimiter, accelLimiter)
@staticmethod
def get_params(candidate, fingerprint):
ret = car.CarParams.new_message()
ret.carName = "honda"
ret.carFingerprint = candidate
if candidate in HONDA_BOSCH:
ret.safetyModel = car.CarParams.SafetyModels.hondaBosch
ret.enableCamera = True
... | if x in fingerprint)
ret.enableGasInterceptor = 0x201 in fingerprint
cloudlog.warn("ECU Camera Simulated: %r", ret.enableCamera)
cloudlog.warn("ECU Gas Interceptor: %r", ret.enableGasInterceptor)
ret.enableCruise = not ret.enableGasInterceptor
# kg of standard extra cargo to count for drive, gas... |
TrevorLowing/PyGames | pysollib/games/sanibel.py | Python | gpl-2.0 | 2,437 | 0.007386 | #!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
##---------------------------------------------------------------------------##
##
## Copyright (C) 1998-2003 Markus Franz Xaver Johanne | s Oberhumer
## Copyright (C) 2003 Mt. Hood Playing Card Co.
## Copyright (C) 2005-2009 Skomoroh
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as p | ublished by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later 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... |
coreyabshire/marv | bin/experiments/key_test.py | Python | mit | 472 | 0.002119 | import tty
import sys
import termios
fd = sys.stdin.fileno()
fdattrorig = termios.tcgetattr(fd)
try:
tty.setraw(fd)
done = False
while not done:
ch = sys.stdin.read(1)
sys.stdout.write('test: %s\r\n' % ord(ch))
if | ord(ch) == 27:
ch = sys.stdin.read(1)
sys.stdout.write('esc: %s\r\n' % ord(ch))
if ord(ch) == 3:
done = True
finally:
termios.tcsetattr(fd, te | rmios.TCSADRAIN, fdattrorig)
|
statbio/Sargasso | sargasso/filter/hits_checker.py | Python | mit | 8,017 | 0.000624 | from collections import namedtuple
class HitsChecker:
REJECTED = -1
AMBIGUOUS = -2
CIGAR_GOOD = 0
CIGAR_LESS_GOOD = 1
CIGAR_FAIL = 2
CIGAR_OP_MATCH = 0 # From pysam
CIGAR_OP_REF_INSERTION = 1 # From pysam
CIGAR_OP_REF_DELETION = 2 # From pysam
CIGAR_OP_REF_SKIP = 3 # From pys... | if t.mismatches == min_mismatches]
if len(threshold_data) == 1:
if __debug__:
self.logger.debug('assigne due to primary hit min_mismatches!')
return threshold_data[0].index
min_cigar_check = min([m.cigar_check for m in threshold_data])
threshold_d... | ata) == 1:
if __debug__:
self.logger.debug('assigne due to primart hit CIGAR!')
return threshold_data[0].index
min_multimaps = min([m.multimaps for m in threshold_data])
threshold_data = [t for t in threshold_data
if t.multimaps == min_m... |
GNOME/gnome-session | meson_post_install.py | Python | gpl-2.0 | 789 | 0.007605 | #!/usr/bin/env python3
import os
import shutil
import subprocess
import sys
if os.environ.get('DESTDIR'):
install_root = os.environ.get('DESTDIR') + os.path.abspath(sys.argv[1])
else:
install_root = sys.argv[1]
if not os.environ.get('DESTDIR'):
schemadir = os.path.join(install_root, ' | glib-2.0', 'schemas')
print('Compile gsettings schemas...')
subprocess.call(['glib-compil | e-schemas', schemadir])
# FIXME: Meson is unable to copy a generated target file:
# https://groups.google.com/forum/#!topic/mesonbuild/3iIoYPrN4P0
dst_dir = os.path.join(install_root, 'wayland-sessions')
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
src = os.path.join(install_root, 'xsessions', 'gnome... |
thomaslima/PySpice | PySpice/Tools/File.py | Python | gpl-3.0 | 7,812 | 0.005248 | ####################################################################################################
#
# PySpice - A Spice Package for Python
# Copyright (C) 2014 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published... | ename(self, filename):
return File(filename, self._path)
######################################### | #####
def iter_file(self, followlinks=False):
for root, directories, files in os.walk(self._path, followlinks=followlinks):
for filename in files:
yield File(filename, root)
##############################################
def iter_directories(self, followlinks=False):
... |
yephper/django | django/conf/locale/__init__.py | Python | bsd-3-clause | 12,721 | 0.000161 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
"""
LANG_INFO is a dictionary structure to provide meta information about languages.
About name_local: capitalize it as if your language name was appearing
inside a sentence in your language.
The 'fallback' key can be used to specify a special ... | raeg',
},
'da': {
'bidi': False,
'code': 'da',
'name': 'Danish',
'name_local': 'dansk',
},
'de': {
'bidi': False,
'code': 'de',
'name': 'German',
'name_local': 'Deutsch',
},
'el': {
'bidi': False,
'co... | de': 'en',
'name': 'English',
'name_local': 'English',
},
'en-au': {
'bidi': False,
'code': 'en-au',
'name': 'Australian English',
'name_local': 'Australian English',
},
'en-gb': {
'bidi': False,
'code': 'en-gb',
'name'... |
mcus/SickRage | sickbeard/providers/morethantv.py | Python | gpl-3.0 | 8,361 | 0.00311 | # Author: Seamus Wassman
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 you... | y
# are some mistakes or things I could have done better.
import re
import requests
import traceback
import logging
from sickbeard import tvcache
from sickbeard.providers import generic
from sickbeard.bs4_parser import BS4Parser
from sickrage.helper.exceptions import AuthException
class MoreThanTVProvider(generic.T... | rrentProvider.__init__(self, "MoreThanTV")
self.supportsBacklog = True
self._uid = None
self._hash = None
self.username = None
self.password = None
self.ratio = None
self.minseed = None
self.minleech = None
# self.freeleech = False
self.... |
hakuliu/inf552 | hw3/pca.py | Python | apache-2.0 | 1,541 | 0.008436 | import numpy
def doPCA(data, dim):
data = makeDataMatrix(data)
means = getMeanVector(data)
data = normalizeData(data, means)
cov = getCov(data)
eigvals, eigvecs = getEigs(cov)
principalComponents = sortEigs(eigvals, eigvecs)
return getDimensions(dim, principalComponents)
def getDimensions... | = vals[j]
currentInd = j
if currentInd != -1:
result[i] | = vecs[currentInd]
lastMax = currentMax
return result
def getEigs(cov):
return numpy.linalg.eig(cov)
def getCov(data):
return numpy.cov(data)
def getMeanVector(data):
result = numpy.zeros(len(data))
for i in range(len(data)):
result[i] = numpy.mean(data[i,:])
return resul... |
ohanar/PolyBoRi | pyroot/polybori/partial.py | Python | gpl-2.0 | 1,509 | 0 | from polybori import BooleSet, interpolate_smallest_lex
class PartialFunction(object):
"""docstring for PartialFunction"""
def __init__(self, zeros, ones):
super(PartialFunction, self).__init__()
self.zeros = zeros.set()
self.ones = ones.set()
def interpolate_smallest_lex(self):
... | )
def __mul__(self, other):
zeros = self.zeros.union(other.zeros)
ones = self.ones.intersect(other.ones)
return PartialFunction(zeros, ones)
d | ef __or__(self, other):
zeros = self.zeros.intersect(other.zeros)
ones = self.ones.union(other.ones)
return PartialFunction(zeros, ones)
def __xor__(self, other):
return self + other
def __and__(self, other):
return self * other
|
CarlosPena00/Mobbi | Rasp/nrf/lib_nrf24/example-nrf24-recv.py | Python | mit | 1,196 | 0.020067 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Example program to receive packets from the radio link
#
import virtGPIO as GPIO
from lib_nrf24 import NRF24
import time
pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]
radio2 = NRF24(GPIO, GPIO.SpiDev())
radio2.begin(9, 7)
radio2.setRetries(1... |
pipe | = [0]
while not radio2.available(pipe):
time.sleep(10000/1000000.0)
recv_buffer = []
radio2.read(recv_buffer, radio2.getDynamicPayloadSize())
print ("Received:") ,
print (recv_buffer)
c = c + 1
if (c&1) == 0:
radio2.writeAckPayload(1, akpl_buf, len(akpl_buf))
print ... |
plilja/algolib | util/checksol.py | Python | apache-2.0 | 2,044 | 0.005382 | #!/usr/bin/env python
import sys
import os
import tempfile
import glob
import filecmp
import time
from argparse import ArgumentParser
usage = "usage: %prog [options] program_to_test"
parser = ArgumentParser(description="""Testrunner for programming puzzles, runs a program against each
.in-file and checks the... | r to the folder where the program is located)""")
parser.add_argument("program")
args = parser.parse_args()
program = args.program
if program[0] != '.':
program = "./" + program
f = open(pr | ogram)
program_path = os.path.dirname(program)
if args.directory:
test_search_path = "%s/*.in" % args.directory
else:
test_search_path = "%s/test/*.in" % program_path
success = True
tests_found = False
try:
for test_file in glob.glob(test_search_path):
tests_found = True
start = time.time... |
ylitormatech/terapialaskutus | config/urls.py | Python | bsd-3-clause | 1,837 | 0.003266 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpat... | url(r'^customers/', include("therapyinvoicing.customers.urls", namespace="customers")),
url(r'^customerinvoicing/', include("therapyinvoicing.customerinvoicing.urls", namespace="customerinvoicing")),
url(r'^kelainvoicing/', include("therapyinvoicing.kelainvoicing.urls", namespace="kelainvoicing")),
url(r'... | eporting.urls", namespace="reporting")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', d... |
linuxserver/davos | docs/source/conf.py | Python | mit | 5,191 | 0.000385 | # -*- coding: utf-8 -*-
#
# davos documentation build configuration file, created by
# sphinx-quickstart on Sat Jul 29 08:01:32 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | ument.
master_doc = 'index'
|
# General information about the project.
project = u'davos'
copyright = u'2017, Josh Stark'
author = u'Josh Stark'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
ve... |
JohnGarbutt/taskflow-1 | setup.py | Python | apache-2.0 | 1,467 | 0 | #!/usr/bin/env python
import os
import setuptools
def _clean_line(line):
line = line.strip()
line = line.split("#")[0]
line = line.strip()
return line
def read_requires(base):
path = os.path.join('tools', base)
requires = []
if not os.path.isfile(path):
return requires
with ... | ong_description='The taskflow library provides core functionality that '
'can be used to build [resumable, reliable, '
'easily understandable, ...] highly available '
'systems which process workflows in a structured manner.',
author_email='openstack-dev... | ckages=setuptools.find_packages(),
tests_require=read_requires('test-requires'),
install_requires=read_requires('pip-requires'),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Progra... |
csaldias/python-usm | Ejercicios progra.usm.cl/Parte 2/7- Procesamiento de Texto/vocales_consonantes.py | Python | mit | 466 | 0.032189 | def es_v | ocal(letra):
if letra in 'aeiou':
return True
else:
return False
def contar_vocales_y_consonantes(palabra):
cuenta_vocal = 0
cuenta_consonante = 0
for letra in palabra:
if es_vocal(letra):
cuenta_vocal += 1
else:
cuenta_consonante += 1
return (cuenta_vocal, cuenta_consonante)
palabra = raw_input("... | onantes(palabra)
print "Tiene", vocal, "vocales y", consonante, "consonantes" |
endlessm/chromium-browser | third_party/catapult/telemetry/telemetry/internal/results/artifact_logger.py | Python | bsd-3-clause | 2,300 | 0.004783 | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Logging-like module for creating artifacts.
In order to actually create artifacts, RegisterArtifactImplementation must be
called from somewhere with an a... | isterArtifactImplementation(artifact_implementation):
"""Register the artifact implementation used to log future artifacts.
Args:
artifact_implementation: The artifact implementation to use for future
artifact creations. Must be supported in
artifact_compatibility_wrapper.ArtifactCompatibilityW... | ilityWrapperFactory(
artifact_implementation)
def GetTimestampSuffix():
"""Gets the current time as a human-readable string.
The returned value is suitable to use as a suffix for avoiding artifact name
collision across different tests.
"""
# Format is YYYY-MM-DD-HH-MM-SS-microseconds. The microsecond... |
Dark-Bob/mro | mro/connection.py | Python | mit | 910 | 0.002198 | import atexit
connection = None
connection_function = None
reconnect_function = None
hooks = None
def set_connection_function(_connection_function):
| global connection
global connection_function
connection_function = _connection_function
connection = connection_function()
def disconnect():
| global connection
try:
connection.close()
except:
pass
def set_on_reconnect(_reconnect_function):
global reconnect_function
reconnect_function = _reconnect_function
def set_hooks(_hooks):
global hooks
hooks = _hooks
def reconnect():
global connection
global connec... |
Jortolsa/l10n-spain | l10n_es_aeat_mod349/wizard/export_mod349_to_boe.py | Python | agpl-3.0 | 13,634 | 0.000074 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C)
# 2004-2011: Pexego Sistemas Informáticos. (http://pexego.es)
# 2013: Top Consultant Software Creations S.L.
# (http://www.topconsultant.es/)
# 2014: ... | ativo de la declaración
anterior
136-137 Alfanumérico Período
138-146 Numérico Número total de operadores
intracomunitarios
147-161 Numérico Importe de las operac | iones
intracomunitarias
147-159 Numérico Importe de las operaciones
intracomunitarias (parte entera)
160-161 Numérico Importe de las operaciones
intracomu... |
DanielBaird/CliMAS-Next-Generation | climas-ng/climasng/tests/test_prosemaker_conditions_rangenum.py | Python | mit | 8,241 | 0.005096 | import unittest
import transaction
from pyramid import testing
from climasng.tests import ProseMakerTestCase
from climasng.parsing.prosemaker import ProseMaker
# ===================================================================
class TestProseMakerConditions(ProseMakerTestCase):
# ----------------------------... | '[[0.99 >1> 1]]hiding',
'[[11 >2> 10]]hiding',
'[[1 >0> 1.01]]hiding',
'[[1 >0.1> 1.2]]hiding | ',
]
}
for sample_result, sample_docs in samples.items():
for sample_doc in sample_docs:
self.assertParses(sample_doc, sample_result)
# ======= |
infoscout/weighted-levenshtein | weighted_levenshtein/__init__.py | Python | mit | 20 | 0 | from .clev | import *
| |
AutonomyLab/deep_intent | code/autoencoder_model/scripts/config_nmta.py | Python | bsd-3-clause | 3,079 | 0.003573 | from __future__ import absolute_import
from __future__ import division
from __future__ impor | t print_function
from keras.optimizers import SGD
from keras.optimizers import Adam
from keras.optimi | zers import adadelta
from keras.optimizers import rmsprop
from keras.layers import Layer
from keras import backend as K
K.set_image_dim_ordering('tf')
import socket
import os
# -------------------------------------------------
# Background config:
hostname = socket.gethostname()
if hostname == 'baymax':
path_var =... |
diogocs1/comps | web/addons/l10n_at/account_wizard.py | Python | apache-2.0 | 1,234 | 0.009724 | # -*- encoding: utf-8 -*-
########## | ####################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) conexus.at
#
# This pr | ogram 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.
#
# This program is distributed in the hope that it will be us... |
mtury/scapy | scapy/contrib/isotp.py | Python | gpl-2.0 | 75,260 | 0 | #! /usr/bin/env python
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Nils Weiss <nils@we155.de>
# Copyright (C) Enrico Pozzobon <enricopozzobon@gmail.com>
# Copyright (C) Alexander Schroeder <alexander1.schroeder@st.othr.de>
# This program is published und... | rame]
frame_header = struct.pack("b", (n % 16) + N_PCI_CF)
n += 1
idx += len(frame_data)
if self.exdst:
frame_header = struct.pack('B', self.exdst) + frame_header
pkt = CAN(identifier=self.dst, data=frame_header + frame_data)
pkts... | if len(can_frames) == 0:
raise Scapy_Exception("ISOTP.defragment called with 0 frames")
dst = can_frames[0].identifier
for frame in can_frames:
if frame.identifier != dst:
warning("Not all CAN frames have the same identifier")
parser = ISOTPMessage... |
Rosebotics/pymata-aio | examples/sparkfun_redbot/sparkfun_experiments/Exp6_LineFollowing_IRSensors.py | Python | gpl-3.0 | 2,131 | 0.001877 | """//***********************************************************************
* Exp6_LineFollowing_IRSensors -- RedBot Experiment 6
*
* This code reads the three line following sensors on A3, A6, and A7
* and prints them out to the Serial Monitor. Upload this example to your
* RedBot and open up the Serial Monitor ... | library.redbot import RedBotSensor
WIFLY_IP_ADDRESS = None # Leave set as None if not using WiFly
WIFLY_IP_ADDRESS = "10.0.1.18" # If using a WiFly on the RedBot, set the ip address here.
if WIFLY_IP_ADDRESS:
board = PyMata3(ip_addres | s=WIFLY_IP_ADDRESS)
else:
# Use a USB cable to RedBot or an XBee connection instead of WiFly.
COM_PORT = None # Use None for automatic com port detection, or set if needed i.e. "COM7"
board = PyMata3(com_port=COM_PORT)
LEFT_LINE_FOLLOWER = 3 # pin number assignments for each IR sensor
CENTRE_LINE_FOLLOWER... |
OpenSourceOV/cavicapture | calibrate.py | Python | gpl-3.0 | 3,982 | 0.010296 | from cavicapture import CaviCapture
from process import CaviProcess
import sys, os, getopt
import time, datetime
import numpy as np
import matplotlib.pyplot as plt
def main():
config_path = './config.ini' # default
try:
opts, args = getopt.getopt(sys.argv[1:], "c", ["config="])
except getopt.GetoptError:
... | cess.subtract_images(file | _1, file_2)
# self.cavi_process.write_image(self.output_dir + "/diff.png", diff)
# self.summarise(diff, self.output_dir + "/noise_hist.png")
# Image difference first two and last two
img_group_1_diff = self.cavi_process.subtract_images(file_1, file_2)
self.cavi_process.write_image(self.output_dir +... |
janusnic/21v-python | unit_13/re6.py | Python | mit | 469 | 0.013544 | # -*- coding:utf-8 -*-
import re
# Обработка телефонных номеров
phonePattern = re.compile(r'^(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$')
print phonePattern.search('80055512 | 121234').groups()
# ('800', '555', '1212', '1234')
print phonePattern.search('800.555.1212 x1234').groups()
# ('800', '555', '1212', '1234')
print phonePattern.search('800-555-1212'). | groups()
# ('800', '555', '1212', '')
print phonePattern.search('(800)5551212 x1234') |
tjps/bitcoin | test/functional/mempool_persist.py | Python | mit | 6,912 | 0.002604 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool persistence.
By default, bitcoind will dump mempool on shutdown and
then reload it on sta... | 0].prioritisetransaction(txid=last_txid, fee_delta=1000)
fees = self.nodes[0].getmempoo | lentry(txid=last_txid)['fees']
assert_equal(fees['base'] + Decimal('0.00001000'), fees['modified'])
tx_creation_time = self.nodes[0].getmempoolentry(txid=last_txid)['time']
assert_greater_than_or_equal(tx_creation_time, tx_creation_time_lower)
assert_greater_than_or_equal(tx_creation_ti... |
talapus/Ophidian | Academia/Filesystem/demo_os_walk.py | Python | bsd-3-clause | 483 | 0.00207 | #!/usr/bin/env python3
impo | rt os
print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("file | s prints out all files from root and directories")
print("*" * 20)
'''
for root, dirs, files in os.walk("/var/log"):
print('Root: '.format(root))
print('Dirs: '.format(dirs))
print('Files: '.format(files))
'''
for root, dirs, files in os.walk("/var/log"):
print(root)
print(dirs)
print(files)
|
iw3hxn/LibrERP | purchase_discount_combined/__openerp__.py | Python | agpl-3.0 | 1,361 | 0 | # -*- coding: utf-8 -*-
######################################## | ######################################
#
# Copyright (C) 2020 Didotech S.r.l. (<http://www.d | idotech.com/>).
#
# This program 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.
#
# This program is distributed ... |
mohamedhagag/dvit-odoo | dvit_report_inventory_valuation_multi_uom/wizard/stock_quant_report.py | Python | agpl-3.0 | 6,534 | 0.004132 | # -*- coding: utf-8 -*-
###############################################################################
# License, author and contributors information in: #
# __manifest__.py file at the root folder of this module. #
########################################################... | cation',
'report_type': 'qweb-pdf',
'report_file': 'dvit_report_inventory_valuation_multi_uom.report_stock_inv | entory_location',
'name': 'Stock Inventory',
'flags': {'action_buttons': True},
}
class WizardValuationStockInventoryLine(models.TransientModel):
_name = 'wizard.valuation.stock.inventory.line'
wizard_id = fields.Many2one('wizard.valuation.stock.inventory', required=True, on... |
tarquasso/softroboticfish6 | fish/pi/runMbedProgramWithLogging.py | Python | mit | 1,134 | 0.0097 | import sys
import os
import time
import resetMbed
import serialMonitor
# Program the mbed, restart it, launch a serial monitor to record streaming logs
def runMbedProgramWithLogging(argv):
for arg in argv:
if 'startup=1' in arg:
time.sleep(10)
# If a bin file was given as argument, program ... | *.bin /media/MBED')
#time.sleep(1)
os.system('sudo /home/pi/fish/mbed/programMbed.sh ' + arg)
if 'remount' in arg:
re | mount=int(arg.split('=')[1].strip())==1
# Remount mbed
if remount:
os.system("sudo /home/pi/fish/mbed/remountMbed.sh")
# Start mbed program and serial monitor
print 'Resetting mbed and starting serial monitor'
print ''
resetMbed.reset()
print '============'
serialMonitor.run(argv... |
CEFAP-USP/fastqc-report | RunFastQC.py | Python | gpl-3.0 | 18,788 | 0.002715 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Workflow:
# 1. Check if the folder has been analysed before
# 1.1 Status: checked, converted, reported, compiled, emailed, running, error, completed
# 2. If the sequencer is NextSeq:
# 2.1 Run bcl2fastq to create the FASTQ files
# 2.1.1 Execution:
# nohup /us... | x with the results on 3.1
# 4.1 pdflatex -output-directory [DIR] tex.tex
# 5. Send email with the PDF created on 4.1
# 5.1 sendmail ...
import argparse
import os
import subprocess
import shutil
import csv
import re
from collections import OrderedDict
from bs4 import BeautifulSoup
import datetime
BCL2FASTQ_PATH =... | /FastQC/fastqc'
WORKING_DIR = os.path.dirname(os.path.abspath(__file__))
REPORT_FILE = 'FastQC_report.tex'
REPORTS_PATH = 'FastQC_reports'
STATUS_FILE = 'run_report'
# informações do experimento
SAMPLESHEET = 'SampleSheet.csv'
BCL2FASTQ_REPORT = 'laneBarcode.html'
def getDatetime():
try:
d = datetime.date... |
PRIArobotics/HedgehogProtocol | hedgehog/protocol/messages/ack.py | Python | agpl-3.0 | 1,301 | 0.002306 | from typing import Any, Sequence, Union
from dataclasses import dataclass
from . import RequestMsg, ReplyMsg, Message, SimpleMessage
from hedgehog.protocol.proto import ack_pb2
from hedgehog.utils import protobuf
__all__ = ['Acknowledgement']
# <GSL customizable: module-header>
from hedgehog.protocol.proto.ack_pb2 i... | gement(SimpleMessage):
code: int = OK
message: str = ''
def __post_init__(self):
# <default GSL customizable: Acknowledgement-init-validation>
pass
# </GSL customizable: Acknowledgement-init-validation>
# <d | efault GSL customizable: Acknowledgement-extra-members />
@classmethod
def _parse(cls, msg: ack_pb2.Acknowledgement) -> 'Acknowledgement':
code = msg.code
message = msg.message
return cls(code, message=message)
def _serialize(self, msg: ack_pb2.Acknowledgement) -> None:
msg... |
Exterminus/Redes | Cliente/Cliente_Interface/cliente_gui.py | Python | mit | 18,741 | 0.001122 | # coding: utf-8
import pygame
import sys
from pygame.locals import *
from gui import *
from conexao import *
from jogador import *
from Queue import Queue
from threading import Thread
"""
Cliente
Tp de Redes - Truco
UFSJ
Carlos Magno
Lucas Geraldo
Requisitos:
*python 2.7
*pygame
Modulo Principal.
"""
class Princi... | _jogadas(
i, self.gui.pos_cartas_jog_3)
self.gui.update_card_adversario(
3, self.gui.cont_cartas)
elif cont is 2:
self.gui.renderiza_cartas_jogadas(
i, self.gui.sua_pos... | cartas_jog_1)
self.gui.update_card_adversario(
|
cliffano/swaggy-jenkins | clients/python-experimental/generated/test/test_blue_ocean_api.py | Python | mit | 4,757 | 0 | # coding: utf-8
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import unittest
import openapi_client
from openapi_cl... | ss
def test_get_pipeline_runs(self):
"""Test case for get_pipeline_runs
"""
pass
def test_get_pipelines(self | ):
"""Test case for get_pipelines
"""
pass
def test_get_scm(self):
"""Test case for get_scm
"""
pass
def test_get_scm_organisation_repositories(self):
"""Test case for get_scm_organisation_repositories
"""
pass
def test_get_scm_or... |
google/grumpy | third_party/stdlib/urlparse.py | Python | apache-2.0 | 19,619 | 0.001988 | """Parse (absolute and relative) URLs.
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, Decemb... | ', 'wais', 'imap', 'snews', 'sip', 'sips']
uses_query = ['http', 'wais', 'imap', 'https', 'shttp', 'mms',
'gopher', 'rtsp', 'rtspu', 'sip', 'sips', '']
uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news',
'nntp', 'wais', 'https', 'shttp', 'snews',
'file', 'prosper | o', '']
# Characters valid in scheme names
scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
'+-.')
MAX_CACHE_SIZE = 20
_parse_cache = {}
def clear_cache():
"""Clear the parse cache."""
_parse_cache.clear()
class ResultMi... |
mtils/ems | ems/qt4/gui/mapper/strategies/dict_strategy.py | Python | mit | 857 | 0.016336 | '''
Created on 21.03.2012
@author: michi
'''
from PyQt4.QtGui import QTableView
from ems.qt4.gui.mapper.base import BaseStrategy #@UnresolvedImport
| from ems.xtype.base import DictType, ObjectInstanceType #@UnresolvedImport
from ems.qt4.gui.itemdelegate.xtypes.objectinstancetype import ObjectInstanceDelegate #@UnresolvedImport
class DictStrategy(BaseStrategy):
def match(self, param):
if isinstance(param, DictType):
return | True
return False
def getDelegateForItem(self, mapper, type_, parent=None):
return ObjectInstanceDelegate(type_, parent)
def addMapping(self, mapper, widget, columnName, type_):
if isinstance(widget, QTableView):
columnIndex = mapper.model.columnOfName(col... |
Aveias/gestt | main.py | Python | gpl-3.0 | 1,104 | 0.009991 | # -*-coding:UTF-8 -*
import os
import Auth.authentication as auth
import Auth.login as log
import Menu.barreOutils as barre
import Users.Model as U
import Projects.Model as P
#On appelle le module d'identification - Commen | té pour les pahses de test d'autres modules
login = log.Login()
login.fenetre.mainloop()
#auth.Auth.access = True
#auth.Auth.current_user_id = 1
#On lance le programme
while auth.Auth.access == True:
print("programme en cours")
user = U.User(auth.Auth.current_user_id)
print("Bonjour", user.nom, user.preno... | l'attribut fermer de la classe BarreOutils() -> true si appuie sur le bouton deconnexion
print("fermer = ",barreOutils.fermer)
if barreOutils.fermer == True:
auth.Auth.access = False
else:
os.system("pause")
# Test de l'attribut access qui détermine si on entre ou pas dans la boucle whi... |
rakshify/News_Recommender | policy/policy.py | Python | mit | 472 | 0.004237 | """
policy.py
Janbaanz Launde
Apr 1, 2017
"""
class Policy(object):
"""Abstract class for all policies"""
name = 'POLICY'
def __init__(self, contexts):
self.contexts = contexts
def predict_arm(self, contexts=None):
raise NotImplementedError("Yo | u need to override this function in child class.")
def pull_arm(self, arm, reward, contexts=None):
raise NotImplementedError("You need to override t | his function in child class.")
|
JesseLivezey/Diffusion-Probabilistic-Models | extensions.py | Python | mit | 7,673 | 0.006907 | """
Extensions called during training to generate samples and diagnostic plots and printouts.
"""
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import theano.tensor as T
import theano
from blocks.extensions import SimpleExtension
import viz
import sampler
clas... | grad_f = theano.function(algorithm.inputs, gradients, allow_input_downcast=True)
def do(self, callback_name, *args):
print "plotting gradients"
grad_vals = self.grad_f(self.X)
keynames = sorted(self.blocks_model.params.keys())
for ii in xrange(len(key | names)):
param_name = keynames[ii]
val = grad_vals[ii]
filename_safe_name = '-'.join(param_name.split('/')[2:]).replace(' ', '_')
base_fname_part1 = self.path + '/grads-' + filename_safe_name
base_fname_part2 = '_epoch%04d'%self.main_loop.status['epochs_done']... |
fedhere/SESNCfAlib | vaccaleibundgut.py | Python | mit | 4,704 | 0.00744 | import sys
import os
import glob
import inspect
import pylab as pl
from numpy import *
from scipy import optimize
import pickle
import time
import copy
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates")
if cmd_folder not in sys.path:
sys.path.in... | axiter':5})
else:
pl.plot(x[10:], mycavvaccaleib(x[10:], p0, secondg=False), 'k')
pf = scipy.optimize.minimize(minfunc, p0, args=(y[10:], x[10:], e[10:], 0), method='Powell') # ,options={'maxiter':5})
#pl.figure(4)
pl.figure(0)
ax.errorbar(mjd+0.5-53000, y, yerr=e, fmt=None, ms=7,
... | label = "SN 19"+sys.argv[1].split('/')[-1].\
replace('.dat', '').replace('.', ' '))
# mycavvaccaleib(x,pf.x, secondg=True)
mycavvaccaleib(x, pf.x, secondg=secondg)
ax.plot(mjd[10:]+0.5-53000, mycavvaccaleib(x[10:], pf.x, secondg=secondg), 'k',
linewidth=2, label="v... |
iulian787/spack | var/spack/repos/builtin/packages/openipmi/package.py | Python | lgpl-2.1 | 1,087 | 0.00368 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Openipmi(AutotoolsPackage):
"""The Open IPMI project aims to develop an open code base
... | /files/OpenIPMI%202.0%20Library/OpenIPMI-2.0.29.tar.gz"
version('2.0.28', sha256='8e8b1de2a9a041b419133ecb21f956e999841cf2e759e973eeba9a36f8b40996')
version('2.0.27', sha256='f3b1fafaaec2e2bac32fec5a86941ad8b8cb64543470bd6d819d7b166713d20b')
depends_on('popt')
depends_on('python')
depends_on('term... | args
def install(self, spec, prefix):
make('install', parallel=False)
|
tensorflow/agents | tf_agents/bandits/policies/boltzmann_reward_prediction_policy.py | Python | apache-2.0 | 13,821 | 0.004197 | # coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | ts per-arm
features.
constraints: iterable of constraints objects that are instances of
`tf_agents.bandits.agents.NeuralConstraint`.
emit_policy_info: (tuple of strings) what side information we want to get
as part of the policy info. Allowed values can be found in
`policy_ut... | ration. Otherwise, empty.
name: The name of this policy. All variables in this module will fall
under that name. Defaults to the class name.
Raises:
NotImplementedError: If `action_spec` contains more than one
`BoundedTensorSpec` or the `BoundedTensorSpec` is not valid.
"""
poli... |
Forage/Gramps | gramps/plugins/tool/desbrowser.py | Python | gpl-2.0 | 5,538 | 0.004514 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... | self.mo | del.set(item_id, 1, person_handle)
prev_id = None
for family_handle in person.get_family_handle_list():
family = self.db.get_family_from_handle(family_handle)
for child_ref in family.get_child_ref_list():
prev_id = self.add_to_tree(item_id, prev_id, child_ref.ref)... |
theno/utlz | utlz/cmd.py | Python | mit | 2,420 | 0 | import subprocess
from utlz import func_has_arg, namedtuple
CmdResult = namedtuple(
typename='CmdResult',
field_names=[
'exitcode',
'stdout', # type: bytes
'stderr', # type: bytes
'cmd',
'input',
],
lazy_vals={
'stdout_str': lambda self: self.stdout.d... | 'stderr_str': lambda self: self.stderr.decode('utf-8'),
}
)
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
'''Run command `cmd`.
It's like that, and that's the way it is.
'''
if type(cmd) == str:
cmd = cmd.split()
process = subprocess.Popen(cmd,
... | stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
communicate_has_timeout = func_has_arg(func=process.communicate,
arg='timeout')
exception = Exception
if communicate_has_timeout:
exception = subprocess.Timeo... |
radish-bdd/radish | tests/unit/test_utils.py | Python | mit | 1,022 | 0 | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import pytest
import radish.utils as utils
@pytest.mark.filterwarnings("ignore")
def test_getting_any_debugger():
"""When asking for a ... | gger it should return one
It shouldn't matter if IPython i | s installed or not,
just give me that debugger.
"""
# when
debugger = utils.get_debugger()
# then
assert callable(debugger.runcall)
def test_utils_should_locate_arbitrary_python_object():
# when
obj = utils.locate_python_object("str")
# then
assert obj == str
def test_conve... |
nathanielvarona/airflow | tests/providers/mongo/sensors/test_mongo.py | Python | apache-2.0 | 1,820 | 0.000549 | #
# 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 use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# ... | an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
import pytest
from airflow.models import Connection
from airflow.models.dag import DAG
from airflow.... |
JElchison/Numberjack | Numberjack/__init__.py | Python | lgpl-2.1 | 148,044 | 0.002742 | # Copyright 2009 - 2014 Insight Centre for Data Analytics, UCC
UNSAT, SAT, UNKNOWN, LIMITOUT = 0, 1, 2, 3
LUBY, GEOMETRIC = 0, 1
MAXCOST = 100000000
from .solvers import available_solvers
import weakref
import exceptions
import datetime
import types
import sys
#SDG: extend recursive limit for predicate decomposition... | by solver %s and no decomposition is available." % (self.value, self.solver)
class UnsupportedSolverFunction(exceptions.Exception):
"""
Raised if a solver does not support a particular API call.
"""
def __init__(self, solver, func_name, msg=""):
self.solver = so | lver
self.func_name = func_name
self.msg = msg
def __str__(self):
return "ERROR: The solver %s does not support the function '%s'. %s" % (self.solver, self.func_name, self.msg)
class InvalidEncodingException(exceptions.Exception):
"""
Raised if an invalid encoding was specified, f... |
ESSolutions/ESSArch_Core | ESSArch_Core/WorkflowEngine/migrations/0019_processstep_parent_step.py | Python | gpl-3.0 | 1,448 | 0.000691 | """
ESSArch is an open source archiving and digital preservation system
ESSArch
Copyright (C) 2005-2019 ES Solutions AB
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... | lass Migration(migrations.Migration):
dependencies = [
('WorkflowEngin | e', '0018_auto_20160725_2120'),
]
operations = [
migrations.AddField(
model_name='processstep',
name='parent_step',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='child_steps', to='WorkflowEngine.ProcessStep'),
)... |
BoyuanYan/CIFAR-10 | cs231n/gradient_check.py | Python | apache-2.0 | 1,636 | 0.006541 | import numpy as np
from random import randrange
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
'''
计算在x点,f的数值梯度的简单实现。
-f: 应该是一个只接受一个输入参数的函数
-x: 要评估梯度的点,是numpy的数组
'''
fx = f(x) # 获取源点函数值
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite']... | l
grad[ix] = (fxph - fxmh) / (2 * h)
if verbose:
print(ix, grad[ix])
it.iternext()
return grad
def grad_check_sparse(f, x, analytic_grad, num_checks=10, h=1e-5):
'''
抽取x中的一些随机元素,计算在这些维度上的梯度值,跟analytic_grad的值做对比。
'''
for i in range(num_checks):
ix = tup... |
fxmh = f(x) # 计算f(x-h)
x[ix] = oldval # 重置
grad_numerical = (fxph - fxmh) / (2 * h)
grad_analytic = analytic_grad[ix]
rel_error = abs(grad_numerical - grad_analytic) / (abs(grad_numerical) + abs(grad_analytic))
print('数值计算求梯度:%f 分析法求梯度:%f,相对误差是:%e' % (grad_numerical, gr... |
acs-test/openfda | PER_2017-18/clientServer/P1/server_web.py | Python | apache-2.0 | 1,505 | 0.008638 | # A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTT... | aders += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length: %i" % len(str.encode(web_contents))
clientsocket.send(str.encode(web_headers + "\n\n" + web_contents))
clientsocket.close()
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
... | the socket to a public host, and a well-known port
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# Let's use better the local interface name
hostname = "10.10.104.17"
try:
serversocket.bind((ip, PORT))
# become a server socket
# MAX_OPEN_REQUESTS connect requests before refusing outs... |
kakaba2009/MachineLearning | python/src/algorithm/coding/basic/comprehension.py | Python | apache-2.0 | 240 | 0.0125 | if __na | me__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
L = [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1)]
L = list(filter(lambda x : sum(x) != n, L))
print(L | )
|
mastizada/kuma | vendor/packages/ipython/IPython/Extensions/__init__.py | Python | mpl-2.0 | 429 | 0 | # -*- coding: utf-8 -*-
"""This directory is meant for special-pu | rpose extensions to IPython.
This can include things which alter the syntax processing stage (see
PhysicalQ_Input for an example of how to do this).
Any file located here can be called with an 'execfile =' option as
execfile = Extensions/filename.py
since the IPython directory itself is already part of the search... | isted as 'execfile ='.
"""
|
Tehsmash/inspector-hooks | inspector_hooks/enroll_node_not_found.py | Python | apache-2.0 | 1,013 | 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 Licens | e at
#
# http://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 gove... | mport utils
def hook(introspection_data, **kwargs):
ironic = utils.get_client()
try:
node = ironic.node.create(**{'driver': 'fake'})
except exceptions.HttpError as exc:
raise utils.Error(_("Can not create node in ironic for unknown"
"node: %s") % exc)
return... |
CSC-IT-Center-for-Science/pouta-blueprints | pebbles/drivers/provisioning/openstack_driver.py | Python | mit | 6,069 | 0.002636 | """ ToDo: document OpenStack driver on user level here.
"""
import json
from pebbles.services.openstack_service import OpenStackService
from pebbles.drivers.provisioning import base_driver
from pebbles.client import PBClient
from pebbles.models import Instance
from pebbles.utils import parse_ports_string
SLEEP_BETWEE... | ]
}
| log_uploader.info("Publishing server data\n")
pbclient.do_instance_patch(
instance_id,
{'instance_data': json.dumps(instance_data), 'public_ip': ip})
log_uploader.info("Provisioning complete\n")
def do_deprovision(self, token, instance_id):
log_uploader = self.create... |
pcmagic/stokes_flow | ecoli_in_pipe/wrapper_head_tail.py | Python | mit | 1,450 | 0.001379 | import sys
import petsc4py
petsc4py.init(sys.argv)
from ecoli_in_pipe import head_tail
# import numpy as np
# from scipy.interpolate import interp1d
# from petsc4py import PETSc
# from ecoli_in_pipe import single_ecoli, ecoliInPipe, head_tail, ecoli_U
# from codeStore import ecoli_common
#
#
# def call_head_tial(uz_f... | _tail_U[5] = C1 / (wz_factor * C2 - 1)
# t_head_U[5] = wz_factor * t_head_U[5]
# t_kwargs = {'head_U': t_head_U,
# 'tail_U': t_tail_U, }
# total_force = head_tail.main_fun()
# return total_force
#
#
# OptDB = PETSc.Options()
# fileHandle = OptDB.getString('f', 'ecoliInPipe')
# OptDB.setV... | ecoli_common.ecoli_restart(**main_kwargs)
# head_U = np.array([0, 0, 1, 0, 0, 1])
# tail_U = np.array([0, 0, 1, 0, 0, 1])
# call_head_tial()
head_tail.main_fun()
|
DanBuchan/cache_server | blast_cache/wsgi.py | Python | gpl-2.0 | 400 | 0 | """
WSGI config for cache_server project.
It exposes the WSGI callable as a | module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.ws | gi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blast_cache.settings")
application = get_wsgi_application()
|
COMU/lazimlik | lazimlik/social_app/views.py | Python | gpl-2.0 | 568 | 0.019366 | from django.contrib.auth import logout as auth_logout
from django.c | ontrib.auth.decorators import login_required
from django.http import *
from django.template import Template, Context
from django.shortcuts import render_to_response, redirect, render, RequestContext, HttpResponseRedirect
def login(request):
return render(request, 'login.html')
@login_required
def home(request):
... | logout(request)
return redirect('/') |
tensorflow/tfjs-examples | visualize-convnet/get_vgg16.py | Python | apache-2.0 | 172 | 0 | from tensorflow.keras.applications.vgg16 import VGG16
import tensorflowjs as tfjs
model = VGG16(weights='imagenet')
tfjs.converters.save_ker | as_model(model, | 'vgg16_tfjs')
|
jjgomera/pychemqt | lib/EoS/Cubic/SRK.py | Python | gpl-3.0 | 13,006 | 0.000385 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
r"""Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
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 Softwa... | ai
self.bi = bi
self.mi = mi
def _lib(self, cmp):
ao = 0.42747*self.R**2*cmp.Tc**2/cmp.Pc # Eq 5
b = 0.08664*self.R*cmp.Tc/cmp.Pc # Eq 6
return ao, b
def _GEOS(self, xi):
am, bm = self._mixture("SRK", xi, ... | return am, bm, delta, epsilon
def _alfa(self, cmp, T):
"""α parameter calculation procedure, separate of general procedure
to let define derived equation where only change this term.
This method use the original alpha formulation for temperatures below
the critical temperature an... |
Trii/NoseGAE | examples/pets/pets.py | Python | bsd-2-clause | 239 | 0 | import webapp2
class Pets(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello Pets!')
app = webapp2.WSGIApplicat | ion([('/', Pets)], debug=True) | |
joergdietrich/astropy | astropy/time/utils.py | Python | bsd-3-clause | 3,571 | 0 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Time utilities.
In particular, routines to do basic arithmetic on numbers represented by two
doubles, using the procedure of Shewchuk, 1997, Discrete & Computational
Geometry 18(3):305-363 -- http://www.cs.berkeley.edu/~jrs/pape... | l2)
if np.any(factor != 1.):
sum12, carry = two_product(sum12, factor)
carry += err12 * factor
sum12, err12 = two_sum(sum12, carry)
i | f np.any(divisor != 1.):
q1 = sum12 / divisor
p1, p2 = two_product(q1, divisor)
d1, d2 = two_sum(sum12, -p1)
d2 += err12
d2 -= p2
q2 = (d1 + d2) / divisor # 3-part float fine here; nothing can be lost
sum12, err12 = two_sum(q1, q2)
# get integer fraction
... |
bokeh/bokeh | bokeh/plotting/glyph_api.py | Python | bsd-3-clause | 25,080 | 0.001994 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | rdinateMapping | None:
return self._coordinates
def __init__(self, parent: Plot | None = None, coordinates: CoordinateMapping | None = None) -> None:
self._parent = parent
self._coordinates = coordinates
@glyph_method(glyphs.AnnularWedg | e)
def annular_wedge(self, **kwargs):
pass
@glyph_method(glyphs.Annulus)
def annulus(self, **kwargs):
"""
Examples:
.. code-block:: python
from bokeh.plotting import figure, output_file, show
plot = figure(width=300, height=300)
plot.annulus(x=[1, 2, 3], y=[1,... |
joodicator/PageBot | page/chess.py | Python | lgpl-3.0 | 2,574 | 0.007382 | # coding=utf8
from __future__ import print_function
import re
import sys
import socket
from untwisted.mode import Mode
from untwisted.network import Work
from untwisted.event import DATA, BUFFER, FOUND, CLOSE, RECV_ERR
from untwisted.utils import std
from untwisted.utils.common import append, shrug
from untwisted.ma... | und(work, line):
match = re.match | (r'(#\S+) (.*)', line.strip())
if not match: return
ab_mode.send_msg(match.group(1), match.group(2))
@ch_link(CLOSE)
@ch_link(RECV_ERR)
def ch_close_recv_error(work, *args):
kill_work(work)
yield runtime.sleep(RECONNECT_DELAY_SECONDS)
init_work(work.address)
|
SimplyAutomationized/python-snap7 | snap7/six.py | Python | mit | 26,731 | 0.001459 | """Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2014 Benjamin Peterson
#
# 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 with... | "StringIO", "io"),
MovedAttribute("UserDic | t", "UserDict", "collections"),
MovedAttribute("UserList", "UserList", "collections"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedAttribute("zip... |
darinmcgill/forker | tests/TestRequest.py | Python | gpl-3.0 | 3,544 | 0.000282 | #!/usr/bin/env python
from __future__ import print_function
import unittest
from forker import Request
import socket
import os
import sys
import re
_example_request = b"""GET /README.md?xyz HTTP/1.1
Host: localhost:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:... | )
self.assertTrue(re.match(b"HTTP/1.. 201", out))
self.assertTrue(b"QUERY_STRING=abc" in out)
def test_wsgi1(self):
client, server = socket.socketpair()
client.send(_example_request)
request = Request(sock=server)
client.close()
server.close()
out = r... | elf.assertTrue(out.startswith(b'HTTP/1.0 200 OK'))
def test_wsgi2(self):
client, server = socket.socketpair()
client.send(_example_request)
request = Request(sock=server)
client.close()
server.close()
out = request.wsgi(AppClass)
self.assertTrue(isinstance(ou... |
rxncon/rxncon | rxncon/simulation/boolean/boolean_model.py | Python | lgpl-3.0 | 35,991 | 0.005057 | from abc import ABCMeta
from copy import deepcopy
from enum import Enum
from itertools import product
from typing import List, Dict, Tuple, Optional
from rxncon.core.reaction import Reaction, OutputReaction
from rxncon.core.rxncon_system import RxnConSystem
from rxncon.core.spec import Spec
from rxncon.core.state impo... | eepcopy(self.current_state)
se | lf.step()
if prev == self.current_state:
assert isinstance(prev, BooleanModelState)
return prev
iters += 1
raise AssertionError('Could not find steady state.')
def _validate_update_rules(self) -> None:
"""Assert that all targets appearing on... |
jeffreyliu3230/scrapi | scrapi/harvesters/plos.py | Python | apache-2.0 | 3,868 | 0.002068 | """PLoS-API-harvester
=================
<p>To run "harvester.py" please follow the instructions:</p>
<ol>
<li>Create an account on <a href=" | http://register.plos.org/ambra-registration/register.action">PLOS API</a></li>
<li>Sign in <a href="http://alm. | plos.org/">here</a> and click on your account name. Retrieve your API key.</li>
<li>Create a new file in the folder named "settings.py". In the file, put<br>
<code>API_KEY = (your API key)</code></li>
</ol>
Sample API query: http://api.plos.org/search?q=publication_date:[2015-01-30T00:00:00Z%20TO%202015-02-02T00:00:... |
DraXus/andaluciapeople | oauth_access/views.py | Python | agpl-3.0 | 1,715 | 0.004665 | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from oauth_access.access import OAuthAccess
from oauth_access.exceptions import MissingToken
def oauth_login(request, service,
redirect_field_name="next", redirect_to_sessio... | :
request.session[redirect_to_session_key] = request.GET.get(redirect_field_name)
return HttpResponseRedirect(access.authorization_url(token))
def oauth_callback(request | , service):
ctx = RequestContext(request)
access = OAuthAccess(service)
unauth_token = request.session.get("%s_unauth_token" % service, None)
try:
#print "oauth_callback unauth_token = %s" % unauth_token
#print "oauth_callback request.GET = %s" % request.GET
auth_token = access.c... |
nacl-webkit/chrome_deps | tools/telemetry/telemetry/temporary_http_server.py | Python | bsd-3-clause | 1,660 | 0.010843 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import socket
import subprocess
import sys
import urlparse
from telemetry import util
class TemporaryHTTPServer(object):
def __init__(self, ... | er(
util.PortPair(self._host_port,
browser_backend.GetRemotePort(self._host_port)))
def IsServerUp():
return not socket.socket().connect_ex(('localhos | t', self._host_port))
util.WaitFor(IsServerUp, 5)
@property
def path(self):
return self._path
def __enter__(self):
return self
def __exit__(self, *args):
self.Close()
def __del__(self):
self.Close()
def Close(self):
if self._forwarder:
self._forwarder.Close()
self._f... |
ctoher/pymatgen | pymatgen/util/io_utils.py | Python | mit | 2,727 | 0.000367 | # coding: utf-8
from __future__ import unicode_literals
"""
This module provides utility classes for io operations.
"""
__author__ = "Shyue Ping Ong, Rickard Armiento, Anubhav Jain, G Matteo, Ioannis Petousis"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Shyue Ping On... | n],[regex,test,run],...]
'results' is a an object that your search program will have access to for
storing results.
Here regex is either as a Regex object, or a string that we compile into a
Regex. test and run are callable objects.
This function goes through each line in filename, and if regex ma... | tch is the match object from running
Regex.match.
The default results is an empty dictionary. Passing a results object let
you interact with it in run() and test(). Hence, in many occasions it is
thus clever to use results=self.
Author: Rickard Armiento, Ioannis Petousis
Returns:
resu... |
naomi-/exploration | Enemy.py | Python | mit | 1,023 | 0 | import pygame
from pygame.locals import *
import constants as c
class Enemy:
def __init__(self, x, y, health, movement_pattern, direction, img):
self.x = x
self.y = y
self.health = health
self.movement_pattern = movement_pattern
self.direction = direction
... | do updates based on movement_pattern
if self.movement_pattern == "vertical":
if self.direction == "up":
self.y -= | 2
elif self.direction == "down":
self.y += 2
else:
self.y = self.y
if self.y > avatar.y + 30:
self.direction = "up"
elif self.y < avatar.y - 30:
self.direction = "down"
else:
... |
Smarsh/django | tests/regressiontests/forms/localflavor/cz.py | Python | bsd-3-clause | 4,319 | 0.001158 | # -*- coding: utf-8 -*-
# Tests for the contrib/localflavor/ CZ Form Fields
tests = r"""
# CZPostalCodeField #########################################################
>>> from django.contrib.localflavor.cz.forms import CZPostalCodeField
>>> f = CZPostalCodeField()
>>> f.clean('84545x')
Traceback (most recent call las... | XXXXXXXXX.']
>>> f.clean('12345612 | ')
Traceback (most recent call last):
...
ValidationError: [u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.']
>>> f.clean('12345612345')
Traceback (most recent call last):
...
ValidationError: [u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.']
>>> f.clean('881523/0000', 'm')
Traceback (m... |
giuserpe/leeno | src/Ultimus.oxt/python/pythonpath/LeenoUtils.py | Python | lgpl-2.1 | 7,316 | 0.002873 | '''
Often used utility functions
Copyright 2020 by Massimo Del Fedele
'''
import sys
import uno
from com.sun.star.beans import PropertyValue
from datetime import date
import calendar
import PyPDF2
'''
ALCUNE COSE UTILI
La finestra che contiene il documento (o componente) corrente:
desktop.CurrentFrame.Container... | ontext().ServiceManager
def createUnoService(serv):
'''
create an UNO service
'''
return getComponentContext().getServiceManager().crea | teInstance(serv)
def MRI(target):
ctx = getComponentContext()
mri = ctx.ServiceManager.createInstanceWithContext("mytools.Mri", ctx)
mri.inspect(target)
def isLeenoDocument():
'''
check if current document is a LeenO document
'''
try:
return getDocument().getSheets().hasByName('S2... |
TrimBiggs/calico | calico/test/test_calcollections.py | Python | apache-2.0 | 5,048 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Metaswitch Networks
#
# 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 applicab... | iscard("k", "v")
self.assertFalse(self.index.contains("k", "v"))
self.assertEqual(self.index._index, {})
def test_empty(self):
self.assertFalse(bool(self.index))
self.assertEqual(self.index.num_items("k"), 0)
self.assertEqual(list(self.index.iter_values("k")), [])
def t... | self.assertEqual(self.index.num_items("k"), 1)
self.index.add("k", "v")
self.assertEqual(self.index.num_items("k"), 1)
self.index.add("k", "v2")
self.assertEqual(self.index.num_items("k"), 2)
self.index.add("k", "v3")
self.assertEqual(self.index.num_items("k"), 3)
... |
fabioz/PyDev.Debugger | tests_python/resources/_pydev_coverage_cyrillic_encoding_py3.py | Python | epl-1.0 | 135 | 0.014815 | # -*- | coding: iso-8859-5 -*-
# Ʋ³´µ¶
class DummyƲ³´µ¶(object):
def Print(self):
print ('Ʋ³´µ¶')
Dummy | Ʋ³´µ¶().Print()
|
sql-machine-learning/sqlflow | python/runtime/dbapi/pyalisa/task.py | Python | apache-2.0 | 3,699 | 0 | # Copyright 2020 The SQLFlow Authors. 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 required by applicable law o... | nts
resultful: has result
output: like sys.stdout
"""
task_id, status = self.cli.create_sql_task(code)
return self._tracking(task_id, status, output, resultful)
def exec_pyodps(self, code, args, output=sys.stdout):
| """submit the python code to alisa server, write the logs to output
Args:
code: python code
args: args for python code
output: such as sys.stdout
"""
task_id, status = self.cli.create_pyodps_task(code, args)
return self._tracking(task_id, status, out... |
google/pymql | test/type_link_test.py | Python | apache-2.0 | 36,235 | 0.001711 | #!/usr/bin/python2.6
# Copyright 2020 Google LLC
#
# 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 a... | ons under the License.
# -*- coding: utf-8 -*-
#
"""type link."""
__author__ = 'bneutra@google.com (Brendan Neutra)'
# thanks warren for these dimetests
import google3
from pymql.mql import error
from pymql.test import mql_fixture
class MQLTest(mql_fixture.MQLTest):
"""type link tests."""
def setUp(self):
... | lf.env = {'as_of_time': '2010-05-01'}
def testLinkMasterProperty(self):
"""link:null (master_property) of obj property."""
query = """
{
"/people/person/place_of_birth": {
"link": null,
"id": null
},
"id": "/en/bob_dylan"
}
"""
exp_response = """
{
... |
zeyuanxy/leet-code | vol4/number-of-islands/number-of-islands.py | Python | mit | 851 | 0.00235 | class Solution(object):
def search(self, grid, x, y, s):
if grid[x][y] == '0' or (x, y) in s:
return s
s.add((x, y))
if x - 1 >= 0:
s = self.search(grid, x - 1, y, s)
if x + 1 < len(grid):
s = self.search(grid, x + 1, y, s)
if y - 1 >= 0:
... | s = self.search(grid, x, y - 1, s)
if y + 1 < len(grid[0]):
s = self.search(grid, x, y + 1, s)
return s
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
" | ""
ans = 0
s = set()
for x in range(len(grid)):
for y in range(len(grid[0])):
if grid[x][y] == '1' and (x, y) not in s:
ans += 1
s = self.search(grid, x, y, s)
return ans |
bobpoekert/tornado-threadpool | tests.py | Python | mit | 2,117 | 0.001417 | import thread_pool
from tornado.testing import AsyncTestCase
from unittest import TestCase
import time, socket
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from functools import partial
class ThreadPoolTestCase(AsyncTestCase):
def tearDown(self):
thread_pool.thread_pool = thread... | ().stop()
def test_blocking_war | n(self):
self._fired_warning = False
thread_pool.blocking_warning = self.warning_fired
self.blocking_method()
self.assertTrue(self._fired_warning)
@thread_pool.blocking
def blocking_method(self):
time.sleep(0.1)
def warning_fired(self, fn):
self._fired_warni... |
Jian-Zhan/customarrayformatter | openpyxl/workbook.py | Python | mit | 8,298 | 0.000603 | # file openpyxl/workbook.py
# Copyright (c) 2010-2011 openpyxl
#
# 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, ... | range to the list of named_ranges."""
self._named_ranges.append(named_range)
def get_named_range(self, name):
"""Return the range specified by name."""
requested_range = None
for named_range in self._named_ranges:
if named_range.name == name:
requested_ra... | return requested_range
def remove_named_range(self, named_range):
"""Remove a named_range from this workbook."""
self._named_ranges.remove(named_range)
def save(self, filename):
"""Save the current workbook under the given `filename`.
Use this function instead of using an `... |
mambocab/cassandra | pylib/cqlshlib/cql3handling.py | Python | apache-2.0 | 55,793 | 0.001667 | # 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... | ld', 'enabled', 'unchecked_tombstone_compaction', 'only_purge_repaired_tombstones')),
('compression', 'compression_parameters',
('sstable_compression', 'chunk_length_kb', 'crc_check_chance')),
('caching', None,
('rows_per_p | artition', 'keys')),
)
obsolete_cf_options = ()
consistency_levels = (
'ANY',
'ONE',
'TWO',
'THREE',
'QUORUM',
'ALL',
'LOCAL_QUORUM',
'EACH_QUORUM',
'SERIAL'
)
size_tiered_compaction_strategy_options = (
'min_sstable_... |
manjitkumar/drf-url-filters | example_app/serializers.py | Python | mit | 525 | 0 |
# django-drf imports
from rest_framework import serializers
# app level imports
from .models import Player, Team
class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = (
'id', 'name', 'rating', 'teams',
'install_ts', 'update_ts'
)... | s Meta:
model = Team
fields = (
'id', 'name', 'rating', 'players',
'i | nstall_ts', 'update_ts'
)
|
openqt/algorithms | leetcode/python/ac/lc003-longest-substring-without-repeating-characters.py | Python | gpl-3.0 | 1,545 | 0.000647 | # coding=utf-8
import unittest
"""3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
Given a string, find the length of the **longest substring** without repeating
characters.
**Examples:**
Given `"abcabcbb"`, the answer is `"a... | ongestSubstring("bbbbb"), 1)
self.assertEqual(self.lengthOfLongestSubstring("pwwkew"), 3)
self.assertEqual(s | elf.lengthOfLongestSubstring("c"), 1)
if __name__ == "__main__":
unittest.main()
|
blake-sheridan/py | test/test_grammar.py | Python | apache-2.0 | 200 | 0.005 | import unittest
from b.grammar import Parser
| class ParserTests(unittest.TestCase):
def test_parse(self):
p = Parser()
p.parse('123 "thing | s"')
raise NotImplementedError
|
qmagico/gae-migrations | tests/my/migrations_pau_na_migration/migration_paunamigration_0001.py | Python | mit | 414 | 0.007246 | from my.models import QueD | oidura
# Opcional. Retorn | a quantas migracoes devem ser rodadas por task (default = 1000)
MIGRATIONS_PER_TASK = 2
# Descricao amigavel dessa alteracao no banco
DESCRIPTION = 'multiplica por 2'
def get_query():
""" Retorna um objeto query das coisas que precisam ser migradas """
return QueDoidura.query()
def migrate_one(entity):
e... |
ianastewart/cwltc-admin | pos/services.py | Python | mit | 8,750 | 0.002058 | import datetime
import logging
from decimal import Decimal
from django.db import transaction
from django.http import HttpResponse
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
from .models import Transaction, LineItem, Layout, PosPayment, Item, Location, TWO... | total, people, attended, creation_date=None
):
"""
Create Transaction, LineItem and PosPayment records in the database
Return a description of it
"""
try:
complimentary = False
count = len(people)
dec_total = (Decimal(total) / 100).quantize(TWO_PLACES)
item_type = Lay... | complimentary = True
person_id = None
else:
person_id = None
trans = Transaction(
creation_date=creation_date,
creator_id=creator_id,
person_id=person_id,
terminal=terminal,
item_type=item_type,
total=d... |
7kbird/chrome | net/PRESUBMIT.py | Python | bsd-3-clause | 1,034 | 0.005803 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Chromium presubmit script for src/net.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit ... | swarming': set(['defaulttests']),
},
'tryserver.chromium.win': {
'win_chromium_rel_swarming': set(['defaulttests']),
}
}
# Changes that touch NSS files will likely need a corresponding OpenSSL edit.
# Conveniently, this one glob also matches _openssl.* changes too.
if any('nss' in f.LocalPath(... | 'linux_redux', set()).add('defaulttests')
return masters
|
jepio/JKalFilter | docs/conf.py | Python | gpl-2.0 | 8,011 | 0.00699 | # -*- coding: utf-8 -*-
#
# JKal-Filter documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 24 16:56:49 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration val | ues are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to... | os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add ... |
caesar2164/edx-platform | lms/djangoapps/shoppingcart/models.py | Python | agpl-3.0 | 91,861 | 0.003103 | # pylint: disable=arguments-differ
""" Models for the shopping cart and assorted purchase types """
from collections import namedtuple
from datetime import datetime
from datetime import timedelta
from decimal import Decimal
import json
import analytics
from io import BytesIO
from django.db.models import Q, F
import py... | ient_name = models.CharField(max_length=255, null=True, blank=True)
recipient_email = models.CharField(max_length=255, null=True, blank=True)
customer_reference_number = models.CharField(max_length=63, null=True, blank=True)
order_type = models.CharField(max_length=32, default='personal', choices=OrderTypes... | Always use this to preserve the property that at most 1 order per user has status = 'cart'
"""
# find the newest element in the db
try:
cart_order = cls.objects.filter(user=user, status='cart').order_by('-id')[:1].get()
except ObjectDoesNotExist:
# if nothing ... |
sparkslabs/kamaelia | Sketches/RJL/bittorrent/BitTorrent/bittorrent-console.py | Python | apache-2.0 | 7,540 | 0.00809 | #!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... | from cStringIO | import StringIO
from Axon.ThreadedComponent import threadedcomponent
from Axon.Component import component
from BitTorrent.download import Feedback, Multitorrent
from BitTorrent.defaultargs import get_defaults
from BitTorrent.parseargs import printHelp
from BitTorrent.zurllib import urlopen
from BitTorrent.bencode imp... |
tinenbruno/ml-buff | tests/helpers/feature_value_helper_test.py | Python | mit | 2,534 | 0.007103 | from ml_buff.database import session_scope
from ml_buff.models import feature, feature_value, input_data, base_feature_record
from ml_buff.helpers.feature_value_helper import FeatureValueHelper
class TestFeature1(base_feature_record.BaseFeatureRecord):
def calculate(self, input_data):
return [1]
class Tes... | 2, 3]
FeatureValueHelper.createAll(input_data_list)
for test_input_datum in test_inp | ut_data:
value1 = TestFeature1().getValue(test_input_datum)
value2 = TestFeature2().getValue(test_input_datum)
assert value1.value == [1]
assert value2.value == [2]
def test_forceUpdateForInput():
test_input_data = (input_data.InputData(1, 'createAll'), input_data.InputData... |
tktrungna/leetcode | Python/shortest-distance-from-all-buildings.py | Python | mit | 2,335 | 0.0197 | """
QUESTION:
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You are
given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land w | hich you can | pass by freely.
Each 1 marks a building which you cannot pass through.
Each 2 marks an obstacle which you cannot pass through.
The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2)... |
bjolivot/ansible | lib/ansible/module_utils/sros.py | Python | gpl-3.0 | 4,609 | 0.004339 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | (['show system rollback'])
match = re.search(r'^Rollback Location\s+:\s(\S+)', resp[0], re.M)
self._rollback_enabled = match.group(1) != 'None'
return self._rollback_enabled
def load_config_w_rollback(self, | commands):
if self.rollback_enabled:
self.execute(['admin rollback save'])
try:
self.configure(commands)
except NetworkError:
if self.rollback_enabled:
self.execute(['admin rollback revert latest-rb',
'admin rollback delete latest-rb'])
... |
SahSih/ARStreaming360Display | RealTimeVideoStitch/motion_detector.py | Python | mit | 2,815 | 0.019893 | # USAGE
# python motion_detector.py
# python motion_detector.py --video videos/example_01.mp4
# import the necessary packages
import argparse
import datetime
import imutils
import time
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", he... | xt), (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, datetime.da | tetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
# show the frame and record if the user presses a key
cv2.imshow("Security Feed", frame)
cv2.imshow("Thresh", thresh)
cv2.imshow("Frame Delta", frameDelta)
key = cv2.waitKey(1) & 0xFF
# ... |
fluentstream/asterisk-p2p | res/pjproject/tests/pjsua/scripts-call/150_srtp_1_1.py | Python | gpl-2.0 | 340 | 0.023529 | # $Id: | 150_srtp_1_1.py 369517 2012-07-01 17:28:57Z file $
#
from inc_cfg import *
test_param = TestParam(
"Callee=optional SRTP, caller=optional SRTP",
[
InstanceParam("callee", "--null-audio --use-srtp=1 --srtp-secure=0 --max-calls=1"),
InstanceParam("caller", "--null-audio --use-srtp=1 --srtp-secure=0 --max-call... | ")
]
)
|
mrshu/iepy | iepy/webui/corpus/migrations/0005_auto_20140923_1502.py | Python | bsd-3-clause | 412 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('corpus', '0004_auto_20140923_1501'),
]
operations = [
migrations.RenameField(
model_name='labeledrelationevidenc... | me='date',
| new_name='modification_date',
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.