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 |
|---|---|---|---|---|---|---|---|---|
varunmehta/photobooth | photobooth.py | Python | mit | 12,204 | 0.002786 | #!/usr/bin/env python
# created by [email protected]
# modified by varunmehta
# see instructions at http://www.drumminhands.com/2014/06/15/raspberry-pi-photo-booth/
import atexit
import glob
import logging
import math
import os
import subprocess
import sys
import time
import traceback
from time import sleep
impo... | python.
################################# Begin Step 1 #################################
logging.info("Get Ready")
GPIO.output(led_pin, False)
show_image(real_path + "/instructions.png")
sleep(prep_delay)
# clear the screen
clear_screen()
camera = picamera.PiCamera()
camera.vfli... | ent
# camera.saturation = -100 # comment out this line if you want color images
# camera.iso = config.camera_iso
camera.resolution = (high_res_w, high_res_h) # set camera resolution to high res
################################# Begin Step 2 #################################
logging.info("Starti... |
ThomasGerstenberg/serial_monitor | stream/__init__.py | Python | bsd-3-clause | 551 | 0 | from serial_settings import SerialSettings
class AbstractStream(object):
def __init__(self, config, name):
"""
:type name: str
"""
self.confi | g = config
self.name = name
def open(self):
raise NotImplementedError
def close(self):
raise NotImplementedError
def read(self, num_bytes=1):
raise NotImplementedError
def write(self, data):
raise NotImplementedErro | r
def reconfigure(self, config):
raise NotImplementedError
|
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py | Python | apache-2.0 | 4,089 | 0.000734 | #!/usr/bin/env python
"""
Synopsis: %(prog)s [-h|-b|-g|-r|-a|-d] [ picklefile ] dbfile
Read the given picklefile as a series of key/value pairs and write to a new
database. If the database already exists, any contents are deleted. The
optional flags indicate the type of the output database:
-a - open ... | in ("-a", "--anydbm"):
try:
dbopen = anydbm.open
except AttributeError:
sys.stderr.write("anydbm module unavailable.\n")
return 1
elif opt in ("-g", "--gdbm"):
try:
dbopen = gdbm.open
except ... | ilable.\n")
return 1
elif opt in ("-d", "--dbm"):
try:
dbopen = dbm.open
except AttributeError:
sys.stderr.write("dbm module unavailable.\n")
return 1
if dbopen is None:
if bsddb is None:
sy... |
How2Compute/SmartHome | cli/demo2.py | Python | mit | 1,643 | 0.008521 | # Import time (for delay) library (for SmartHome api) and GPIO (for raspberry pi gpio)
from library import SmartHomeApi
import RPi.GPIO as GPIO
import time
from datetime import datetime
# 7 -> LED
# Create the client with pre-existing credentials
api = SmartHomeApi("http://localhost:5000/api/0.1", id=10, api_key="ap... | e preference! | Please set it to the correct value in your dashboard")
else:
bedtime = preference['value']
if not bedtime:
print("Unexpected error occured!")
else:
print(bedtime)
time_str = datetime.now().strftime('%H:%M')
print("time: {}".format(time_str))
... |
shabab12/edx-platform | lms/djangoapps/ccx/tests/test_overrides.py | Python | agpl-3.0 | 7,563 | 0.001587 | # coding=UTF-8
"""
tests for overrides
"""
import datetime
import mock
import pytz
from nose.plugins.attrib import attr
from ccx_keys.locator import CCXLocator
from courseware.courses import get_course_by_id
from courseware.field_overrides import OverrideFieldData
from courseware.testutils import FieldOverrideTestMixi... | E SAVEPOINT pair around the INSERT caused by the
# transaction.atomic down in Django's get_or_create()/_create_object_from_params().
with self.assertNumQueries(6):
override_field_for_ccx(self.ccx, chapter, 'start', ccx_start) |
def test_override_num_queries_update_existing_field(self):
"""
Test that overriding existing field executed create, fetch and update queries.
"""
ccx_start = datetime.datetime(2014, 12, 25, 00, 00, tzinfo=pytz.UTC)
new_ccx_start = datetime.datetime(2015, 12, 25, 00, 00, tzi... |
h0ke/pynt | pynt/pynt.py | Python | mit | 290 | 0 | """
Pynt is a Python client that wraps the Open Beer Database API.
Questions, comments? [email protected]
"""
__author__ = "Matthew Ho | kanson <[email protected]>"
__version__ = "0.2.0"
from beer import Beer
from brewery import Brewery
from | request import Request
from settings import Settings
|
purduesigbots/purdueros-cli | proscli/flasher.py | Python | bsd-3-clause | 8,643 | 0.003934 | import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flashe... | port = p.device
break
if port is None:
click.echo('No additional ports found.')
click.get_current_context().abort()
sys.exit(1)
i | f port == 'all':
port = [p.device for p in prosflasher.ports.list_com_ports()]
if len(port) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
click.get_current_context().abort()
... |
stvstnfrd/edx-platform | common/lib/xmodule/xmodule/modulestore/split_mongo/mongo_connection.py | Python | agpl-3.0 | 23,649 | 0.002241 | """
Segregation of pymongo functions from the data modeling mechanisms for split modulestore.
"""
import datetime
import logging
import math
import re
import zlib
from contextlib import contextmanager
from time import time
import pymongo
import pytz
import six
from six.moves import cPickle as pickle
from contracts i... | locks'] | ):
new_block = dict(block.to_storable())
new_block.setdefault('block_type', block_key.type)
new_block['block_id'] = block_key.id
new_structure['blocks'].append(new_block)
return new_structure
class CourseStructureCache(object):
"""
Wrapper around django... |
kylebegovich/ICIdo | mainsite/temp.py | Python | mit | 138 | 0.007246 | from models import *
donation = Donation()
donor = Donor | ()
donor.first_name = "FirstName"
donor.last_name = "LastName" |
print(donor)
|
Sh1n/AML-ALL-classifier | main.py | Python | gpl-2.0 | 5,647 | 0.015583 | import Orange
import logging
import random
from discretization import *
from FeatureSelector import *
from utils import *
from sklearn import svm
from sklearn import cross_validation
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.feature_extraction import DictVectorizer
import numpy ... |
# Convert Train Dataset
# Apply transformation, from labels to you know what I mean
converted_train_data = ([ | [ d[f].value for f in trainingSet.domain if f != trainingSet.domain.class_var] for d in trainingSet])
converted_train_data = [dict(enumerate(d)) for d in converted_train_data]
vector = DictVectorizer(sparse=False)
converted_train_data = vector.fit_transform(converted_train_data)
converted_train_targets = ([ 0 if d[tra... |
KanoComputing/kano-settings | kano_settings/system/boards/__init__.py | Python | gpl-2.0 | 1,199 | 0 | #
# __init__.py
#
# Copyright (C) 2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Module for board specific settings
#
import importlib
import re
import pkgutil
from kano.logging import logger
from kano.utils.hardware import RPI_1_CPU_PROFILE, get_board_pr | operty, \
get_rpi_model
__author__ = 'Kano Computing Ltd.'
__email__ = '[email protected]'
def get_board_props(board_ | name=None):
if not board_name:
board_name = get_rpi_model()
cpu_profile = get_board_property(board_name, 'cpu_profile')
if not cpu_profile:
cpu_profile = RPI_1_CPU_PROFILE
board_module = re.sub(r'[-/ ]', '_', cpu_profile).lower()
try:
board = importlib.import_module(
... |
ecdavis/spacegame | tests/unit/test_star_system.py | Python | apache-2.0 | 3,976 | 0.002012 | import mock
from pantsmud.driver import hook
from spacegame.core import hook_types
from spacegame.universe.star_system import StarSystem
from spacegame.universe.universe import Universe
from tests.unit.util import UnitTestCase
class StarSystemUnitTestCase(UnitTestCase):
def setUp(self):
UnitTestCase.setUp... | tem.pulse()
self.hook_star_system_reset.assert_called()
def test_pulse_with_reset_timer_below_one_does_not_call_hook_star_system_reset(self):
self.star_system.reset_timer = 0
self.star_system.pulse()
self.hook_star_system_reset.assert_not_called()
def test_pulse_with_reset_time... | ystem.reset_timer = 2
self.star_system.pulse()
self.assertEqual(self.star_system.reset_timer, 1)
def test_pulse_with_reset_timer_at_one_resets_reset_timer(self):
self.star_system.reset_timer = 1
self.star_system.pulse()
self.assertEqual(self.star_system.reset_timer, self.sta... |
Morphux/IRC-Bot | modules/mv/mv.py | Python | gpl-2.0 | 1,360 | 0.001472 | # -*- coding: utf8 -*-
class Mv:
def command(self):
self.config = {
"command": {
"mv": {
"function": self.mvScreams,
"usage": "mv <us | er>",
"help": "Le clavier y colle!"
}
}}
return self.config
def mvScreams(self, Morphux, infos):
print(infos)
if (len(infos['args']) == 0 and infos['nick'] == "valouche"):
Morphux.sendMessage("Ta mere la chauve", infos['nick'])
elif (l... | elif (len(infos['args']) == 0):
Morphux.sendMessage("SARACE BOULBA", infos['nick'])
elif (infos['args'][0] == "allow"):
Morphux.sendMessage("ALLOW?", infos['nick'])
elif (infos['args'][0] == "thunes"):
Morphux.sendMessage("Money equals power", infos['nick'])
... |
jamesr/sky_engine | build/zip.py | Python | bsd-3-clause | 1,167 | 0.011997 | #!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code i | s governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import zipfile
import os
import sys
def _zip_dir(path, zip_file, prefix):
path = path.rstrip('/\\')
for root, dirs, files in os.walk(path):
for file in files:
zip_file.write(os.path.join(root, file), os.path.join... | irs:
if os.path.isdir(path):
_zip_dir(path, zip_file, archive_name)
else:
zip_file.write(path, archive_name)
zip_file.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='This script creates zip files.')
parser.add_argument('-o', dest='output', action='stor... |
Chasego/cod | leetcode/665-Non-decreasing-Array/NonDecreasingArr.py | Python | mit | 567 | 0.001764 | class S | olution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
is_modified = False
for i in xrange(len(nums) - 1):
if nums[i] > nums[i+1]:
if is_modified:
return False
... | if i == 0 or nums[i-1] <= nums[i+1]:
nums[i] = nums[i+1]
else:
nums[i+1] = nums[i]
is_modified = True
return True
|
karpierz/libpcap | setup.py | Python | bsd-3-clause | 39 | 0.051282 | from | setuptools i | mport setup ; setup()
|
DarioGT/docker-carra | src/prototype/actions/graphModel.py | Python | mit | 8,442 | 0.014215 | #!/usr/bin/env python
"""
Prototype to DOT (Graphviz) converter by Dario Gomez
Table format from django-extensions
"""
from protoExt.utils.utilsBase import Enum, getClassName
from protoExt.utils.utilsConvert import slugify2
class GraphModel():
def __init__(self):
self.tblStyle = False
... |
for pDiag in diagramSet:
gDiagram = {
'code': getClassName(pDiag.code) ,
'label': slugify2( pDiag.code ),
'clusterName': slugify2( getattr(pDiag, 'title', pDiag.code)),
'graphLevel' : getattr(pDiag, 'graphLevel' , self.... | EL.all),
'graphForm' : getattr(pDiag, 'graphForm' , self.GRAPH_FORM.orf),
'showPrpType': getattr(pDiag, 'showPrpType' , False),
'showBorder' : getattr(pDiag, 'showBorder' , False),
'showFKey' : getattr(pDiag, 'showFKey' , False),
'prefix... |
andrewhead/Package-Qualifiers | tests/compute/test_compute_code.py | Python | mit | 4,317 | 0.001853 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import unittest
from bs4 import BeautifulSoup
from compute.code import CodeExtractor
logging.basicConfig(level=logging.INFO, format="%(message)s")
class ExtractCodeTest(unittest.TestCase):
def setUp(self):
... | nglish sentence.</code>")
snippets = self.code_extractor.extract(document)
self.assertEqual(len(snippets), 0)
def test_fail_to_detect_command_line(self):
document = self._make_document_with_body("<code>npm install package</code>")
snippets = self.code_extractor.extract(document)
... | s), 0)
def test_skip_whitespace_only(self):
document = self._make_document_with_body("<code>\t \n</code>")
snippets = self.code_extractor.extract(document)
self.assertEqual(len(snippets), 0)
# In practice I don't expect the next two scenarios to come up. But the expected behavior of
... |
Golker/wttd | eventex/core/migrations/0003_contact.py | Python | mit | 822 | 0.00365 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-19 00:28
from __future__ import unicode_literals
from django.db import migrations, mode | ls
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20160218_2359'),
]
operations = [
migrations.CreateMo | del(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('kind', models.CharField(choices=[('E', 'Email'), ('P', 'Phone')], max_length=1)),
('value', models.CharField(max_leng... |
DonaldWhyte/module-dependency | tests/test_tokeniser.py | Python | mit | 6,029 | 0.026373 | import unittest
import sys
import os
sys.path.append(os.environ.get("PROJECT_ROOT_DIRECTORY", "."))
from moduledependency.tokeniser import Token, Tokeniser
class TestToken(unittest.TestCase):
def test_construction(self):#
# Test with invalid token type
with self.assertRaises(ValueError):
Token(... | en.type, "identifier")
self.assertEqual(token.value, "testVariable")
token = Token("from")
self.assert | Equal(token.type, "from")
self.assertEqual(token.value, "from")
class TestTokeniser(unittest.TestCase):
def setUp(self):
self.tokeniser = Tokeniser()
# Create test data
self.noImportSource = """
def testFunction(x):
\"\"\"This is a docstring but I'm not sure
how far it goes.
\"\"\"
... |
kpeiruza/incubator-spot | spot-oa/oa/dns/dns_oa.py | Python | apache-2.0 | 17,663 | 0.018174 |
import logging
import os
import json
import shutil
import sys
import datetime
import csv, math
from tld import get_tld
from collections import OrderedDict
from utils import Util
from components.data.data import Data
from components.iana.iana_transform import IanaTransform
from components.nc.network_context import Net... | self._logger.info("Getting reputation for each service in config")
rep_services_results = []
if self._rep_services | :
for key,value in rep_cols.items():
rep_services_results = [ rep_service.check(None,value) for rep_service in self._rep_services]
rep_results = {}
for result in rep_services_results:
rep_results = {k: "{0}::{1}".for... |
tescalada/npyscreen-restructure | npyscreen/ThemeManagers.py | Python | bsd-2-clause | 4,810 | 0.005821 | # encoding: utf-8
"""
IMPORTANT - COLOUR SUPPORT IS CURRENTLY EXTREMELY EXPERIMENTAL. THE API MAY CHANGE, AND NO DEFAULT
WIDGETS CURRENTLY TAKE ADVANTAGE OF THEME SUPPORT AT ALL.
"""
import curses
from . import global_options
def disable_color():
global_options.DISABLE_ALL_COLORS = True
def enable_color():
... | efault_colors)
def initalize_pair(self, name, fg, bg):
#Initialize a colo | r_pair for the required color and return the number.
#Raise an exception if this is not possible.
if (len(list(self._defined_pairs.keys())) + 1) == self._max_pairs:
raise Exception("Too many colors")
_this_pair_number = len(list(self._defined_pairs.keys())) + 1
curses.init_... |
kevinnguyeneng/django-uwsgi-nginx | app/naf_autoticket/migrations/0024_alertcorrelationweight.py | Python | gpl-3.0 | 1,043 | 0.002876 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models |
class Migration(migrations.Migration):
dependencies = [
('naf_autoticket', '0023_hostdevice_hostlocation'),
]
operations = [
migrations.CreateModel(
name='AlertCorrelationWeight',
fields=[
| ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('AlertCompare', models.CharField(max_length=100)),
('TimeWeight', models.CharField(max_length=50)),
('LocationWeight', models.CharField(max_length=255, null=True)),... |
pierreboudes/pyThymio | garden_real.py | Python | lgpl-3.0 | 1,328 | 0.003765 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pythymio
import random
from gardenworld import *
init('info2_1')
with pythymio.thymio(["acc"],[]) as Thym:
state = dict([])
state["time"] = 0
state["delay"] = 10
def dispatch(evtid, evt_name, evt_args):
# https://www.thymio.org/en:thymioapi pr... | lay"] = 20
dp()
elif evt_args[0] < -10:
state["delay"] = 20
ra()
else: # Wat?
print evt_name
# Now lets start the loopy thing
Thym.loop(dis | patch)
print "state is %s" % state
print "Sayonara"
|
oxfordinternetinstitute/scriptingcourse | Lecture 2/PR_printRedditJson1.1.py | Python | gpl-3.0 | 3,376 | 0.039396 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Week 2: Project 1: Download and print json from reddit's main page.
This file contains methods to download and parse Reddit.com's main page.
One could do this hourly to sample reddit activity, and plot it over some metric.
hmmm....
CHANGELOG
version 1.1. Fixed bug ... | bove.
def getIteratedReddits(max=20 | 0,url="http://www.reddit.com/.json"):
'''This is the main controller method. Notice _i_ is in a range stepping by 25.
This is a user configurable setting, so if this code worked on a logged in user
it would have to be changed. I look at 50 reddits per page, for example.'''
after = ""
step = 25
for i in range(... |
scottrice/Ice | ice/emulators.py | Python | mit | 1,887 | 0.015898 | # encoding: utf-8
import os
def emulator_rom_launch_command(emulator, rom):
"""Generates a command string that will launch `rom` with `emulator` (using
the format provided by the user). The return value of this function should
be suitable to use as the `Exe` field of a Steam shortcut"""
# Normalizing the stri... | give us the ROM information, but screw it, I already
# have some code to add quotes to a string, might as well use it.
quoted_location = add_quotes(normalize(emulator.location))
quoted_rom = add_quotes(normalize(rom.path))
# The format string contains a bunch of specifies that users can use to
# substit... | are:
# %l - The location of the emulator (to avoid sync bugs)
# %r - The location of the ROM (so the emulator knows what to launch)
# %fn - The ROM filename without its extension (for emulators that utilize separete configuration files)
#
# More may be added in the future, but for now this is what we support... |
carlgao/lenga | images/lenny64-peon/usr/share/python-support/mercurial-common/hgext/convert/cvs.py | Python | mit | 11,997 | 0.001584 | # CVS conversion code inspired by hg-cvs-import and git-cvsimport
import os, locale, re, socket
from cStringIO import StringIO
from mercurial import util
from common import NoRepo, commit, converter_source, checktool
class convert_cvs(converter_source):
def __init__(self, ui, path, rev=None):
super(conve... | (t, id))
elif l.startswith("Log:"):
# switch to gathering log
state = 1
log = ""
elif state == 1: # lo | g
if l == "Members: \n":
# switch to gathering members
files = {}
oldrevs = []
log = self.recode(log[:-1])
state = 2
else:
# gather log
... |
cott81/rosha | rosha/rosha_repair_executor/test/repair_action_RedundantLoc.py | Python | lgpl-3.0 | 905 | 0.01989 | #!/usr/bin/env python
##\author Dominik Kirchner
##\brief Publishes diagnostic messages for diagnostic aggregator unit test
from debian.changelog import keyvalue
PKG = 'rosha_repair_executor'
import roslib; roslib.load_manifest(PKG)
import rospy
from time import sleep
#from diagnostic_msgs.msg import DiagnosticA... |
msg = RepairAction()
msg.robotId = 12
#
# redundancy replace loc
#
msg.repairActionToPerform = 32
msg.compName = "GPS"
msg.compId = -1
msg.msgType = ""
#pub.publish(msg)
#sleep(2)
while not rospy.is_shutdown():
pub.publish(msg)
sle... | (5)
|
exelearning/iteexe | exe/export/cmdlineexporter.py | Python | gpl-2.0 | 6,556 | 0.002289 | # -- coding: utf-8 --
# ===========================================================================
# eXe
# Copyright 2012, Pedro Peña Pérez, Open Phoenix IT
#
# 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 Softwar... | f __init__(self, config, options):
self.config = config
self.options = options
self.web_dir = Path(self.config.webDir)
self.styles_dir = None
def do_export(self, inputf, outputf):
if hasattr(self, 'export_' + self.options["export"]):
LOG.debug("Exporting to type ... | if not outputf:
if self.options["export"] in ('website', 'singlepage'):
outputf = inputf.rsplit(".elp")[0]
else:
outputf = inputf + self.extensions[self.options["export"]]
outputfp = Path(outputf)
if outputfp.exists() and no... |
ebruck/pyxis | pyxis/Player.py | Python | gpl-2.0 | 1,159 | 0.014668 | #!/usr/bin/python
#Pyxis and Original Sipie: Sirius Command Line Player
#Copyright (C) Corey Ling, Eli Criffield
#
#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, ... | TNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from StreamHandler im... | dler(opts)
def play(self, url, stream):
self.streamHandler.play(url, stream)
def playing(self):
return self.streamHandler.playing();
def close(self):
self.streamHandler.close()
|
sbaechler/simpleshop | simpleshop/payment_modules.py | Python | bsd-3-clause | 320 | 0.00625 | from plata.payme | nt.modules import cod
from django.shortcuts import redirect
from feincms.content.application.models import app_reverse
class CodPaymentProcessor(cod.PaymentProcessor):
def redirect(self, url_name):
return redirect(app_reverse(url_name,
' | simpleshop.urls')) |
sazzadBuet08/programming-contest | hackar_rank/infolytx_mock_hackar_rank/ABigSum.py | Python | apache-2.0 | 176 | 0 | #!/ | bin/python3
def aVeryBigSum(n, ar):
return sum(ar)
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = aVeryBi | gSum(n, ar)
print(result)
|
xulesc/spellchecker | impl1.py | Python | gpl-3.0 | 1,898 | 0.029505 | ## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
r... | f e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word | ]
return max(candidates, key=NWORDS.get)
#######################################################################################
if __name__ == '__main__':
TXT_FILE = sys.argv[1]
t0 = time.clock()
o_words = words(file(TXT_FILE).read())
NWORDS = train(o_words)
#print time.clock() - t0, " seconds build time"
... |
rtucker/sycamore | Sycamore/macro/allusers.py | Python | gpl-2.0 | 12,303 | 0.003658 | # -*- coding: utf-8 -*-
import time
import re
from cStringIO import StringIO
from Sycamore import wikiutil
from Sycamore import config
from Sycamore import wikidb
from Sycamore import user
from Sycamore.Page import Page
def execute(macro, args, formatter=None):
if not formatter:
formatter = macro.format... | page.link_to(know_status=True,
know_status_exists=True,
| querystr="sort_by=file_count",
text="Files Contributed"),
page.link_to(know_status=True,
know_status_exists=True,
querystr="sort_by=first_edit_date",
... |
jmbeuken/abinit | tests/pymods/memprof.py | Python | gpl-3.0 | 12,121 | 0.00693 | from __future__ import print_function, division, unicode_literals
from pprint import pprint
from itertools import groupby
from functools import wraps
from collections import namedtuple, deque
# OrderedDict was added in 2.7. ibm6 still uses python2.6
try:
from collections import OrderedDict
except ImportError:
... | pend(e); continue
# TODO: Should remove redondant entries.
if size > peaks[0].size:
peaks.append(e)
peaks = deque(sorted(peaks, key=lambda x: x.size), maxlen=maxlen)
peaks = deque(sorted(peaks, key=lambda x: x.size, reverse=True), maxlen=maxlen)
... | ll
def plot_memory_usage(self, show=True):
memory = [e.tot_memory for e in self.yield_all_entries()]
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(memory)
if show: plt.show()
return fig
#def get_dataframe(self):
... |
Code4Maine/suum | suum/apps/property/management/commands/import_property_csv.py | Python | bsd-3-clause | 2,559 | 0.010942 | from datetime import datetime
from csv import DictReader
from django.core.management.base import BaseCommand, CommandError
from property.models import Property, Owner, MailingAddress, Assessment, Building, Sale
class Command(BaseCommand):
help = 'Imports property from CSV file'
def add_arguments(self, parser)... | a,created = Assessment.objects.get_or_create(assoc_property=p, date=adate)
if created:
print('Adding assessment for {0}'.format(adate.year))
a.land=self.convert_to_float(d['Land Value'])
a.bu | ilding=self.convert_to_float(d['Building Value'])
a.exemption=self.convert_to_float(d['Exemption'])
a.tax_amount=self.convert_to_float(d['Tax Amount'])
a.date=adate
a.save()
o, created = Owner.objects.get_or_create(name=d["Owner's Name"])
... |
hdweiss/qt-creator-visualizer | tests/system/shared/workarounds.py | Python | lgpl-2.1 | 9,260 | 0.005508 | import urllib2
import re
JIRA_URL='https://bugreports.qt-project.org/browse'
class JIRA:
__instance__ = None
# Helper class
class Bug:
CREATOR = 'QTCREATORBUG'
SIMULATOR = 'QTSIM'
SDK = 'QTSDK'
QT = 'QTBUG'
QT_QUICKCOMPONENTS = 'QTCOMPONENTS'
# constructor of ... | pe = bugType
self._localOnly = os.getenv("SYSTEST_JIRA_NO_LOOKUP")=="1"
self.__initBugDict__()
self.__fetchStatusAndResolutionFromJira__()
| # function to retrieve the status of the current bug
def getStatus(self):
return self._status
# function to retrieve the resolution of the current bug
def getResolution(self):
return self._resolution
# this function checks the resolution of the given bug
... |
geary/claslite | web/app/lib/simplejson/tests/test_decimal.py | Python | unlicense | 1,752 | 0.002854 | from decimal import Decimal
from unittest import TestCase
from StringIO import StringIO
import simplejson as json
class TestDecimal(TestCase):
NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500"
def dumps(self, obj, **kw):
sio = StringIO()
json.dump(obj, sio, **kw)
res = json.... | n map(Decimal, self.NUMS):
self.assertEquals(self.dumps(d, use_decimal=True), str(d))
def test_decimal_decode(self):
| for s in self.NUMS:
self.assertEquals(self.loads(s, parse_float=Decimal), Decimal(s))
def test_decimal_roundtrip(self):
for d in map(Decimal, self.NUMS):
# The type might not be the same (int and Decimal) but they
# should still compare equal.
self.asse... |
tylerclair/py3canvas | py3canvas/apis/originality_reports.py | Python | mit | 24,351 | 0.001766 | """OriginalityReports API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class OriginalityReportsAPI(BaseCanvasAPI):
"""OriginalityReports... | eric_request(
"POST",
"/api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report".format(
**path
),
data=data,
params=params,
single_item=True,
)
def edit_originality_report_submissions(
... | id,
submission_id,
originality_report_error_message=None,
originality_report_originality_report_file_id=None,
originality_report_originality_report_url=None,
originality_report_originality_score=None,
originality_report_tool_setting_resource_type_code=None,
ori... |
maschwanden/boxsimu | boxsimu/builtins.py | Python | mit | 834 | 0.002398 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 2017 at 14:20
@author: Mathias Aschwanden ([email protected])
Makes various Variables available to the user.
IMPORTANT: All data has been included without warranty, express or implied.
References:
Molar Masses : From Wikipedia.org
" | ""
from . import ur
from . import entities as bs_entities
# VARIABLES
carbon = bs_entities.Variable('C', molar_mass=)
carbon_dioxide = bs_entites.Variable('CO2', molar_mass=)
methane = bs_entites.Variable('CH4', molar_ | mass=)
phosphate = bs_entities.Variable('PO4', molar_mass=94.9714*ur.gram/ur.mole)
phosphorus = bs_entities.Variable('P', molar_mass=)
nitrate = bs_entities.Variable('NO3', molar_mass=62.00*ur.gram/ur.mole)
nitrogen = bs_entities.Variable('P', molar_mass=)
# PROCESSES
# REACTIONS
# BOXES
# SYSTEMS
|
jgmize/nucleus | nucleus/settings/base.py | Python | bsd-3-clause | 4,534 | 0.000221 | # This is your project's main settings file that can be committed to your
# repo. If you need to override a setting locally, use local.py
import dj_database_url
from funfactory.settings_base import *
# Django Settings
##############################################################################
# Note: be sure not ... | serializers.HyperlinkedModelSerializerWithPkField',
# Use Django's standard `django.contrib.auth` permissions,
# or a | llow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_FILTER_BACKENDS': ('rna.filter... |
geraldspreer/the-maker | makerTemplateViewBuilder.py | Python | gpl-3.0 | 7,622 | 0.009315 | from makerUtilities import writeFile
from makerUtilities import readFile
import os
def scaffold(systemDir, defaultTheme):
return (
"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src='file://"""
+ os.path.join(systemDir, "jquery.min.js")
+ """'></script... | 00%;
-webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(50%, transparent), to(rgba(0,0,0,0.2)));
-webkit-transform: perspective( 600px ) rotateY( 0deg);
margin-bottom:40px;
}
.row {
... |
}
.thumbnail {
width:17%;
padding:20px 20px 10px 20px;
margin:0px 20px 0px 0px;
float:left;
clear:right;
background:none;
}
.thumbnail img {
height:100px;
... |
sqlalchemy/alembic | tests/test_autogen_composition.py | Python | mit | 16,541 | 0 | import re
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy.sql.sqltypes import DateTime
from alembic import autogenerate
from alembic.migration import MigrationContext
from alembic.testing import eq_... | lf.m1,
"upgrade_token": "upgrades",
"downgrade_token": "downgrades",
"alembic_module_prefix": "op.",
"sqlalchemy_module_prefix": "sa.",
"render_as_batch": True,
"include_symbo | l": lambda name, schema: False,
},
)
template_args = {}
autogenerate._render_migration_diffs(context, template_args)
eq_(
re.sub(r"u'", "'", template_args["upgrades"]),
"""# ### commands auto generated by Alembic - please adjust! ###
pass
# ##... |
dkm/skylines | skylines/lib/base36.py | Python | agpl-3.0 | 746 | 0 | """
base 36 encoding/decoding taken from wikipedia sample code
http://en.wikipedia.org/wiki/Base_36#Python_Conversion_Code
"""
def encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Converts an in | teger to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number >= 0 and number <= 9:
return alphabet[number]
base36 = ''
sign = ''
if number < 0:
| sign = '-'
number = -number
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def decode(number):
"""Converts a base36 string to an integer."""
return int(number, 36)
|
smalls12/django_helpcenter | helpcenter/admin.py | Python | mit | 883 | 0 | from django.contrib import admin
from helpcenter import models
class ArticleAdmin(admin.ModelAdmin):
""" Admin for the Article model """
date_hierarchy = 'time_published'
fieldsets = (
(None, {
'fields': ('category', 'title', 'body')
}),
('Publishing Options', {
... | list_display = (
'title', 'category', 'time_published', 'time_edited', 'draft')
search_fields = | ('title',)
class CategoryAdmin(admin.ModelAdmin):
""" Admin for the Category model """
fieldsets = (
(None, {
'fields': ('parent', 'title')
}),)
list_display = ('title', 'parent')
search_fields = ('title',)
admin.site.register(models.Article, ArticleAdmin)
admin.site.reg... |
berndf/avg_q | python/avg_q/Presentation.py | Python | gpl-3.0 | 3,161 | 0.043341 | # Copyright (C) 2013 Bernd Feige
# This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING).
"""
Presentation utilities.
"""
from . import trgfile
class PresLog(object):
# Basic log file reading.
def __init__(self,logfile,part='events'):
'''part can be 'events' or 'trials' for the first or sec... | f,logfile,part='events'):
self.PL=PresLog(logfile,part)
trgfile.trgfile.__init__(self,self.PL)
self.preamble['Sfreq']=10000.0
def rdr(self):
for fields in self.reader:
data=dict(zip(self.PL.header_fields,fields))
point=int(data['Time'])
description=data['Event Type']
| try:
code=int(data['Code'])
except:
code= -1
description=' '.join([description,data['Code']])
yield (point, code, description)
def close(self):
if self.PL:
self.PL.close()
self.PL=None
def gettuples_abstime(self):
# We are calculating backwards from the time the log was written, which is g... |
athkishore/vgr | migrations/versions/c626e32ddcc_.py | Python | mit | 2,615 | 0.01262 | """empty message
Revision ID: c626e32ddcc
Revises: None
Create Date: 2016-01-23 14:47:09.205628
"""
# revision identifiers, used by Alembic.
revision = 'c626e32ddcc'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
... | .String(length=128), nullable=True),
sa.Column('confirmed', sa.Boolean(), nullable=True),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('location', sa.String(length=64), nullable=True),
sa.Column('about_me', sa.Text(), nullable=True),
sa.Column('member_ | since', sa.DateTime(), nullable=True),
sa.Column('last_seen', sa.DateTime(), nullable=True),
sa.Column('avatar_hash', sa.String(length=32), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_users_email', 'users', ['email'], ... |
root-z/ECPP | hilbert.py | Python | gpl-2.0 | 4,207 | 0.002377 | '''
Compute Hilbert Class Polynomials
'''
from mpmath import *
import mpmath
round = lambda x: mpmath.floor(x + 0.5)
def hilbert(d):
'''
Compute Hilbert Class Polynomial.
Follows pseudo code from Algorithm 7.5.8
Args:
d: fundamental discriminant
Returns:
Hilbert class number, Hil... | reduced_forms = reduced_form(d) # print h1
a_inverse_sum = sum(1/mpf(form[0]) for form in reduced_forms)
precision = round(pi*sqrt(-d)*a_inverse_sum / log(10)) + 10
mpmath.mp.dps = precision
| # outer loop
while b <= r:
m = (b*b - d) / 4
m_sqrt = int(floor(sqrt(m)))
for a in range(1, m_sqrt+1):
if m % a != 0:
continue
c = m/a
if b > a:
continue
# optional polynomial setup
tau = (-b + 1j * s... |
Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.1/async_samples/sample_recognize_custom_forms_async.py | Python | mit | 6,386 | 0.004071 | # coding: utf-8
# --------------------------- | ----------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# License | d under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_recognize_custom_forms_async.py
DESCRIPTION:
This sample demonstrates how to analyze a form from a document with a custom
traine... |
dudanogueira/microerp | microerp/comercial/migrations/0054_tipodeproposta_tipo_contrato_mapeado.py | Python | lgpl-3.0 | 472 | 0.002119 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('comercial', '0053_auto_20151118_1323'),
]
operations = [
m | igrations.AddField(
model_name='tipodeproposta',
name='tipo_contrato_mapeado',
field=models.ForeignKey(blank=True, to='comercial.TipodeContratoFechado', null=True),
),
| ]
|
CDE-UNIBE/lokp | lokp/review/activities.py | Python | gpl-3.0 | 314 | 0 | from lokp.model | s import DBSession
from lokp.protocols.activity_protocol import ActivityProtocol
from lokp.review.review import BaseReview
class ActivityReview(BaseRevi | ew):
def __init__(self, request):
super(ActivityReview, self).__init__(request)
self.protocol = ActivityProtocol(DBSession)
|
sbarton272/StreetPong | IPC/printer.py | Python | apache-2.0 | 195 | 0.005128 |
from sys import stdin
import signal |
# for i in xrange(1,10):
# print "Stuff", i
# print s | tdin.readline()
import os
pid = int(stdin.readline().strip())
print pid
os.kill(pid, signal.SIGINT) |
jgehring/rsvndump | tests/db/tests/delete_add.py | Python | gpl-3.0 | 1,440 | 0.046528 | #
# Test database for rsvndump
# written by Jonas Gehring
#
import os
import test_api
def info():
return "Add after delete test"
def setup(step, log):
if step == 0:
os.mkdir("dir1")
f = open("dir1/file1","wb")
print >>f, "hello1"
print >>f, "hello2"
f = open("dir1/file2","wb")
print >>f, "hello3"
... | api.run("svn", "rm", "file1", output=log)
return True
elif step == 3:
f = open("file12","ab")
print >>f, "hello6"
return True
elif step == 4:
test_api.run("svn", "rm", "dir1", output=log)
return True
elif step == 5:
os.mkdir("dir1")
f = open("dir1/file1","wb")
print >>f, "hello7"
f = open("dir1/f... | open("dir1/file1","ab")
print >>f, "hello10"
return True
else:
return False
# Runs the test
def run(id, args = []):
# Set up the test repository
test_api.setup_repos(id, setup)
odump_path = test_api.dump_original(id)
rdump_path = test_api.dump_rsvndump(id, args)
vdump_path = test_api.dump_reload(id, rdu... |
metrey/b2tob3 | setup.py | Python | mit | 935 | 0.001071 | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
from b2tob3 import VERSION
with open('README | .rst') as f:
README = f.read()
with open('LICENSE') as f:
LICENSE = f.read()
setup(
name='b2tob3',
version=VERSION,
packages=find_packages(),
long_description=README,
license=LICENSE,
author='Ramiro Gómez',
author_email='[email protected]',
description='Help migrate HTML files an... | : Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Communications',
'Topic :: Text Processing',
],
entry_points={
'console_scripts': [
'b2tob3=b2tob3.b2tob3:main'
]
... |
initzx/aobot | utils/logger.py | Python | gpl-3.0 | 3,201 | 0.002812 | from utils.edit_configs import get_json
class Logger:
config = get_json('server_configs')
log_config = {}
_instances = {}
@staticmethod
def get_singleton(client):
if client.shard_id not in Logger._instances:
Logger._instances[client.shard_id] = Logger()
return Logger.... | = ':bust_in_silhouette::arrow_left: **User left**: {0}'.format(member)
await client.send_message(logs, to_send)
@client.async_event
async def on_member_ban(member):
if member.server.id in Logger.log_config[client.shard_id]:
logs = Logger.log_config[client.sh... | n_silhouette::x: **User banned**: {0}'.format(member)
await client.send_message(logs, to_send)
@client.async_event
async def on_member_unban(server, user):
if server.id in Logger.log_config[client.shard_id]:
logs = Logger.log_config[client.shard_id][server.id... |
mailgun/flanker | flanker/mime/create.py | Python | apache-2.0 | 2,803 | 0 | """
This package is a set of utilities and methods for building mime messages.
"""
import uuid
from flanker import _email
from flanker.mime import DecodingError
from flanker.mime.message import ContentType, scanner
from flanker.mime.message.headers import WithParams
from flanker.mime.message.headers.parametrized impo... | e),
is_root=True)
def binary(maintype, subtype, body, filename=None,
disposition=None, charset=None, trust_ctype=False):
return MimePart(
container=Body(
content_type=ContentType(maintype, subtype),
trust_ctype=trust_ctype,
body=body,
char... | ame=None,
disposition=None, charset=None):
"""Smarter method to build attachments that detects the proper content type
and form of the message based on content type string, body and filename
of the attachment
"""
# fix and sanitize content type string and get main and sub parts:
... |
jyr/japos | dashboards/urls.py | Python | gpl-2.0 | 112 | 0.017857 | f | rom django.conf.urls.defaults import *
urlpatterns = pattern | s('japos.dashboards.views',
(r'^$', 'index')
) |
Chasego/codi | util/basic/quicksort.py | Python | mit | 120 | 0.008333 | quicksort(A, lo, hi):
if lo | < hi:
p := partition(A, lo, hi)
quicksort(A, lo, p - | 1)
quicksort(A, p + 1, hi)
|
Skippern/PDF-scraper-Lorenzutti | creators/seletivo/common.py | Python | gpl-3.0 | 1,983 | 0.013138 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Common functions
import os, sys
lib_path = os.path.abspath( os.path.join( '..', '..', 'lib' ) )
sys.path.append(lib_path)
from commons import *
from overpasser import *
from routing import *
from feriados import *
from make_json import *
def lower_capitalized(input):
o... | P. Costa", u"Praia da Costa")
output = output.replace(u"S. Dourada", u"Serra Dourada")
output = output.replace(u"M. Noronha", u"Marcilio de Noronha")
| output = output.replace(u"Marcilio de Noronha", u"Marcílio de Noronha")
return output.strip()
def getLines():
downloadURL = "https://sistemas.es.gov.br/webservices/ceturb/onibus/api/ConsultaLinha?Tipo_Linha=Seletivo"
routes = []
myJSON = None
r = False
while r == False:
try:
... |
zstackorg/zstack-woodpecker | integrationtest/vm/virt_plus/other/test_parallel_crt_vm_to_use_all_disk.py | Python | apache-2.0 | 5,980 | 0.009532 | '''
This case can not execute parallelly.
This case will calculate max available VMs base on 1 host available disk space.
The it will try to create all VMs at the same time to see if zstack could
handle it.
@author: Youyk
'''
import os
import sys
import threading
import time
import random
import zst... | ion_storage_rate(over_provision_rate)
data_volume_size = int(av | ail_cap / target_vm_num * over_provision_rate - image_size)
if data_volume_size < 0:
test_util.test_skip('Do not have enough disk space to do test')
return True
delete_policy = test_lib.lib_set_delete_policy('vm', 'Direct')
delete_policy = test_lib.lib_set_delete_policy('volume', 'Dir... |
thopiekar/Uranium | plugins/UpdateChecker/UpdateCheckerJob.py | Python | lgpl-3.0 | 4,818 | 0.009755 | # Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Message import Message
from UM.Version import Version
from UM.Logger import Logger
from UM.Job import Job
import urllib.request
import platform
import json
import codecs
f... | ("download", i18n_catalog.i18nc | ("@action:button", "Download"), "[no_icon]", "[no_description]")
if self._set_download_url_callback:
self._set_download_url_callback(value["url"])
message.actionTriggered.connect(self._callback)
... |
ncos/hometasks | Lunev/programming/star_1/stable/tests/file_generator.py | Python | mit | 193 | 0.010363 |
f_source = open( | '../talker/workfile', 'w')
f_gold = open('../listener/workfile', 'w')
for i in range(100000):
f_source.write('0123456789abcdef')
f_gold.write('012 | 3456789abcdef')
|
sachinkum/Bal-Aveksha | WebServer/Authentications/admin.py | Python | gpl-3.0 | 54 | 0 | fro | m django.contrib import | admin
from . import models
|
DarioGT/OMS-PluginXML | org.modelsphere.sms/lib/jython-2.2.1/Lib/test/test_compile.py | Python | gpl-3.0 | 3,243 | 0.005242 | from test_support import verbose, TestFailed
if verbose:
print "Testing whether compiler catches assignment to __debug__"
try:
compile('__debug__ = 1', '?', 'single')
except SyntaxError:
pass
import __builtin__
prev = __builtin__.__debug__
setattr(__builtin__, '__debug__', 'sure')
setattr(__... |
comp_args(1, (2, 3))
comp_args()
try:
exec 'def f(a=1, (b, c)): pass'
raise TestFailed, "non-default args after default"
except SyntaxError:
pass
if verbose:
print "testing bad float literals"
def expect_error(s):
try:
eval(s)
raise TestFailed("%r accepted" % s)
... | with leading zeroes"
def expect_same(test_source, expected):
got = eval(test_source)
if got != expected:
raise TestFailed("eval(%r) gave %r, but expected %r" %
(test_source, got, expected))
expect_error("077787")
expect_error("0xj")
expect_error("0x.")
expect_error(... |
lucaskanashiro/debile | tests/test_slave_cli.py | Python | mit | 370 | 0.010811 | # Run with nosetests tests/test_slave_cli.py
import debile.slave.cli as slave
def test_pa | rse_args():
args = slave.parse_args(['--auth', 'simple', '--config', \
'/etc/debile/slave.yaml', '-s', '-d'])
assert args.auth_method == | 'simple'
assert args.config == '/etc/debile/slave.yaml'
assert args.syslog == True
assert args.debug == True
|
elyezer/robottelo | robottelo/ui/locators/menu.py | Python | gpl-3.0 | 10,740 | 0 | # -*- encoding: utf-8 -*-
"""Implements different locators for UI"""
from selenium.webdriver.common.by import By
from .model import LocatorDict
NAVBAR_PATH = (
'//div[contains(@class,"navbar-inner") and '
'not(contains(@style, "display"))]'
)
MENU_CONTAINER_PATH = NAVBAR_PATH + '//ul[@id="menu"]'
ADM_MENU_CO... | [@id='menu_item_docke | r_tags']")),
# Containers Menu
"menu.containers": (
By.XPATH,
(MENU_CONTAINER_PATH + "//a[@id='containers_menu']")),
"menu.all_containers": (
By.XPATH,
(MENU_CONTAINER_PATH + "//a[@id='menu_item_containers']")),
"menu.new_container": (
By.XPATH,
(MENU_CON... |
crypto101/clarent | clarent/exercise.py | Python | isc | 1,105 | 0.002715 | """
Public exercise API.
"""
from twisted.protocols import amp
from txampext.errors import Error
class UnknownExercise(Error):
"""The exercise was not recognized.
"""
class GetExercises(amp.Command):
"""
Gets the identifiers and titles of some exercises.
"""
arguments = [
(b"solved... | amp.Unicode())
]))
]
class GetExerciseDetails(amp.Command):
"""
Gets the details of a partiucular exercise.
"""
arguments = [
(b"identifier", amp.String())
]
response = [
(b"title", amp.Unicode()),
(b"description", amp.Unicode()),
(b"solved", amp.B... | ownExercise.asAMP()
])
class NotifySolved(amp.Command):
"""Notify the client that they have solved an exercise.
"""
arguments = [
(b"identifier", amp.String()),
(b"title", amp.Unicode())
]
response = []
requiresAnswer = False
|
lecaoquochung/ddnb.django | django/contrib/gis/db/models/fields.py | Python | bsd-3-clause | 12,573 | 0.000954 | from django.db.models.fields import Field
from django.db.models.sql.expressions import SQLEvaluator
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis import forms
from django.contrib.gis.db.models.constants import GIS_LOOKUPS
from django.contrib.gis.db.models.lookups import GISLookup
from ... | :
"""
Spatial lookup values are either a parameter that is (or may be
converted to) a geometry, or a sequence of lookup values that
begins with a geometry. This routine will setup the geometry
value properly, and preserve any other lookup parameters before
returning to t... | or):
return value
elif isinstance(value, (tuple, list)):
geom = value[0]
seq_value = True
else:
geom = value
seq_value = False
# When the input is not a GEOS geometry, attempt to construct one
# from the given string input.
... |
jjshoe/ansible-modules-core | cloud/vmware/vsphere_guest.py | Python | gpl-3.0 | 65,239 | 0.001456 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible 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.
#... | . See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# TODO:
# Ability to set CPU/Memory reservations
try:
import json
except ImportError:
import simplejson as json
H | AS_PYSPHERE = False
try:
from pysphere import VIServer, VIProperty, MORTypes
from pysphere.resources import VimService_services as VI
from pysphere.vi_task import VITask
from pysphere import VIException, VIApiException, FaultTypes
HAS_PYSPHERE = True
except ImportError:
pass
import ssl
DOCUMEN... |
3stack-software/credsmash | credsmash/__init__.py | Python | apache-2.0 | 686 | 0 | #!/usr/bin/env python
# Copyright 2015 Luminal, Inc.
#
# 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... |
__version__ = pkg_resources.resource_string(__name | __, 'VERSION')
|
benoitc/pywebmachine | pywebmachine/resource.py | Python | mit | 3,011 | 0.004982 | # -*- coding: utf-8 -*-
#
# This file is part of pywebmachine released under the MIT license.
# See the NOTICE for more information.
class Resource(object):
def __init__(self, req, rsp):
pass
def allowed_methods(self, req, rsp):
return ["GET", "HEAD"]
def allow_missing_post(self, req, r... | lf, req, rsp):
return [
("text/html", self.to_html)
]
def created_location(self, req, rsp):
return None
def delete_completed(self, req, rsp):
return True
def delete_resource(self, req, rsp):
return False
def encodings_provided(self, req, rsp):
... | iation logic.
"""
return None
def expires(self, req, rsp):
return None
def finish_request(self, req, rsp):
return True
def forbidden(self, req, rsp):
return False
def generate_etag(self, req, rsp):
return None
def is_authorized(self, req, ... |
72squared/redpipe | docs/conf.py | Python | mit | 5,400 | 0 | # -*- coding: utf-8 -*-
#
# RedPipe documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 19 13:22:45 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.
#
# A... | ath
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML out | put ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme... |
SergeyMakarenko/fbthrift | thrift/lib/py3/__init__.py | Python | apache-2.0 | 800 | 0 | #!/usr/bin/env python3
__all__ = [
'get_client', 'Client', 'ThriftServer', 'Struct', 'BadEnum', 'Error',
'ApplicationError', 'TransportError', 'SSLPolicy',
]
try:
from thrift.py3.client import get_client, Client
except ImportError:
__all__.remove('Client')
__all__.remove('get_client')
try:
fro... | pt ImportError:
__all__.remove('ThriftServer')
__all__.remove('SSLPolicy')
try:
from thrift.py3.types import Struct, BadEnum
except ImportError:
__all__.remove('Struct')
__all__.remove('BadEnum')
try:
from thr | ift.py3.exceptions import Error, ApplicationError, TransportError
except ImportError:
__all__.remove('Error')
__all__.remove('ApplicationError')
__all__.remove('TransportError')
|
fxstein/SentientHome | rules/plugin.rules.py | Python | apache-2.0 | 3,196 | 0.000626 | #!/usr/local/bin/python3 -u
"""
Author: Oliver Ratzesberger <https://github.com/fxstein>
Copyright: Copyright (C) 2016 Oliver Ratzesberger
License: Apache License, Version 2.0
"""
# Make sure we have access to SentientHome commons
import os
import sys
try:
sys.path.append(os.path.dirname(os.pat... | ment.core import hook
def process_event(app, event_type, event):
app.log.debug('process_event() Event: %s %s' %
(event_type, event), __name__)
try:
if event_type == 'isy' and event['Event.node'] is not None:
# Lookup name for easy rules coding
nodename = app.... | (event['Event.node'], nodename, event), __name__)
if nodename == 'Master - Lights' and\
event['Event.control'] == 'DON':
app.log.error('Auto Off for: %s %s' %
(event['Event.node'], nodename), __name__)
time.... |
XiaofanZhang/ROPgadget | ropgadget/ropparse/arch/parserx86.py | Python | gpl-2.0 | 17,183 | 0.013967 | #!/usr/bin/env python2
##
## We define Instrution as two types "Computing instruction" and "Control Transfer instruction"
## for computing instruction
## "NAME" : [ Operand_Number , [ Formula_that_modify_reg ], [ FLAG_reg_modified]]
## for control transfter instruciton
## "NAME" : [ Operand_Number , [ Formula_tha... | operand1 : 0"]],
"je": [1, [], ["ZF == 1 ? | * operand1 : 0"]],
"jnc": [1, [], ["CF == 0 ? * operand1 : 0"]],
"jne": [1, [], ["ZF == 0 ? * operand1 : 0"]],
"jnp": [1, [], ["PF == 0 ? * operand1 : 0"]],
"jp": [1, [], ["PF == 1 ? * operand1 : 0"]],
"jg": [1, [], ["( ( ZF == 0 ) & ( SF == OF ) ) ? * operand1 : 0"]],
"jge": [1, [], ["SF ... |
MarauderXtreme/sipa | sipa/backends/types.py | Python | mit | 268 | 0 | from typing_extensions import Protoco | l
# noinspection PyPropertyDefinition
class UserLike(Protocol):
@property
def is_active(self) -> bool: ...
@property
def is_authenticated(self) -> bool: ...
@property
def is_anonymous(self) -> bo | ol: ...
|
jolynch/mit-tab | mittab/apps/tab/management/commands/load_test.py | Python | mit | 4,345 | 0.001611 | import re
from threading import Thread
import time
from django.core.management.base import BaseCommand
import requests
from mittab.apps.tab.models import Round, TabSettings
from mittab.apps.tab.management.commands import utils
class Command(BaseCommand):
help = "Load test the tournament, connecting via localhos... | nt("Total errors: %s" % num_errors)
class SubmitResultThread(Thread):
MAX_ERRORS = 10
def __init__(self, host, ballot_code, csrf_token, round_obj):
super( | SubmitResultThread, self).__init__()
self.host = host
self.ballot_code = ballot_code
self.csrf_token = csrf_token
self.round_obj = round_obj
self.num_errors = 0
self.resp = None
def run(self):
self.resp = self.get_resp()
def get_resp(self):
if se... |
OSUrobotics/peac_bridge | src/peac_bridge/peac_client.py | Python | bsd-3-clause | 3,420 | 0.003509 | #!/usr/bin/env python
import json
import requests
from requests.auth import HTTPBasicAuth
import urlparse
import time
class PEACInfo:
def __init__(self, url, method):
self.url = url
self.method = method
self.headers = {
'accept': 'application/json',
'Content-Type': '... | , proxies={}):
self.server = server
self.user = user
self.password = password
self.proxies = proxies
def _make_url(self, peacinfo):
urlparts = list(urlparse.urlparse(self.server + peacinfo.url))
return urlparse.urlunparse(urlparts)
def _PEAC_request(self, peacin... | s, data=json.dumps(payload), headers=peacinfo.headers, auth=HTTPBasicAuth(self.user, self.password), proxies=self.proxies)
else:
resp = requests.request(peacinfo.method, url % url_args, headers=peacinfo.headers, auth=HTTPBasicAuth(self.user, self.password), proxies=self.proxies)
return resp
... |
CitrineInformatics/lolo | python/lolopy/learners.py | Python | apache-2.0 | 23,987 | 0.004586 | from abc import abstractmethod, ABCMeta
import numpy as np
from lolopy.loloserver import get_java_gateway
from lolopy.utils import send_feature_array, send_1D_array
from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin, is_regressor
from sklearn.exceptions import NotFittedError
__all__ = ['RandomFor... | ABCMeta):
"""Base object for all leaners that use Lolo.
Contains logic for starting the JVM gateway, and the fit operations.
It is only necessary to implement the `_make_learner` object and create an `__init__` function
to adapt a learner from the Lolo library for use in lolopy.
The logic for maki... | specific to a regression or classification problem and the type of problem is determined
when fitting data is provided to the algorithm.
In contrast, Scikit-learn learners for regression or classification problems are different classes.
We have implemented `BaseLoloRegressor` and `BaseLoloClassifier` abstra... |
shoyer/xarray | xarray/coding/cftime_offsets.py | Python | apache-2.0 | 35,760 | 0.001091 | """Time offset classes for use with cftime.datetime objects"""
# The offset classes and mechanisms for generating time ranges defined in
# this module were copied/adapted from those defined in pandas. See in
# particular the objects and methods defined in pandas.tseries.offsets
# and pandas.core.indexes.datetimes.
# ... | TS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import re
from datetime import timedelta
from dist... | rtial
from typing import ClassVar, Optional
import numpy as np
from ..core.pdcompat import count_not_none
from .cftimeindex import CFTimeIndex, _parse_iso8601_with_reso
from .times import format_cftime_datetime
def get_date_type(calendar):
"""Return the cftime date type for a given calendar name."""
try:
... |
stevenmizuno/QGIS | tests/src/python/test_qgsmaplayer.py | Python | gpl-2.0 | 4,223 | 0.000474 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsMapLayer
.. note:: 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.
"""
__auth... | hEnabled())
self.assertEqual(layer.autoRefreshInterval(), 0)
layer.setAutoRefreshInterval(5)
self.assertFalse(layer.hasAutoRefreshEnabled())
self.assertEqual(layer.autoRefreshInterval(), 5)
layer.setAutoRefreshEnabled(True)
| self.assertTrue(layer.hasAutoRefreshEnabled())
self.assertEqual(layer.autoRefreshInterval(), 5)
layer.setAutoRefreshInterval(0) # should disable auto refresh
self.assertFalse(layer.hasAutoRefreshEnabled())
self.assertEqual(layer.autoRefreshInterval(), 0)
def testSaveRestoreAutoRef... |
sfriesel/suds | suds/sax/parser.py | Python | lgpl-3.0 | 4,378 | 0.000228 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser 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 b... | y Lesser General Pub | lic License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( ... |
alenasf/Pythontest | test/test_add_group.py | Python | apache-2.0 | 813 | 0.00492 | # -*- coding: utf-8 -*-
from model.group import Group
def test_add_group(app):
old_groups = app.group.get_group_list()
group = Group(name="hjhj", header="jhjh", footer="jhjjhhj")
app.group.create(group)
new_groups = app.group.get_group_list()
assert len(old_groups) + 1 == len(new_groups)
old_... | app.group.create(group)
new_groups = ap | p.group.get_group_list()
assert len(old_groups) + 1 == len(new_groups)
old_groups.append(group)
assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
|
fengz10/ICN_SCM | Zipf.py | Python | gpl-2.0 | 821 | 0.015834 | #!/usr/bin/python
import random
import math
imp | ort bisect
############################Zipf Generater###################### | ##########
# The library of numpy.random.zipf or scipy.stats.zipf only work when
# alph > 1
class ZipfGenerator:
def __init__(self, n, alpha):
# Calculate Zeta values from 1 to n:
tmp = [1. / (math.pow(float(i), alpha)) for i in range(1, n+1)]
zeta = reduce(lambda sums, x: sums + [sums[-1... |
quietcoolwu/learn-python3-master | imooc/10_3.py | Python | gpl-2.0 | 365 | 0.023166 | #条件过滤的要点是综合语句的构造。利用 if 剔除掉非字符串的元 | 素。e.g:而列表生成式则可以用一行语句代替循环生成上面的list:
#>>> [x * x for x in range(1, 11)]
#[1 | , 4, 9, 16, 25, 36, 49, 64, 81, 100]
def toUppers(L):
return [x.upper() for x in L if isinstance(x,str)]
print (toUppers(['Hello', 'world', 101]))
|
CenterForOpenScience/osf-sync | osfsync/gui/qt/tray.py | Python | lgpl-3.0 | 9,674 | 0.001654 | import logging
import os
import sys
import threading
from queue import Empty, Queue
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QMutex
from PyQt5.QtCore import QThread
from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QTex... | user.folder = os.path.join(containing_folder, 'OSF')
os.makedirs(user.folder, exist_ok=True)
session.add(user)
session.commit()
def start(sel | f):
logger.debug('Start in main called.')
self.hide()
user = LoginScreen().get_user()
if user is None:
return False
self.ensure_folder(user)
self.show()
logger.debug('starting background handler from main.start')
BackgroundHandler().set_inter... |
victorshch/axiomatic | integration_test_frequecy_axioms.py | Python | gpl-3.0 | 1,653 | 0.005445 | # coding=UTF-8
import pandas as pd
import numpy as np
import pickle
from axiomatic.base import AxiomSystem, MinMaxAxiom, MaxAxiom, MinAxiom, ChangeAxiom, IntegralAxiom
from axiomatic.base import RelativeChangeAxiom, FirstDiffAxiom, SecondDiffAxiom, TrainingPipeline
from axiomatic.axiom_training_stage import Frequency... | cognizerTrainingStage()
training_pipeline = TrainingPipeline([frequency_ec_stage, frequency_axiom_stage, dum | my_recognizer_stage])
artifacts = training_pipeline.train(dataset, dict())
print("Artifacts after training: ", artifacts)
recognizer = AbnormalBehaviorRecognizer(artifacts['axiom_system'], artifacts['abn_models'],
dict(bound=0.1,maxdelta=0.5))
obj_fn = ObjectiveFunction(1, 20... |
aequitas/home-assistant | homeassistant/components/remote_rpi_gpio/binary_sensor.py | Python | apache-2.0 | 3,259 | 0 | """Support for binary sensor using RPi GPIO."""
import logging
import voluptuous as vol
import requests
from homeassistant.const import CONF_HOST
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
from . import (CONF_BO... | oteRPiGPIOBinarySensor(port_name, button, invert_logic)
devices.append(new_sensor)
add_entities(devices, True)
class RemoteRPiGPIOBinarySensor(BinarySensorDevice):
"""Represent a binary sensor that uses a Remote Raspberry Pi GPIO."""
def __init__(self, | name, button, invert_logic):
"""Initialize the RPi binary sensor."""
self._name = name
self._invert_logic = invert_logic
self._state = False
self._button = button
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
def read_g... |
RevansChen/online-judge | Codewars/8kyu/freudian-translator/Python/solution1.py | Python | mit | 91 | 0.010989 | # Python - 2.7.6
to_freud = lambda sentence: ' '.join(['sex'] * le | n(s | entence.split(' ')))
|
newvem/pytz | pytz/zoneinfo/Asia/Ashkhabad.py | Python | mit | 1,535 | 0.160261 | '''tzinfo timezone information for Asia/Ashkhabad.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Ashkhabad(DstTzInfo):
'''Asia/Ashkhabad timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Ashkhabad'
... | ,0),
d(1981,9,30,18,0,0),
d(1982,3,31,19,0,0),
d(1982,9,30,18,0,0),
d(1983,3,31,19,0,0),
d(1983,9,30,18,0,0),
d(1984,3,31,19,0,0),
d(1984,9,29,21,0,0),
d(1985,3,30,21, | 0,0),
d(1985,9,28,21,0,0),
d(1986,3,29,21,0,0),
d(1986,9,27,21,0,0),
d(1987,3,28,21,0,0),
d(1987,9,26,21,0,0),
d(1988,3,26,21,0,0),
d(1988,9,24,21,0,0),
d(1989,3,25,21,0,0),
d(1989,9,23,21,0,0),
d(1990,3,24,21,0,0),
d(1990,9,29,21,0,0),
d(1991,3,30,21,0,0),
d(1991,9,28,22,0,0),
d(1991,10,26,20,0,0),
d(1992,1,18,22,0,0)... |
danigm/sweetter | sweetter/contrib/karma/urls.py | Python | agpl-3.0 | 136 | 0.007353 | from django.conf.urls.defau | lts import *
urlpatterns = patterns('contrib.karma.views',
(r'^$', 'index'),
| (r'index', 'index'),
)
|
TejasM/wisely | wisely_project/get_courses_file.py | Python | mit | 1,721 | 0.004648 | import sys
import os
import traceback
from django import db
sys.path.append('/root/wisely/wisely_project/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wisely_project.settings.production'
from django.db.models import F, Q
from django.utils import timezone
from users.tasks import get_coursera_courses, get_edx_courses, ge... | rt CourseraProfile, EdxProfile, UdemyProfile
while True:
try:
for connection in db.connections.all():
if len(connection.queries) > 100:
db.reset_queries()
for user in CourseraProfile.objects.filter(last_updated__lt=F('user__last_lo | gin')).filter(~Q(username='')).filter(
incorrect_login=False):
print user.username
print "Start coursera"
get_coursera_courses(user)
user.last_updated = timezone.now()
print "Done Coursera"
user.save()
for user in EdxProfile... |
cycloidio/cyclosible | cyclosible/playbook/migrations/0004_playbookrunhistory_log_url.py | Python | gpl-3.0 | 441 | 0 | # -*- coding: utf-8 -*-
fro | m __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('playbook', '0003_auto_20151028_1735'),
]
operations = [
migrations.AddField(
model_name='playbookrunhistory',
name='log_url',
... | (default=b'', max_length=1024, blank=True),
),
]
|
tryggvib/datapackage | datapackage/schema.py | Python | gpl-3.0 | 11,045 | 0.000181 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .util import Specification
from . import compat
class Field(Specification):
"""
Field object for adding fields to a resource schema... | o through a list and get out the names and use them as the
# value
if value_type == list:
modified_value = []
for single_value in value:
if type(single_value) == compat.str:
modified_value.append(single_value)
... | else:
raise TypeError(
'Foreign key type ({0}) is not supported'.format(
type(single_value)))
value = modified_value
elif value_type == compat.str:
# We don't need to do anythin... |
zstang/learning-python-the-hard-way | ex5.py | Python | mit | 635 | 0.009449 | # -*- coding: utf-8 -*-
#
# exercise 5: more vari | ables and printing
#
# string formating
name = 'Zed A. Shaw'
ages = 35 # not a lie
height = 74 # inched
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inched tall." % height
print "He's %d pounds heavy." % weight
print | "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." %(
ages, height, weight, ages + height + weight) |
sileht/python-gnocchiclient | gnocchiclient/tests/functional/test_benchmark.py | Python | apache-2.0 | 4,537 | 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
# d... | result = | self.gnocchi(
u'metric', params=u"create -a %s" % apname)
metric = json.loads(result)
result = self.gnocchi(
u'benchmark', params=u"measures add -n 10 -b 4 %s" % metric['id'])
result = json.loads(result)
self.assertEqual(2, int(result['push executed']))
... |
quentinbodinier/custom_gnuradio_blocks | python/qa_test_interp.py | Python | gpl-3.0 | 36,971 | 0.003489 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but chang... | rovision to those domains in future versions
# of the GPL, as needed to protect the freedom of users.
#
# Finally, every program is threatened constantly by software patents.
# States should not allow patents to restrict development and use of
# software on general-purpose compu | ters, but in those that do, we wish to
# avoid the special danger that patents applied to a free program could
# make it effectively proprietary. To prevent this, the GPL assures that
# patents cannot be used to render the program non-free.
#
# The precise terms and conditions for copying, distribution and
# modifi... |
midnightradio/gensim | gensim/sklearn_api/hdp.py | Python | gpl-3.0 | 8,719 | 0.004358 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Radim Rehurek <[email protected]>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Scikit learn interface for :class:`~gensim.models.hdpmodel.HdpModel`.
Follows scikit-learn API conventions to facilitate using gensi... | Path to a directory where topic and options information will be stored.
random_st | ate : int, optional
Seed used to create a :class:`~np.random.RandomState`. Useful for obtaining reproducible results.
"""
self.gensim_model = None
self.id2word = id2word
self.max_chunks = max_chunks
self.max_time = max_time
self.chunksize = chunksize
... |
betrisey/home-assistant | homeassistant/components/media_player/yamaha.py | Python | mit | 7,019 | 0 | """
Support for Yamaha Receivers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.yamaha/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_... | lse
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
receiver_vol = 100 - (volume * 100)
negative_receiver_vol = -receiver_vol
self._receiver.volume = negative_receiver_vol
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player... | te = mute
def turn_on(self):
"""Turn the media player on."""
self._receiver.on = True
self._volume = (self._receiver.volume / 100) + 1
def select_source(self, source):
"""Select input source."""
self._receiver.input = self._reverse_mapping.get(source, source)
def p... |
nishimotz/NVDARemote | addon/globalPlugins/remoteClient/input.py | Python | gpl-2.0 | 3,588 | 0.032609 | import ctypes.wintypes as ctypes
import braille
import brailleInput
import globalPluginHandler
import scriptHandler
import inputCore
import api
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
MAPVK_VK_TO_VSC = 0
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENT_SCANCODE = 0x0008
KEY... | ng),
('mouseData', ctypes.DWORD),
('dwFlags', ctypes.DWORD),
('time', ctypes.DWORD),
('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)),
)
class KEYBDINPUT(cty | pes.Structure):
_fields_ = (
('wVk', ctypes.WORD),
('wScan', ctypes.WORD),
('dwFlags', ctypes.DWORD),
('time', ctypes.DWORD),
('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)),
)
class HARDWAREINPUT(ctypes.Structure):
_fields_ = (
('uMsg', ctypes.DWORD),
('wParamL', ctypes.WORD),
('wParam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.