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 |
|---|---|---|---|---|---|---|---|---|
maciek123/pyage-forams | pyage_forams/solutions/test_foram.py | Python | gpl-2.0 | 263 | 0.007605 | f | rom unittest import TestCase
from pyage.core import inject
from pyage_forams.solutions.foram | import Foram
class TestForam(TestCase):
def test_step(self):
inject.config = "pyage_forams.conf.dummy_conf"
foram = Foram(10)
# foram.step() |
geobricks/Playground | playground/clustering/cluster_internet/plot_u.py | Python | gpl-2.0 | 340 | 0.008824 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def plot_u(u):
fig = plt.figure()
ax = Axes3D(fig)
x = []
y = []
for (i,j),val in np.nde | numerate(u):
x.append(i)
y.append(j)
a | x.plot(xs=x, ys=y, zs=u.flatten(), zdir='z', label='ys=0, zdir=z')
plt.show()
|
jmckaskill/subversion | doc/tools/bin/find-xsl.py | Python | apache-2.0 | 1,187 | 0.007582 | #!/usr/bin/env python
import sys
import os
import glob
#######################################################
candidate_xsldirs = (
# Fedora
'/usr/share/sgml/docbook/xsl-stylesheets',
# Cygwin
'/usr/share/docbook-xsl',
# Debian
'/usr/share/xml/docbook/stylesheet/nwalsh',
# SUSE
'/usr/... | cbook.xsl')):
os.symlink(j, xsl_dir)
print("Found and linked %s" | % j)
sys.exit(0)
sys.stderr.write('ERROR: Failed to find a DocBook XSL directory\n')
sys.exit(1)
|
MJJoyce/climate | ocw/tests/test_dataset.py | Python | apache-2.0 | 8,091 | 0.002225 | # 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... | 2000, 12, 1)))
def test_spatial_resolution(self):
self.assertEqual(self.test_dataset.spatial_resolution(), (2, 2))
def test_temporal_resolution(self):
self.assertEqual(self.test_dataset.temporal_resolution(), 'monthly')
class TestBounds(unittest.TestCase):
def setUp(self):
self.bo... | dt.datetime(2000, 1, 1), # Start time
dt.datetime(2002, 1, 1)) # End time
# Latitude tests
def test_inverted_min_max_lat(self):
with self.assertRaises(ValueError):
self.bounds.lat_min = 81
with self.assertRaises(ValueError):
self.bounds... |
Andy-hpliu/AirtestX | atx/__main__.py | Python | apache-2.0 | 4,930 | 0.004665 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# USAGE
# python -matx -s ESLKJXX gui
import argparse
import functools
import json
import sys
import inspect
from contextlib import contextmanager
import atx.androaxml as apkparse
from atx.cmds import run
from atx.cmds import iosdeveloper
from atx.cmds import install
... | apk(args.filename)
print json.dumps({
'package_name': pkg_name,
'main_activity': activity,
}, indent=4)
def _version(args):
import atx
print atx.version
def main():
ap = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument("... | =False, default='127.0.0.1', help="Adb host")
ap.add_argument("-P", "--port", required=False, type=int, default=5037, help="Adb port")
subp = ap.add_subparsers()
@contextmanager
def add_parser(name):
yield subp.add_parser(name, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
with ... |
tebeka/pythonwise | pandas-validation/populate.py | Python | bsd-3-clause | 1,289 | 0.000776 | #!/usr/bin/env python
'''Populate with dummy data.'''
from pull import cursor
from random import randi | nt, random
from collections import namedtuple
sql = '''
INSERT INTO points (
x
, y
, z
, value
) VALUES (
%s
, %s
, %s
, %s
)'''
Point = namedtuple('Point', ['x', 'y', 'z'])
def rand_coord():
return randint(0, 1000)
def rand_point():
return Point(
rand_coord(),
rand_coo... | while len(coords) < count:
coords.add(rand_point())
return coords
if __name__ == '__main__':
pre_cur = cursor('pre')
post_cur = cursor('post')
points = gen_points(10000)
for point in points:
pre_value = random() * 1000
post_value = pre_value
# In 1% probability, ... |
kharlm/Tuxemon | tuxemon/core/components/technique.py | Python | gpl-3.0 | 9,760 | 0.002869 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tuxemon
# Copyright (C) 2014, William Edwards <shadowapex@gmail.com>,
# Benjamin Bean <superman2k5@gmail.com>
#
# This file is part of Tuxemon.
#
# Tuxemon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | :
self.images.append("animations/technique/" + image)
# Load the sound effect for this technique
sfx_directory = "sounds/technique/"
self.sfx = sfx_directory + r | esults["sfx"]
def advance_round(self, number=1):
""" Advance the turn counters for this technique
Techniques have two counters currently, a "combat counter" and a "life counter".
Combat counters should be reset with combat begins.
Life counters will be set to zero when the Techniqu... |
mkoistinen/django-cms | cms/utils/apphook_reload.py | Python | bsd-3-clause | 3,112 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import sys
import uuid
from threading import local
from django.conf import settings
from django.urls import reverse, clear_url_caches
# Py2 and Py3 compatible reload
from imp import reload
_urlconf_revision = {}
_urlconf_revision_threadlocal = local()... | ttings.DEBUG:
print(" New revision!!!! RELOAD!\n"
" {0} ({1 | })\n"
" -> {2} ({3})".format(
global_revision, type(global_revision),
local_revision, type(local_revision),))
debug_check_url('my_test_app_view')
reload_urlconf(new_revision=global_revision)
debug_check_url('my_test_app_view')
def... |
Fiware/ops.Flavor-sync | flavorsync/database.py | Python | apache-2.0 | 345 | 0.011594 | from flavorsync import config
from fla | sk_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db(app):
if app.config['TESTING']:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DB_TEST_URI']
else:
app.config['SQLALCHEMY_DATABASE_URI'] = co | nfig.DB_URI
db.init_app(app)
db.create_all() |
grandmasterchef/WhatManager2 | bibliotik/trans_sync.py | Python | mit | 3,805 | 0.002628 | import os
import os.path
from django.db import transaction
from bibliotik import manage_bibliotik
from bibliotik.models import BibliotikTransTorrent, BibliotikTorrent
from home.models import LogEntry, DownloadLocation
def sync_instance_db(instance):
b_torrents = instance.get_b_torrents_by_hash()
t_torrents ... | orrents = instance.get_t_torrents_by_hash(BibliotikTransTorrent.sync_t_arguments)
with transaction.atomic():
for c_hash, t_torrent in t_torrents.items():
if c_hash not in b_torrents:
try:
bibliotik_torrent = BibliotikTorrent.objects.get(info_hash=c_hash)
... | _location = DownloadLocation.get_by_full_path(t_torrent.downloadDir)
b_torrent = manage_bibliotik.add_bibliotik_torrent(
bibliotik_torrent.id,
instance,
d_location,
add_to_client=False
... |
locaweb/leela-client | src/python/leela/client/sensors/linux/network.py | Python | apache-2.0 | 1,492 | 0.003351 | #!/usr/bin/python
# -*- coding: utf-8; -*-
#
# 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
#
# Unles... | []
agg = {}
for (k, vs) in psutil.network_io_counters(True).iteritems():
k1 = k.split(":")[0]
| if (k1 not in agg):
agg[k1] = vs
else:
agg[k1] = map(lambda (a,b): a+b, zip(agg[k1], vs))
for (k, vs) in agg.iteritems():
events = map(lambda (k1, v): sensor.Sensor.Value("%s.%s" % (k,k1), v), zip(labels, vs))
result.extend(events)
... |
ikn/wvoas | game/conf.py | Python | gpl-3.0 | 19,522 | 0.001024 | from platform import system
import os
from os.path import sep, expanduser, join as join_path
from collections import defaultdict
import pygame as pg
import settings
from util import ir, dd, split
class Conf (object):
IDENT = 'wvoas'
USE_SAVEDATA = True
USE_FONTS = False
# save data
SAVE = ('CU... |
KEYS_BACK = (pg.K_ESCAPE, pg.K_BACKSPACE)
KEYS_MINIMISE = (pg.K_F10,)
KEYS_FULLSCREEN = (pg.K_F11, (pg.K_RETURN, pg.KMOD_ALT, True),
(pg.K_KP_ENTER, pg.KMOD_ALT, True))
KEYS_LEFT = (pg.K_LEFT, pg.K_a, pg.K_q)
KEYS_RIGHT = (pg.K_RIGHT, pg.K_d, pg.K_e)
KEYS_UP = (pg.K_UP, pg.K... | pg.K_z, pg.K_COMMA)
KEYS_DOWN = (pg.K_DOWN, pg.K_s, pg.K_o)
KEYS_MOVE = (KEYS_LEFT, KEYS_UP, KEYS_RIGHT, KEYS_DOWN)
KEYS_JUMP = (pg.K_SPACE,) + KEYS_UP
KEYS_RESET = (pg.K_r, pg.K_p)
KEYS_VOL_UP = ((pg.K_PLUS, 0, True), (pg.K_KP_PLUS, 0, True),
(pg.K_EQUALS, 0, True))
KEYS_VOL_... |
schenc3/InteractiveROSETTA | InteractiveROSETTA/scripts/antibody.py | Python | gpl-2.0 | 14,153 | 0.005935 | import wx
import wx.grid
import wx.lib.scrolledpanel
import wx.stc
import os
import os.path
import time
import platform
import multiprocessing
import datetime
import Bio.PDB
import webbrowser
from threading import Thread
from tools import *
class AntibodyPanel(wx.lib.scrolledpanel.ScrolledPanel):
def __init__(self... | otein sequence")
if (platform.system() == "Windows"):
self.lblHeavyChain = wx.StaticText(self, -1, "Variable Heavy Chain Sequence:", (10, 200), (320, 20), wx.ALIGN_LEFT)
self.lblHeavyChain.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx. | BOLD))
elif (platform.system() == "Darwin"):
self.lblHeavyChain = wx.StaticBitmap(self, -1, wx.Image(self.parent.parent.scriptdir + "/images/osx/antibody/lblHeavyChain.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap(), pos=(10, 200), size=(320, 20))
else:
self.lblHeavyChain = wx.Static... |
supervasion/EventDetector | prototype/events.py | Python | gpl-3.0 | 4,047 | 0.000988 | import logging
logger = logging.getLogger("supervasion")
class Events(object):
@classmethod
def print_event(cls, kwargs):
logger.info("=======================================")
for k, v in kwargs.iteritems():
logger.info("%s: %s"%(str(k), str(v)))
logger.info("============... | um_frame, time_frame):
cls.print_event({
"Event": "starts_moving",
"Instrument": instrument.name,
| "Time_Frame": time_frame,
"Frame": num_frame
})
@classmethod
def on_towards(cls, instrument, target, num_frame, time_frame):
cls.print_event({
"Event": "on_towards",
"Instrument": instrument.name,
"Target": target.name,
"Time_Frame"... |
github/codeql | python/ql/test/library-tests/classes/attr/test.py | Python | mit | 1,199 | 0.030025 | from undefined import unknown
k = 1
l = []
class OldStyle:
def meth1(self):
pass
a1 = k
a2 = l
a3 = unknown
l = l
class OldStyleDerived(OldStyle):
def meth2(self):
pass
class NewStyle(object):
def meth3(self):
pass
a1 = k
a2 = l
... | pass |
#Ok
class W(Y, x):
pass
class O:
pass
#This is OK
class N(object, O):
pass
#
# Assign builtin objects to class attributes
len = len
ord = 10
class Unhashable(object):
__hash__ = None
class Oddities(object):
int = int
float = float
l = len
h = hash
class Sub(Odditie... |
ddico/account-financial-tools | account_loan/wizard/__init__.py | Python | agpl-3.0 | 184 | 0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
|
from . import accou | nt_loan_generate_entries
from . import account_loan_pay_amount
from . import account_loan_post
|
vialette/ultrastorage | ultrastorage/timeoutgenerator/exponential.py | Python | mit | 487 | 0.00823 | __author__ = 'vialette'
# coding=utf-8
"""Uniform imeout generator: integer uniform distribution
.. moduleauthor:: Stéphane Vialette <vialette@gmail.com>
"""
from .timeoutgenerator import TimeoutGenerator
import numpy
class Exponential(Time | outGenerator):
def __init__(self, scale = 100):
super(self.__class__, self).__init__()
self._scale = scale
def value(self):
"""Random
"""
return numpy.random.exponential(scale=s | elf._scale)
|
fxia22/ASM_xf | PythonD/lib/python2.4/site-packages/display/PIL/WmfImagePlugin.py | Python | gpl-2.0 | 7,556 | 0.001985 | #
# THIS IS WORK IN PROGRESS.
#
# The Python Imaging Library.
# $Id: //modules/pil/PIL/WmfImagePlugin.py#4 $
#
# WMF support for PIL
#
# history:
# 96-12-14 fl Created
#
# notes:
# This code currently supports placable metafiles only, and
# just a few graphics operations are implemented.
#
# Copyr... | (bbox[3]-bbox[1]) / 20
# FIXME: while hacking
self.size = (bbox[2] + bbox[0])/10, (bbox[3] + bbox[1])/10
self.bbox = bbox
# check standard header
s = self.fp.read(18)
if s[:6] != "\001\000\011\000\000\003":
raise SyntaxError, "Not a WMF file"
def _ink(... | p colour in current palette
try:
return self.palette[rgb]
except KeyError:
# hmm. what if the palette becomes full?
ink = len(self.palette)
self.palette[rgb] = ink
return ink
def load(self):
if self.im:
return
... |
sgillies/Fiona | tests/test_crs.py | Python | bsd-3-clause | 1,622 | 0.010481 |
from fiona import crs
def test_proj_keys():
assert len(crs.all_proj_keys) == 85
assert 'proj' in crs.all_proj_keys
assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_d... | no_defs': True, 'foo': True, 'axis': False, 'belgium': [1,2] }
assert crs.to_string(
val) == "+datum=WGS84 +ellps=WGS84 +no_defs +proj=longlat"
def test_to_string_ut | m():
# Make a string from a mapping with a few bogus items
val = {
'proj': 'utm', 'ellps': 'WGS84', 'zone': 13,
'no_defs': True, 'foo': True, 'axis': False, 'belgium': [1,2] }
assert crs.to_string(
val) == "+ellps=WGS84 +no_defs +proj=utm +zone=13"
def test_from_epsg():
val = c... |
thopiekar/Uranium | tests/Settings/TestSettingFunction.py | Python | lgpl-3.0 | 6,234 | 0.01572 | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
import pytest
from UM.Settings.SettingFunction import SettingFunction
## Individual test cases for the good setting functions.
#
# Each test will be executed with each of these functions. These functions are
# all... | # Empty string.
"os.read(os.open(\"/etc/passwd\", os.O_RDONLY), 10)", # Function that reads your passwords from your system.
"exec(\"os.read(os.open(\\\"/etc/passwd\\\", os.O_RDONLY), 10)\")", # Obfuscated function that reads your passwords from your system.
... | ns. Id est they should
# give an error when creating the fixture.
@pytest.fixture(params = setting_function_bad_data)
def setting_function_bad(request):
return SettingFunction(request.param)
## Tests the initialisation of setting functions with good functions.
#
# Each of these should create a good function.
... |
spaceone/pyjs | examples/kitchensink/sink/Frames.py | Python | apache-2.0 | 522 | 0.011494 | from pyjamas.ui.Sink import Sink, SinkInfo
from pyjamas.ui.Frame import Frame
class Frames(Sink):
def __init__(self):
Sink.__init__(self)
self.frame=Frame(self.baseURL() + "rembrandt/LaMarcheNocturne.html")
| self.frame.setWidth("100%")
self.frame.setHeight("48em")
self.initWidget(self.frame)
def init():
text="If you need to include multiple pages of good ol' static HTML, it's easy to do using the <code> | Frame</code> class."
return SinkInfo("Frames", text, Frames)
|
r-icarus/openstack_microserver | openstack_dashboard/dashboards/project/vpn/tests.py | Python | apache-2.0 | 12,792 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Mirantis 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
#
#... | permissions and limitations
# unde | r the License.
#
# @author: Tatiana Mazur
from mox import IsA # noqa
from django.core.urlresolvers import reverse # noqa
from django.core.urlresolvers import reverse_lazy # noqa
from django import http
from horizon.workflows import views
from openstack_dashboard import api
from openstack_dashboard.test import he... |
JennyChi/Script-helper | DataGen/file_simple_event.py | Python | apache-2.0 | 2,096 | 0.020515 | ## file_simple_event.py
# Author: Chen-Ning (Jenny) Chi
# Date: 2011 Sep
###########################################################
## The program will generate & input simple event.
# Support files & directory.
# Could specify what's the file to input events if the file is already exieted in the same folder.
# C... | = "line " + str(counter) + " "
input_message = input_message + time.asctime(time.localtime()) + " "
input_message = input_message + "counter=" + str(counter) + ", "
input_message = input_message + | "state=" + str(random.randrange(0, 9, 1)) + ", "
input_message = input_message + "ip=140.116." + str(random.randrange(0, 255, 1)) + "." + str(random.randrange(0, 255, 1)) + "\n"
file_out = open(data, 'a')
file_out.write(input_message)
file_out.close()
size = size + len(input_message)
if (counter%frequenc... |
streamlink/streamlink | src/streamlink/plugins/tvp.py | Python | bsd-2-clause | 1,684 | 0.001781 | """
$url tvpstream.vod.tvp.pl
$type live
$region Poland
"""
import logging
import re
from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r'https?:/... | ps://www.tvp.pl/sess/tvplayer.php?object_id={0}&autoplay=true'
_stream_re = re.compile(r'''src:[" | '](?P<url>[^"']+\.(?:m3u8|mp4))["']''')
_video_id_re = re.compile(r'''class=["']tvp_player["'][^>]+data-video-id=["'](?P<video_id>\d+)["']''')
def get_embed_url(self):
res = self.session.http.get(self.url)
m = self._video_id_re.search(res.text)
if not m:
raise PluginError('... |
leighpauls/k2cro4 | tools/swarm_client/PRESUBMIT.py | Python | bsd-3-clause | 1,409 | 0.009226 | # 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.
"""Top-level presubmit script for swarm_client.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit... | i.canned_checks.RunPylint(input_api, output_api))
finally:
sys.path = sys_path_backup
output.extend(
input_api.canned_checks.RunUnitTestsInDirectory(
input_api, output_api,
input_api.os_path.join(input_api.PresubmitLocalPath(), 'tests'),
whitelist=[r'.+_test\.py$']))
if i... | rojectChecks(input_api,
output_api,
owners_check=False))
return output
def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_ap... |
Crobisaur/HyperSpec | Python/runSpectral.py | Python | gpl-3.0 | 1,039 | 0.014437 | def runSpectral(dcb, gt):
(classes, gmlc, clmap) = runGauss(dcb, gt)
v0 = imshow(classes=clmap)
(gtresults, gtErrors) = genResults(clmap, gt)
v1 = imshow(classes=gtresults)
v2 = imshow(classes=gtErrors)
return (gtresults, gtErrors)
def runPCA(dcb, gt):
pc = principal_components(dcb)
pc_... | img_pc = pc_0999.transform(dcb)
(classes, gmlc, clmap) = run | Gauss(img_pc, gt)
def genResults(clmap, gt):
gtresults = clmap * (gt!=0)
gtErrors = gtresults * (gtresults !=gt)
return (gtResults, gtErrors)
def runGauss(dcb, gt):
classes = create_training_classes(dcb, gt)
gmlc = GaussianClassifier(classes, min_samples=200)
clmap = gmlc.classify_image(dcb)
... |
jeremiahyan/odoo | addons/sale/models/account_move_line.py | Python | gpl-3.0 | 11,377 | 0.004219 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_is_zero
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
sale_line_ids = ... | s_to_create` (not existing case, which will happen more often th | an the first one).
map_move_sale_line = {}
for move_line in self:
sale_order = sale_order_map.get(move_line.id)
# no reinvoice as no sales order was found
if not sale_order:
continue
# raise if the sale order is not currenlty open
... |
neillc/thbs600 | publishconf.py | Python | gpl-3.0 | 534 | 0.005618 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.a | ppend(os.curdir)
from pelicanconf import *
SITEURL = 'http://thbs600.neill.id.au'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = True
# Followi | ng items are often useful when publishing
#DISQUS_SITENAME = ""
#GOOGLE_ANALYTICS = ""
|
nagyistoce/netzob | src/netzob/Common/Type/Format.py | Python | gpl-3.0 | 3,917 | 0.010989 | # -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocol... | , Format.DECIMAL, Format.HEX, Format.STRING, Format.IPv4]
@staticmethod
#+---------------------------------------------------------------------------+
#| getExtendedSupportedFormats:
#| Returns an array composed of the names of all supported formats
#| | for the visualization of messages
#+---------------------------------------------------------------------------+
def getExtendedSupportedFormats():
return [Format.BINARY, Format.OCTAL, Format.DECIMAL, Format.HEX, Format.STRING, Format.IP]
@staticmethod
def getUnitSize(format):
if format... |
Fillll/reddit2telegram | reddit2telegram/channels/tech_receiver/app.py | Python | mit | 2,506 | 0.002793 | #encoding:utf-8
import pymongo
import yaml
import utils
from utils import SupplyResult
from utils.tech import get_dev_channel, short_sleep
subreddit = 'all'
t_channel = '@r_channels'
SETTING_NAME = 1
def send_post(submission, r2t):
config_filename = 'configs/prod.yml'
with open(config_filename) as confi... | ].lower():
continue
new_channel_name = lines[1].split(': ')[-1]
new_subreddit = lines[2].split('/')[-1]
new_tags = lines[3].split(': ')[-1]
utils.channels_stuff.set_new_channel(new_channel_name, subreddit=new_subreddit, tags=new_tags)
settings.find_on... | 'last_update': last_update
}
}
)
# It's not a proper supply, so just stop.
return SupplyResult.STOP_THIS_SUPPLY
|
pypyr/pypyr-cli | tests/arbpack/arbmutatingstep.py | Python | apache-2.0 | 142 | 0 | """Smoke test step that mutates context."""
def run_step(context):
"""Mutate context inside step."""
| context['inside_step | '] = 'arb'
|
cayman/decision | server/application/requests/link.py | Python | mit | 1,054 | 0.018027 | from flask import jsonify, request
from application import app, db
from application.dto.link import LinkDTO
from application.models.link import Link
@app.route('/api/links',met | hods=['GET'])
def get_links():
#sql
_links = Link.query.all()
#dto
links = LinkDTO.create_list(_links)
return jsonify([link.json() for link in links])
@app.route('/api/link | s',methods=['POST'])
def create_links():
link = LinkDTO(json=request.get_json())
print(link)
assert link.id>0,'wrong link.id'
#sql
db.session.add(link.model())
db.session.commit()
_link = Link.query.get(link.id)
#dto
link = LinkDTO(_link)
return jsonify(link.json())
@app.ro... |
thobbs/cassandra-dtest | repair_tests/incremental_repair_test.py | Python | apache-2.0 | 14,693 | 0.001838 | import os
import time
from collections import Counter
from re import findall
from unittest import skip
from cassandra import ConsistencyLevel
from ccmlib.common import is_win
from ccmlib.node import Node
from nose.plugins.attrib import attr
from assertions import assert_almost_equal, assert_one
from dtest import Test... | {'start_rpc': 'true'}
# Ignore these log patterns:
self.ignore_log_patterns = [
r'Can\'t send migration request: node.*is down',
]
Tester.__init__(self, *args, **kwargs)
def sstable_marking_test(self):
"""
* Launch a three node cluster
* Stop node... | ows with stress
* Start node3
* Issue an incremental repair, and wait for it to finish
* Run sstablemetadata on every node, assert that all sstables are marked as repaired
"""
cluster = self.cluster
# hinted handoff can create SSTable that we don't need after node3 restar... |
cloudtools/awacs | awacs/shield.py | Python | bsd-2-clause | 2,682 | 0.000746 | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Shield"
prefix = "shield"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super(... | account: str = "") -> None:
super().__init__(
service=prefix, | resource=resource, region=region, account=account
)
AssociateDRTLogBucket = Action("AssociateDRTLogBucket")
AssociateDRTRole = Action("AssociateDRTRole")
AssociateHealthCheck = Action("AssociateHealthCheck")
AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails")
CreateProtection ... |
dehora/parsel | plymouth/__init__.py | Python | apache-2.0 | 22 | 0 | __author__ | = ' | dehora'
|
ericpp/hippyvm | hippy/objects/iterator.py | Python | mit | 1,367 | 0.001463 |
from hippy.objects.base import W_Root
class W_BaseIterator(W_Root):
def done(self):
return self.finished
def next(self, space):
raise NotImplementedError
def next_item(self, space):
raise NotImplementedError
class W_InstanceIterator(W_BaseIterator):
def __init__(self, space... | w_val = self.w_current.call_args(interp, [])
w_key = self.w_key.call_args(interp, [])
return w_key, w_val
def done(self):
interp = self.space.ec.interpreter
if self.w_next is None:
self.w_next = interp.getmeth(self.w_inst, "next")
else:
self.w... | l_args(interp, [])
w_res = self.w_valid.call_args(interp, [])
return not self.space.is_true(w_res)
|
prasanna08/oppia | core/domain/rating_services_test.py | Python | apache-2.0 | 8,107 | 0.00074 | # coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | .save_new_exploration(
exp_id_b,
exp_domain.Exploration.create_default_exploration(exp_id_b))
rating_services.assign_rating_to_exploration(
self.USER_ID_1, exp_id_a, 1)
rating_services.assign_rating_to_exploration(
self.USER_ID_1, exp_id_b, 3)
rat... | ating_services.assign_rating_to_exploration(
self.USER_ID_2, exp_id_b, 5)
self.assertEqual(
rating_services.get_user_specific_rating_for_exploration(
self.USER_ID_1, exp_id_a), 1)
self.assertEqual(
rating_services.get_user_specific_rating_for_explorat... |
rawjam/django-allauth | allauth/socialaccount/providers/google/views.py | Python | mit | 2,159 | 0.003242 | from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from allauth.socialaccount import requests
from allauth.socialaccount.models import SocialLog... | r_model
from provider import GoogleProvider
User = get_user_model()
class GoogleOAuth2Adapter(OAuth2Adapter):
provider_id = GoogleProvider.id
access_token_url = 'https://accounts.google.com/o/oauth2/token'
authorize_url = 'https://accounts.google.com/o/oauth2/auth'
profile_url = 'https://www.googleap... | { 'access_token': token.token,
'alt': 'json' })
extra_data = resp.json
# extra_data is something of the form:
#
# {u'family_name': u'Penners', u'name': u'Raymond Penners',
# u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAA... |
linpingchuan/misc | python/ml/book1/ch5/DecisionTree1.py | Python | gpl-2.0 | 3,331 | 0.02016 | # coding:utf-8
import numpy as np
def calcShannonEnt(dataSet):
numEntries=len(dataSet)
labelCounts={}
for fectureVec in dataSet:
currentLabel=fectureVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel]=0
labelCounts[currentLabel]+=1
shannonEnt... | foGain
bestFeature=i
return bestFeature
def majorityCnt(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys():
classCount[vote]=0
classCount[vote]+=1
import operator
sortedClassCo | unt=sorted(classCount.iteritems(),
key=operator.itemgetter(1),
reverse=True)
return sortedClassCo
def createTree(dataSet,labels):
classList=[example[-1] for example in dataSet]
if classList.count(classList[0]==len(classList)):
return classList[... |
huangciyin/youtube-dl | youtube_dl/extractor/noco.py | Python | unlicense | 3,451 | 0.002028 | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unified_strdate,
compat_str,
)
class NocoIE(InfoExtractor):
_VALID_URL = r'http://(?:(?:www\.)?noco\.tv/emission/|player\.noco\.tv/\?idvideo=)(?P<id>\d+)'
... | json(
'https://api.noco.tv/1.0/video/medias/%s' % video_id, video_id, 'Downloading video JSON')
formats = []
for fmt in medias['fr']['video_list']['default']['quality_list']:
format_id = fmt['quality_key']
file = self._download_json(
'https://api.no... | video_id, 'Downloading %s video JSON' % format_id)
file_url = file['file']
if not file_url:
continue
if file_url == 'forbidden':
raise ExtractorError(
'%s returned error: %s - %s' % (
self.IE_NAME, file[... |
NickDaly/GemRB-FixConfig-Branch | gemrb/GUIScripts/bg1/GUICG3.py | Python | gpl-2.0 | 3,229 | 0.024775 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 versi... | ut even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth... | nt (GUICG3)
import GemRB
from GUIDefines import *
from ie_stats import *
import CharGenCommon
import GUICommon
import CommonTables
AlignmentWindow = 0
TextAreaControl = 0
DoneButton = 0
AlignmentTable = 0
def OnLoad():
global AlignmentWindow, TextAreaControl, DoneButton
global AlignmentTable
if GUICommon.CloseOt... |
dbrgn/django-messagegroups | messagegroups/tests.py | Python | mit | 1,270 | 0.00315 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import unittest
from django.contrib.messages import DEFAULT_TAGS
from django.contrib.messages import constants
from templatetags.messagegroups import render_messages
class MessagegroupsTest(unittest.TestCase)... | as been done correctly."""
e1 = self.FakeMessage(constants.ERROR, DEFAULT_TAGS[constants.ERROR], 'error1')
e2 = self.FakeMes | sage(constants.ERROR, DEFAULT_TAGS[constants.ERROR], 'error2')
i1 = self.FakeMessage(constants.INFO, DEFAULT_TAGS[constants.INFO], 'info1')
other = self.FakeMessage(99, 'crazy', 'crazy1')
groups = render_messages([e1, e2, i1, other])
self.assertEqual(groups, {'messages': {
(... |
DnPlas/CalamariExamples | Python/calamari_rgb.py | Python | gpl-3.0 | 837 | 0.029869 | import mraa as m
class Rgb(object):
def __init__(self):
self.r = m.Gpio(21)
self.g = m.Gpio(23)
self.b = m.Gpio(26)
self.r.dir(m.DIR_OUT)
self.g.dir(m.DIR_OUT)
self.r.dir(m.DIR... | self.off()
def off(self):
self.r.write(0)
self.g.write(0)
self.b.wr | ite(0)
def on(self,led):
if led is 'red':
self.r.write(1)
self.g.write(0)
self.b.write(0)
elif led is 'green':
self.g.write(1)
self.r.write(0)
self.b.write(0)
elif led is 'blue':
self.b.wr... |
starnight/python-c-extension | 01-HeyMan/test.py | Python | bsd-3-clause | 130 | 0.023077 | #!/usr/bin/env pytho | n3
import helloworld
print(helloworld.hello());
print(helloworld.heyman(5, "StarNight"));
help(hell | oworld);
|
StrellaGroup/erpnext | erpnext/patches/v12_0/create_default_energy_point_rules.py | Python | gpl-3.0 | 195 | 0.020513 | import frappe
from e | rpnext.setup.install import create_default_energy_point_rules
def execute():
frappe.reload_doc('social', 'doctype', 'energy_point_rule')
create_default_e | nergy_point_rules() |
mumuwoyou/vnpy-master | vnpy/api/huobi/__init__.py | Python | mit | 56 | 0.017857 | # | encoding: UTF-8
from vnhuobi import TradeApi, DataAp | i |
Snifer/BurpSuite-Plugins | faraday/plugins/repo/acunetix/plugin.py | Python | gpl-2.0 | 9,521 | 0.012184 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Faraday Penetration Test IDE - Community Version
Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information
'''
from __future__ import with_statement
from plugins import core
from model import api
import re
im... | Write custom parser | to just read the nodes that we need instead of
reading the whole file.
@return xml_tree An xml tree instance. None if error.
"""
try:
tree = ET.fromstring(xml_output)
except SyntaxError, err:
print "SyntaxError: %s. %s" % (err, xml_output)
ret... |
bponsler/pysiriproxy | pysiriproxy/objects/baseObject.py | Python | gpl-3.0 | 5,552 | 0.001981 | # Copyright (C) 2012 Brett Ponsler, Pete Lamonica
# This file is part of pysiriproxy.
#
# pysiriproxy 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 ... | gumentNames:
# Get the value of th | e local argument
argValue = localVars.get(argName)
# Only set the argument if its value is not None
if argValue is not None:
setattr(self, argName, argValue)
def toDict(self):
'''Convert this object into a Python dictionary.'''
dictionary = {
... |
maroux/django-relationships | relationships/compat.py | Python | mit | 563 | 0.001776 | import django
# Django 1.5 add support for custom auth user model
from django.conf import | settings
if django.VERSION >= (1, 5):
AUTH_USER_MODEL = settings.AUTH_USER_MODEL
else:
try:
from django.contrib.auth.models import User
AUTH_USER_MODEL = 'auth.User'
except ImportError:
raise ImportError(u"User model is not to be found.")
# location of patterns, url, include chang... | nf.urls import patterns, url, include
except:
from django.conf.urls.defaults import patterns, url, include
|
solominh/python-stardict | test.py | Python | gpl-3.0 | 1,187 | 0.000842 | from dictutils import find_installed_dictionaries_paths
from app import StarDict, DictionarySettings
import time
DICTS_DIRPATH = './dicts'
SETTINGS_DIRPATH = './settings'
def test():
settings = DictionarySettings(DICTS_DIRPATH, SETTINGS_DIRPATH)
s | tardict = StarDict(settings)
word_str_list = ['hello', 'hi', 'happy', 'animal', 'elephant']
for word_str in word_str_list:
enabled_dictionaries_definitions = stardict.get_definitions_from_enabled_dictionaries(
word_str)
for dictionary, definitions in enabled_dictionaries_definitions... | for k, v in definition.items():
print(v.decode('utf-8', errors='ignore'))
print('*******************************************')
time.sleep(3)
def install_dictionaries():
settings = DictionarySettings(DICTS_DIRPATH, SETTINGS_DIRPATH)
installed_dictionaries_paths = find_... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_chart_line02.py | Python | bsd-2-clause | 1,364 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_compar | ison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_line02.xlsx')
self.ignore_elements = {'xl/workbo... |
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})
chart.axis_ids = [63593856, 63612032]
chart.axis2_ids = [63615360, 63613568]
data = [
[1, 2, 3, 4, 5],
[6, 8, 6, 4, 2]
]
worksheet.write_column('A1', dat... |
softlayer/softlayer-python | SoftLayer/CLI/user/create.py | Python | mit | 3,968 | 0.00252 | """Creates a user """
# :license: MIT, see LICENSE for more details.
import json
import string
import sys
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
@click.command()
@click.argument(... | provided in --template "
"supersedes this template.")
@click.option('--template', '-t', default=None,
help="A json string describing https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer/")
@environment.pass_env
def cli(env, username, email, password, from_user, templa... | te my@email.com -e my@email.com -p generate -a
-t '{"firstName": "Test", "lastName": "Testerson"}'
"""
mgr = SoftLayer.UserManager(env.client)
user_mask = ("mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, "
"state, userStatusId, timezoneId]")... |
ChinaMassClouds/copenstack-server | deploy/src/mplatform/utils/log.py | Python | gpl-2.0 | 2,418 | 0.000827 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# log.py - Copyright (C) 2013 Red Hat, Inc.
# Written by Fabian Deutsch <fabiand@redhat.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 Software Foundation; version... | e)10s %(asctime)s %(pathname)s:%(l | ineno)s:%(funcName)s: \
%(message)s
""")
logging.debug("Setting log config to: %s" % mixedfile)
logging.config.fileConfig(mixedfile, disable_existing_loggers=False)
def getLogger(name=None):
if not getLogger._logger:
if not logging.getLogger().handlers:
configure_logging()
... |
JustinWingChungHui/MyFamilyRoot | auth_api/tests.py | Python | gpl-2.0 | 5,613 | 0.006414 | from django.test import TestCase
from django.test.utils import override_settings
from rest_framework import status
from rest_framework.test import APIClient
from axes.signals import user_locked_out
import json
import time
from family_tree.models.family import Family
from family_tree.models.person import Person
from cu... | self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_api_schema_loads(self):
client = APIClient(HTTP_X_REAL_IP='127.0.0.1')
client.force_authenticate(user=self.user)
response = client.get('/api/schema/')
self.assertEq | ual(response.status_code, status.HTTP_200_OK)
|
ESOedX/edx-platform | openedx/core/djangoapps/schedules/migrations/0006_scheduleexperience.py | Python | agpl-3.0 | 793 | 0.003783 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedules', '0005_auto_20171010_1722'),
]
operations = [
migrations.CreateModel(
name='Schedule... | lds=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('experience_type', models.PositiveSmallIntegerField(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])),
| ('schedule', models.OneToOneField(related_name='experience', to='schedules.Schedule', on_delete=models.CASCADE)),
],
),
]
|
wiseman/energid_nlp | energid_nlp/generation.py | Python | bsd-2-clause | 1,810 | 0.012707 | # Copyright 2012 Energid Technologies
from energid_nlp import logic
GENERATION_PROPOSITION = '$generate'
class Error(Exception):
pass
class Generator:
def __init__(self, kb):
self.kb = kb
def generate_prim(self, concept):
if isinstance(concept, logic.Description):
return self.generate_prim(c... | in case slots in template
# couldn't be | filled.
return result_string.strip()
|
flavour/iscram | modules/eden/cms.py | Python | mit | 12,806 | 0.01062 | # -*- coding: utf-8 -*-
""" Sahana Eden Content Management System Model
@copyright: 2012 (c) Sahana Software Foundation
@license: MIT
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 S... | T = current.T
db = current.db
s3 = current.response.s3
add_component = self.add_component
comments = s3.c | omments
configure = self.configure
crud_strings = s3.crud_strings
define_table = self.define_table
meta_fields = s3.meta_fields
roles_permitted = s3.roles_permitted
# ---------------------------------------------------------------------
# Series
# - lists... |
gsson/soaplib | soaplib/ext/comproxy.py | Python | lgpl-2.1 | 9,149 | 0.001749 | '''
COM Bridge for SOAP Services
============================
This soaplib extension provides a simple COM bridge for accessing SOAP web
services, especially soaplib web services, via a COM-compliant language. It
was developed primarily for use with standard Windows VBScript/VBA.
To use the COM bridge to access a we... | e_date_time(member)
elif type(member) in [types.ListType, types.TupleType]:
newmember = []
for item in member:
if type(item).__name__ == 'PyIDispatch':
item = unwrap_complex_type(item, membertype.serializer)
newmember.append(item)
... | e.soap_members.items():
member = getattr(data, membername)
if isinstance(member, ClassSerializer):
member = wrap_complex_type(member, membertype)
elif type(member) in [types.ListType, types.TupleType]:
newmember = []
for item in member:
if isin... |
pyspace/test | pySPACE/missions/nodes/preprocessing/window_func.py | Python | gpl-3.0 | 6,789 | 0.008249 | """ Multiply a signal with a window """
import warnings
import numpy
# These imports are all for loading the functions.yaml file for the abbreviations of functions for benchmarking.
# Kept here local for debugging and because the file is just used in this node.
# Maybe this will change.
try:
import os
import ... | function itself
pass
se | lf.set_permanent_attributes(window_function_str = window_function_str,
reduce_window = reduce_window,
num_of_samples = None,
window_array = None)
def create_window_array(self):
""" Create a per... |
AWegnerGitHub/IRVING | irving/dashboard/views.py | Python | gpl-2.0 | 14,966 | 0.031338 | from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson
from django.conf import settings
from models import *
from functions i... | db.backends.mysql.base.DatabaseWrapper:
resultcount = myCursor.fetchall()
response_dict['resultsetcount'] = intcomma(len(resultcount))
response_dict['resultsetcmp'] = len(resul | tcount)
response_dict['success'] = True
elif type(connections[system_db]) == sqlserver_ado.base.DatabaseWrapper:
resultcount = myCursor.fetchall()
response_dict['resultsetcount'] = intcomma(len(resultcount))
response_dict['resultsetcmp'] = len(resultcount)
response_dict['success'] = ... |
skosukhin/spack | var/spack/repos/builtin/packages/wxpropgrid/package.py | Python | lgpl-2.1 | 1,938 | 0.001032 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | et control for wxWidgets. In
other words, it is a specialized two-column grid for editing
properties such as strings, numbers, flagsets, string arrays,
and colours."""
homepage = "http://wxpropgrid.sourceforge.net/"
url = "http://prdownloads.sourceforge.net/wxpropgrid/wxpropgrid-1.4.15... | .tar.gz"
version('1.4.15', 'f44b5cd6fd60718bacfabbf7994f1e93')
depends_on("wx")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix, "--with-wxdir=%s" %
spec['wx'].prefix.bin, "--enable-unicode")
make()
make("install")
|
tensorflow/tensorflow | tensorflow/python/feature_column/sequence_feature_column_integration_test.py | Python | apache-2.0 | 5,669 | 0.002999 | # Copyright 2018 The TensorFlow 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 applica... | }
}
}
}
feature_list {
key: "int_list"
value {
feature {
int64_list {
value: 2
value: 2
}
}
feature {
int64_list {
value: 4
value: 4
value: 4
value: 4
}
}
feature {
... | }
}
}
"""
def _make_sequence_example():
example = example_pb2.SequenceExample()
return text_format.Parse(_SEQ_EX_PROTO, example)
if __name__ == '__main__':
test.main()
|
AA33/dsa_exp | bst_misc/interval_tree.py | Python | gpl-3.0 | 4,223 | 0.004499 | __author__ = 'aanurag'
import sys
from binary_tree import BinaryTree
class IntervalTree(BinaryTree):
def __init__(self):
BinaryTree.__init__(self)
self.max = None
def insert(self, key, parent=None):
try:
if (self.key == None):
self.key = key
... | ght == None:
self.key = None
# only right subtree
elif self.left == None:
node = self.right
self.key = node.key
self.left = node.left
self.right = node.right
if self.left:
self.lef... | if self.right:
self.right.parent = self
#only left subtree
elif self.right == None:
node = self.left
self.key = node.key
self.left = node.left
self.right = node.right
if self.left:
... |
gitpan/hyperic-sigar | bindings/python/sigar.py | Python | gpl-2.0 | 21 | 0 | from _siga | r im | port *
|
ewheeler/rapidpro | temba/triggers/urls.py | Python | agpl-3.0 | 79 | 0 | from | .views import TriggerCRUDL
urlpatterns = TriggerCRUDL().as_urlpatt | erns()
|
drunkard/lazycat | dm/model/greenway.py | Python | gpl-2.0 | 1,962 | 0 | """
Default settings for Greenway
"""
proto = 'telnet'
port = 23
vendor = 'greenway'
username_hint = 'Login:'
username = 'admin'
password_hint = 'Password:'
password = '' # set in etc/dev.py
password_wrong = 'Invalid user name or password'
prompt = '>'
|
# priviledge escalating things
escalating_needed = [
'show_config_command',
'upload_config_command'
'upload_config_command2'
]
escalating_going = 0 # we are escalating privilege
escalating_command = 'enable'
escalating_hint = 'Password:'
escalating_password = '' # set in etc/ | dev.py
escalating_password_wrong = 'Invalid password'
# configuration session is exclusive.
escalating_conflict_hint = 'configuration is locked by other user'
escalating_conflicted = 0
escalated_prompt = '#'
escalated = 0 # set to 1 while escalated successfully
# exit commands
exit_escalated = 'exit'
exit_os = 'qui... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/samplers/decorators.py | Python | agpl-3.0 | 1,626 | 0.00123 | """This module implement decorators for wrapping data sources so as to
simplify their construction and attribution of properties.
"""
import functools
def data_source_generator(name=None, **properties):
"""Decorator for applying to a simple data source which directly
returns an iterable/generator with the me... | return _properties
return _decorator
d | ef data_source_factory(name=None, **properties):
"""Decorator for applying to a data source defined as a factory. The
decorator can be applied to a class or a function. The class
constructor or function must accept arguments of 'settings', being
configuration settings for the data source, and 'environ' ... |
TEJESH/gandhi | goodreads/request.py | Python | mit | 1,054 | 0 | import requests
import xmltodict
import json
class GoodreadsRequestException(Exception):
def __init__(self, error_msg, url):
self.error_msg = error_msg
self.url = url
def __str__(self):
return self.url, ':', self.error_msg
class GoodreadsRequest():
def __init__(self, client, pat... | self.params = query_dict
self.params.update(client.query_dict)
self.host = client.base_url
self.path = path
self.req_format = req_format
def request(self):
resp = requests.get(self.host+self.path, params=self.params)
if resp.status_code != 200:
raise Go... | elif self.req_format == 'json':
return json.loads(resp.content)
else:
raise Exception("Invalid format")
|
atlefren/beerdatabase | web/util.py | Python | mit | 309 | 0.003236 | # -* | - coding: utf-8 -*-
import re
RATEBEER_BASE_URL = 'http://www.ratebeer.com/beer'
def ratebeer_url(ratebeer_id, short_name):
fixed_name = re.sub(
'[^A-Za-z0-9\-]+',
'',
short_name.replace(' ', '-')
)
return "%s/%s/%s/ | " % (RATEBEER_BASE_URL, fixed_name, ratebeer_id)
|
erdc/proteus | proteus/tests/cylinder2D/sbm_3Dmesh/pressureInitial_n.py | Python | mit | 1,224 | 0.008987 | from proteus import *
from proteus.default_n import *
from pressureInitial_p import *
triangleOptions = triangleOptions
femSpaces = {0:pbasis}
stepController=FixedStep
#numericalFluxType = NumericalFlux.ConstantAdvection_Diffusion_SIPG_exterior #weak boundary conditions (upwind ?)
matrix = LinearAlgebraTools.Spars... | = KSP_petsc4py
levelLinearSolver = KSP_petsc4py
parallelPartitioningType = parallelPartitioningType
nLayersOfOverlapForParallel = nLay | ersOfOverlapForParallel
nonlinearSmoother = None
linearSmoother = None
numericalFluxType = NumericalFlux.ConstantAdvection_exterior
linear_solver_options_prefix = 'pinit_'
multilevelNonlinearSolver = NonlinearSolvers.Newton
levelNonlinearSolver = NonlinearSolvers.Newton
#linear solve rtolerance
linTolFa... |
defcello/Children-of-Eden-Synth-Server | src/engine/mididevice.py | Python | gpl-3.0 | 10,822 | 0.016081 | ####################################################################################################
# Copyright 2013 John Crawford
#
# This file is part of PatchCorral.
#
# PatchCorral is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | n list((port, midi.getPortName(port)) for port in range(midi.getPortCount()))
##
# Class representing a specific MIDI voice.
class MIDIVoice():
tags = [
'name',
'msb',
'lsb',
'_pc',
'device.portNum',
'device.portName',
'channel',
'category',
'voiceNum',
]
##
# Class cons... | name String
# @param device MIDIOutDevice object
# @param channel MIDI Channcel (1-16)
# @param msb Most Significant Bit
# @param lsb Least Significant Bit
# @param pc Program Change value
# @param category Category of the voice
# @param voiceNum Number of the voice as displayed on the device
def... |
onitake/ansible | lib/ansible/plugins/connection/netconf.py | Python | gpl-3.0 | 11,419 | 0.002715 | # (c) 2016 Red Hat Inc.
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_impo | rt, division, pri | nt_function)
__metaclass__ = type
DOCUMENTATION = """
---
author: Ansible Networking Team
connection: netconf
short_description: Provides a persistent connection using the netconf protocol
description:
- This connection plugin provides a connection to remote devices over the
SSH NETCONF subsystem. This connecti... |
Nikita1710/ANUFifty50-Online-Mentoring-Platform | project/fifty_fifty/blog/urls.py | Python | apache-2.0 | 195 | 0 | from django.co | nf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk | >\d+)/$', views.post_detail, name='post_detail'),
]
|
mondada/pybsdp | interfaces.py | Python | mit | 970 | 0.005155 | # Use those functions to enumerate all interfaces available on the system using Python.
# found on <http://code.activestate.com/recipes/439093/#c1>
import so | cket
import fcntl
import struct
import array
def all_interfaces():
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno()... | tostring()
lst = []
for i in range(0, outbytes, 40):
name = namestr[i:i+16].split('\0', 1)[0]
ip = format_ip(namestr[i+20:i+24])
lst.append((name, ip))
return lst
def format_ip(addr):
return str(ord(addr[0])) + '.' + \
str(ord(addr[1])) + '.' + \
str(or... |
rht/zulip | zerver/migrations/0087_remove_old_scheduled_jobs.py | Python | apache-2.0 | 869 | 0.001151 | # Generated by Django 1.10.5 on 2017-05-10 05:59
from django.db import migrations
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db.migration | s.state import StateApps
def delete_old_scheduled_jobs(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation... | rver", "ScheduledJob")
ScheduledJob.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
("zerver", "0086_realm_alter_default_org_type"),
]
operations = [
migrations.RunPython(delete_old_scheduled_jobs, elidable=True),
]
|
liulion/mayavi | examples/mayavi/zzz_reader.py | Python | bsd-3-clause | 1,778 | 0.014623 | """This is a simple example that shows how to create a reader factory
and register that reader with mayavi.
To use this:
- put this in ~/.mayavi2/
- then import this module in your ~/.mayavi2/user_mayavi.py.
that's it.
What you should get:
- Options to ope | n .zzz files from the file->open menu.
- Open .zzz files via right click.
- Open .zzz files from the engine or mlab (via open)
- do mayavi2 -d foo.zzz.
"""
from mayavi.core.api import registry, SourceMetadata, PipelineInfo
def zzz_reader(fname, engine):
"""Reader for .zzz files.
Parameters:
... | Filename to be read.
engine -- The engine the source will be associated with.
"""
from tvtk.api import tvtk
from mayavi.sources.vtk_data_source import VTKDataSource
# Do your own reader stuff here, I'm just reading a VTK file with a
# different extension here.
r = tvtk.StructuredPointsRead... |
cmc333333/regulations-core | regcore/migrations/0013_remove_models.py | Python | cc0-1.0 | 729 | 0 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db impor | t migrations
class Migration(migrations.Migration):
dependencies = [
('regcore', '0012_migrate_documents'),
]
operations = [
migrations.DeleteModel(
name='Preamble',
),
migrations.AlterUniqueTogether(
name='regulation',
unique_together=... |
airbnb/caravel | superset/utils/core.py | Python | apache-2.0 | 35,717 | 0.000588 | # 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... | uated.
Define ``watch`` as a tuple of attribute names if this Decorator
should account for instance variable changes.
"""
def __init__(self, func, watch=()):
self.func = func
self.cache = {}
self.is_method = False
self.watch = watch
def _ | _call__(self, *args, **kwargs):
key = [args, frozenset(kwargs.items())]
if self.is_method:
key.append(tuple([getattr(args[0], v, None) for v in self.watch]))
key = tuple(key)
if key in self.cache:
return self.cache[key]
try:
value = self.func(*... |
eswartz/RenderPipeline | rpplugins/pssm/pssm_scene_shadow_stage.py | Python | mit | 4,436 | 0.000902 | """
RenderPipeline
Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com>
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... | return state
def request_focus(self, focus_point, focus_size):
self.focus = (focus_point, focus_size)
sel | f.last_focus = self.focus
@property
def mvp(self):
return Globals.base.render.get_transform(self.cam_node).get_mat() * \
self.cam_lens.get_projection_mat()
def update(self):
if self._pipeline.task_scheduler.is_scheduled("pssm_scene_shadows"):
if self.focus is None:
... |
andres-de-castro/kineSYS | motor_imagery_trainer.py | Python | apache-2.0 | 5,885 | 0.003908 | #!usb/bin/env/python
import ctypes
import datetime
import os
import speech
import sys
import time
from ctypes import *
from numpy import *
from ctypes.util import find_library
# print (ctypes.util.find_library('edk.dll'))
# print (os.path.exists('edk.dll'))
libEDK = cdll.LoadLibrary("edk.dll")
if... | bEDK.EE_DataFree(hData)
ED_COUNTER = 0
ED_INTERPOLATED = 1
ED_RAW_CQ = 2
ED_AF3 = 3
ED_F7 = 4
ED_F3 = 5
ED_FC5 = 6
ED_T7 = 7
ED_P7 = 8
ED_O1 = 9
ED_O2 = 10
ED_P8 = 11
ED_T8 = 12
ED_FC6 = 13
ED_F4 = 14
ED_F8 = 15
ED_AF4 = 16
ED_GYROX = 17
ED_GYROY | = 18
ED_TIMESTAMP = 19
ED_ES_TIMESTAMP = 20
ED_FUNC_ID = 21
ED_FUNC_VALUE = 22
ED_MARKER = 23
ED_SYNC_SIGNAL = 24
# IN DLL(edk.dll)
# typedef enum EE_DataChannels_enum {
# ED_COUNTER = 0, ED_INTERPOLATED, ED_RAW_CQ,
# ED_AF3, ED_F7, ED_F3, ED_FC5, ED_T7,
# ED_P7, ED_O1, ED_O2, ED_P8, ED_T8,
# ED_FC6, ED_F4... |
ovidiub13/MoneyManager | old_django/mm_transactions/migrations/0001_initial.py | Python | gpl-3.0 | 3,094 | 0.002909 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
import da | tetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serializ... |
mhbu50/erpnext | erpnext/agriculture/doctype/soil_texture_criteria/soil_texture_criteria.py | Python | gpl-3.0 | 209 | 0.004785 | # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see l | icense.txt
from frappe.model.document import Document
class SoilTextureCriteria(Do | cument):
pass
|
romanvm/python-web-pdb | tests/tests.py | Python | mit | 9,209 | 0.000544 | # coding: utf-8
# Created on: 13.09.2016
# Author: Roman Miroshnychenko aka Roman V.M. (romanvm@yandex.ua)
#
# Copyright (c) 2016 Roman Miroshnychenko
#
# 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... | cls.stdin = cls.browser.find_element_by_id('stdin')
cls.send_btn = cls.browser.find_element_by_id('send_btn')
cls.stdout_tag = cls.browser.find_element_by_id('stdout')
@classmethod
def tearDownClass(cls):
cls.stdin.clear()
cls.stdin.send_keys('q')
cls.send_btn.clic... | wser.quit()
class WebPdbTestCase(SeleniumTestCase):
"""
This class provides basic functionality testing for Web-PDB
"""
@classmethod
def setUpClass(cls):
cls.db_proc = Popen(['python', db_py], shell=False)
super(WebPdbTestCase, cls).setUpClass()
def test_1_set_trace(self):
... |
openqt/algorithms | leetcode/python/lc705-design-hashset.py | Python | gpl-3.0 | 1,918 | 0.009906 | # coding=utf-8
import unittest
"""705. Design HashSet
https://leetcode.com/problems/design-hashset/description/
Design a HashSet without using any built-in hash table libraries.
To be specific, your design | should include these functions:
* `add(value)`: Insert a value into the HashSet.
* `contains(value)` : Return whether the value exists in the HashSet or not.
* `remove(value)`: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
**Example:**
MyHashSet hash... | tains(3); // returns false (not found)
hashSet.add(2);
hashSet.contains(2); // returns true
hashSet.remove(2);
hashSet.contains(2); // returns false (already removed)
**Note:**
* All values will be in the range of `[0, 1000000]`.
* The number of operations... |
tsh/card-game-server | tests/testRoom.py | Python | gpl-2.0 | 3,449 | 0.006669 | import unittest
import json
import sys
import os.path
import websocket
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from app.constants import Message
class TestServer(unittest.TestCase):
"""
This is not a unit test.
Simple client to test basic functionality of the server
"""
def... | ef test_destroy_room(self):
print "\n **************************---***************"
self.ws.recv()
print "\nSending {0} CreateRoom".format(Message.CreateRoom)
self.ws.send(json.dumps({'type':Message.CreateRoom, 'name':'This room will be d | estroyed'}))
print "Recv: {0}".format(self.ws.recv())
#get list of rooms
self.ws.send(json.dumps({'type':Message.GetListOfRoom}))
print "list of rooms {0}".format(self.ws.recv())
print "Sending {0} DestroyRoom".format(Message.DestroyRoom)
self.ws.send(json.dumps({'type':M... |
spreg-git/pysal | pysal/spreg/ml_error.py | Python | bsd-3-clause | 18,341 | 0.000545 | """
ML Estimation of Spatial Error Model
"""
__author__ = "Luc Anselin luc.anselin@asu.edu, Serge Rey srey@asu.edu"
import numpy as np
import numpy.linalg as la
import pysal as ps
from pysal.spreg.utils import RegressionPropsY, RegressionPropsVM
import diagnostics as DIAG
import user_output as USER
import summary_out... | ImportError:
minimize_scalar_available = False
__all__ = ["ML_Error"]
class BaseML_Error(RegressionPropsY, RegressionPropsVM, REGI.Regimes_Frame):
"""
ML estimation of the spatial error model (note no consistency
checks, diagnostics or constants added); Anselin (1988) [1]_
Parameters
------... | s and one column for each
independent (exogenous) variable, excluding the constant
w : Sparse matrix
Spatial weights sparse matrix
method : string
if 'full', brute force calculation (full matrix expressions)
epsilon : float
... |
kyjohnso/mlbslice | hmm_sandbox.py | Python | bsd-2-clause | 3,478 | 0.012076 | #!/usr/bin/env python
import tensorflow as tf
import edward as ed
import numpy as np
from numpy import array
from numpy.linalg import norm
from edward.models import Dirichlet, Multinomial, Gamma, Poisson
sess = tf.Session()
def build_toy_dataset(n, p, A, b):
"""
toy HMM with:
n=number of timesteps,... | anspose(Multinomial(total_count=1.,
probs=tf.transpose(tf.matmul(tf.transpose(vd['A']),z[-1]),
name='tx_prob')),name='z_new')
z = tf.concat([z,tf | .expand_dims(z_new,0)],0)
obs = tf.concat([obs,
tf.expand_dims(
Poisson(rate=tf.matmul(
tf.expand_dims(vd['b'],0), z_new)),0)], 0)
return obs, z
p_p_alpha = [2.,2.]
p_A_alpha = [[2.,1.],[1.,2.]]
p_b_alpha = [0.5,2.0]
p_b_beta = ... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractIzra709.py | Python | bsd-3-clause | 829 | 0.021818 | def extractIzra709(item):
"""
# izra709 | B Group no Shounen Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if not postfi | x and '–' in item['title']:
postfix = item['title'].split('–')[-1]
if 'monohito chapter' in item['title'].lower():
return buildReleaseMessageWithType(item, 'Monogatari no Naka no Hito', vol, chp, frag=frag, postfix=postfix)
if 'b group chapt | er' in item['title'].lower():
return buildReleaseMessageWithType(item, 'B Group no Shounen', vol, chp, frag=frag, postfix=postfix)
if 'assassin chapter' in item['title'].lower():
return buildReleaseMessageWithType(item, 'Other World Assassin Life of a Man who was a Shut-in', vol, chp, frag=frag, postfix=postfix)
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/Cython/Compiler/Builtin.py | Python | agpl-3.0 | 19,922 | 0.008031 | #
# Builtin Definitions
#
from __future__ import absolute_import
from .Symtab import BuiltinScope, StructOrUnionScope
from .Code import UtilityCode
from .TypeSlots import Signature
from . import PyrexTypes
from . import Options
# C-level implementations of builtin types, functions and methods
iter_next_utility_c... | return_type]
return func_type
class BuiltinAttribute(object):
def __init__(self, py_name, cname=None, field_type=None, field_type_name | =None):
self.py_name = py_name
self.cname = cname or py_name
self.field_type_name = field_type_name # can't do the lookup before the type is declared!
self.field_type = field_type
def declare_in_type(self, self_type):
if self.field_type_name is not None:
# lazy t... |
elberthcabrales/djangoerp | source/erp/wsgi.py | Python | gpl-2.0 | 383 | 0 | """
WSGI config for erp p | roject.
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.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "erp.settings")
... | |
blaze/distributed | distributed/protocol/tests/test_collection_cuda.py | Python | bsd-3-clause | 2,448 | 0.001634 | import pytest
from distributed.protocol import serialize, deserialize
from dask.dataframe.utils import assert_eq
import pandas as pd
@pytest.mark.parametrize("collection", [tuple, dict])
@pytest.mark.parametrize("y,y_serializer", [(50, "cuda"), (None, "pickle")])
def test_serialize_cupy(collection, y, y_serializer):... | else:
header, frames = serialize((df1, df2), serializers=("cuda", "dask", "pickle"))
t = deserialize(header, frames, deserializers=("cuda", "dask" | , "pickle"))
assert header["is-collection"] is True
sub_headers = header["sub-headers"]
assert sub_headers[0]["serializer"] == "cuda"
assert sub_headers[1]["serializer"] == df2_serializer
assert isinstance(t, collection)
assert_eq(t["df1"] if isinstance(t, dict) else t[0], df1)
if df2 is N... |
oaelhara/numbbo | code-postprocessing/bbob_pproc/comp2/ppscatter.py | Python | bsd-3-clause | 17,703 | 0.007456 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Scatter Plots.
For two algorithms, this generates the scatter plot of log(ERT1(df)) vs.
log(ERT0(df)), where ERT0(df) is the ERT of the reference algorithm,
ERT1(df) is the ERT of the algorithm of concern, both for target
precision df.
Different symbols are used for d... | vers.number_to_html(targets.label(-1)))
s += htmldesc.getValue('##bbobppscatterlegendend##')
return s
def beautify():
a = plt.gca()
a.set_xscale('log')
a.set_yscale('log')
#a.set_xlabel('ERT0')
#a.set_ylabel('ERT1')
xmin, xmax = plt.xlim()
ymin, | ymax = plt.ylim()
minbnd = min(xmin, ymin)
maxbnd = max(xmax, ymax)
maxbnd = maxbnd ** (1 + 11.*offset/(numpy.log10(float(maxbnd)/minbnd)))
plt.plot([minbnd, maxbnd], [minbnd, maxbnd], ls='-', color='k')
plt.plot([10*minbnd, 10*maxbnd], [minbnd, maxbnd], ls=':', color='k')
plt.plot([100*minbnd, ... |
kimihe/Swallow | swallow-benchmark/HiBench-master/bin/functions/load_config.py | Python | apache-2.0 | 31,060 | 0.004894 | #!/usr/bin/env python2
# 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 "Lice... | tion time | to 'timeout' seconds.
Uses the subprocess module and subprocess.PIPE.
Raises TimeoutInterrupt
"""
p = subprocess.Popen(
cmdline,
bufsize=0, # default value of 0 (unbuffered) is best
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
t_begin =... |
masterkorp/obfsproxy | obfsproxy/transports/scramblesuit/probdist.py | Python | bsd-3-clause | 2,788 | 0.003228 | """
This module provides code to generate and sample probability distributions.
The class RandProbDist provides an interface to randomly generate probability
distributions. Random samples can then be drawn from these distributions.
"""
import random
import const
import obfsproxy.common.log as logging
log = loggin... | self.sampleList = []
self.dist = self.genDistribution(genSingleton)
s | elf.dumpDistribution()
def genDistribution( self, genSingleton ):
"""
Generate a discrete probability distribution.
The parameter `genSingleton' is a function which is used to generate
singletons for the probability distribution.
"""
dist = {}
# Amount of ... |
DrewMcCarthy/dartboard | scenemanager.py | Python | apache-2.0 | 1,324 | 0.030967 | import serial
from threading import Thread
from menu import Menu
from time import sleep
import settings as s
import pygame
from pygame import *
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=.025)
current_mark = None
def worker():
global current_mark
while True:
read_serial = ser.readline().strip... | cene
self.scene.manager = self
def main():
pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.init()
pygame.mixer.quit() |
pygame.mixer.init(44100, -16, 2, 512)
screen = pygame.display.set_mode((s.DISPLAY_WIDTH, s.DISPLAY_HEIGHT), pygame.FULLSCREEN)
timer = pygame.time.Clock()
running = True
manager = SceneMananger()
t.start()
global current_mark
while running:
if pygame.event.get(QUIT):
running = False
return
... |
texttochange/vusion-backend | vusion/persist/export/tests/test_export.py | Python | bsd-3-clause | 293 | 0 | from tw | isted.trial.unittest import TestCase
from vusion.persist import Export
from tests.utils import Object | Maker
class TestExport(TestCase, ObjectMaker):
def test_validation_ok(self):
export = Export(**self.mkdoc_export())
self.assertTrue(isinstance(export, Export))
|
zqfan/leetcode | algorithms/113. Path Sum II/solution.py | Python | gpl-3.0 | 880 | 0 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[i... | not root.left and not root.right:
if target == root.val:
res.append(path + [root.val])
return
path.append(root.val)
dfs(root.left, target - root.val)
dfs(root.right, target - root.val)
path.pop()
res, path = [],... | time: 66 ms
# beats 96.94 %
|
idaholab/civet | ci/client/tests/ClientTester.py | Python | apache-2.0 | 1,836 | 0.000545 |
# Copyright 2016 Battelle Energy Alliance, 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 agr... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals, absolute_import
| import os
from ci.tests import utils, DBTester
from ci.client import ParseOutput
class ClientTester(DBTester.DBTester):
def get_file(self, filename):
dirname, fname = os.path.split(os.path.abspath(__file__))
with open(dirname + '/' + filename, 'r') as f:
js = f.read()
return... |
te-je/ohoh | tests/test_script.py | Python | mit | 3,667 | 0.003818 | from codecs import open
from ohoh import build_parser, DEFAULT_HOST, DEFAULT_PORT
from os import path
import os
import pytest
import sys
import time
@pytest.fixture
def parser():
return build_parser()
@pytest.fixture
def modfile(request, tmpdir):
def uninstall():
sys.path.remove(tmpdir.strpath)
s... | parsed = par | ser.parse_args(["-p", uncreated])
assert uncreated not in sys.path
def test_app_spec_parse_obj_factory(parser, modname, modfile):
with open(modfile, "a", encoding="utf-8") as f:
f.write("""
class App(object):
def __init__(self, name=None, **kwargs):
self.name = name
for kw in kwargs... |
TomConlin/dipper | dipper/sources/MGI.py | Python | bsd-3-clause | 99,120 | 0.000585 | import csv
import os
from datetime import datetime
import logging
import re
from dipper.sources.PostgreSQLSource import PostgreSQLSource
from dipper.models.assoc.Association import Assoc
from dipper.models.assoc.G2PAssoc import G2PAssoc
from dipper.models.Genotype import Genotype
from dipper.models.Reference import Ref... | cations
}
],
'test_keys': '../../resources/mgi_test_keys.yaml'
}
# with an existing set of (fresh) files in the shell; we can get | a head start with:
# for v in raw/mgi/*;do echo -e "\t\t'${v##*/}': \
# {\n\t\t\t'columns': [";head -1 $v|tr '\t' '\n'|sed "s/\(.*\)/\t\t\t\t'\1',/";done
tables = {
'all_allele_mutation_view': {
'columns': [
'_allele_key',
'mutation']},
'all_allele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.