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
Arabidopsis-Information-Portal/hrgrn_webservices
services/hrgrn_list_network/main.py
Python
gpl-2.0
2,479
0.008471
# HRGRN WebServices # Copyright (C) 2016 Xinbin Dai, Irina Belyaeva # This file is part of HRGRN WebServices API. # # HRGRN API is fr
ee 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. # HRGRN API is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; ...
should have received a copy of the GNU General Public License # along with HRGRN API. If not, see <http://www.gnu.org/licenses/>. """ Main Module """ import json import requests import logging import timer as timer from requests.exceptions import ConnectionError from requests import Session import service as svc i...
Shatki/PyIMU
calibration/pyIMUCalibrationServer.py
Python
gpl-3.0
2,005
0.00164
from socket import * from pytroykaimu import TroykaIMU import time import datetime # Адрес HOST = '' PORT = 21567 BUFSIZ = 128 ADDR = (HOST, PORT) imu = TroykaIMU() tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) # Запрет на ожидание # tcpSerSock.setblocking(False) def print_log...
ction...') # Ждем соединения клиента tcpCliSock, addr = tcpSerSock.accept() # Время ожидания данных от клиента
tcpCliSock.settimeout(0.02) print_log('connection from: ' + str(addr)) # Соединились, передаем данные while True: m_x, m_y, m_z = imu.magnetometer.read_calibrate_xyz() a_x, a_y, a_z = imu.accelerometer.read_gxyz() g_x, g_y, g_z = imu.gyroscope.read_ra...
ericholscher/django
django/contrib/admin/filters.py
Python
bsd-3-clause
16,609
0.001204
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.db import models...
uman-readable title to appear in the right sidebar. template = 'admin/filter.html' def __init__(self, request, params, model, model_admin): # This dictionary will eventually contain the request's query string # parameters actually used by this filter. self.used_parameters = {} i...
raise ImproperlyConfigured( "The list filter '%s' does not specify " "a 'title'." % self.__class__.__name__) def has_output(self): """ Returns True if some choices would be output for this filter. """ raise NotImplementedError('subclasses of ListFilte...
Matoking/NVIDIA-vBIOS-VFIO-Patcher
nvidia_vbios_vfio_patcher.py
Python
cc0-1.0
6,176
0.000648
#!/usr/bin/env python from __future__ import print_function import sys import binascii import argparse import re # raw_input doesn't exist in Python 3 try: raw_input except NameError: raw_input = input PROMPT_TEXT = "I agree to be careful" WARNING_TEXT = """ USE THIS SOFTWARE AT YOUR OWN DISCRETION. THIS...
CS CARD. If you want to save the created vBIOS file, type the following phrase EXACTLY as it is written below: %s """ % PROMPT_TEXT class CheckException(Exception): pass class VBIOSROM(object): def __init__(self, f): """ Load a VBIOS and convert it
into a hex-ascii format for easier editing """ content = f.read() self.offsets = { "header": None, "footer": None } self.content = binascii.hexlify(content) def detect_offsets(self, disable_footer=False): """ Search the ROM fo...
zstackorg/zstack-utility
zstacklib/zstacklib/test/test_table.py
Python
apache-2.0
818
0.003667
''' @author: Frank ''' import unittest from zstacklib.iptables import iptables class Test(unittest.TestCase): def testName(self): iptc = iptables.from_iptables_xml() tbl = iptc.get_filter_table() c = iptables.Chain() c.name = 'testchain' r = iptab
les.Rule() m = iptables.TcpMatch() m.dport = 10 m.sport = 1000 r.add_match(m) t = iptables.AcceptTarget() r.set_target(t) c.add_rule(r) r = iptables.Rule() m = iptables.IcmpMatch() m.icmp_type = 8 r.add_match(m) t = iptables...
r.set_target(t) c.add_rule(r) tbl.add_chain(c) print tbl if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
cldrn/rainmap-lite
rainmap-lite/nmaper/migrations/0009_auto_20160108_0613.py
Python
gpl-3.0
538
0.001859
# -*- coding: utf-8 -*- # Generated by Django 1
.9.1 on 2016-01-08 06:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nmaper', '0008_auto_20160108_0558'), ] operations = [ migrations.AlterField( model_name='nmapscan', ...
field=models.CharField(choices=[('waiting', 'Waiting'), ('running', 'Running'), ('finished', 'Finished')], max_length=8), ), ]
stevewoolley/IoT
static_host_pub.py
Python
apache-2.0
2,025
0.002963
#!/usr/bin/env python import json import awsiot import logging import platform import psutil import datetime from gpiozero import * NET_INTERFACES = ['en0', 'en1', 'en2', 'en3', 'wlan0', 'wlan1', 'eth0', 'eth1'] def get_ip(i): if i in psutil.net_if_addrs(): try: for k in psutil.net_if_addrs...
(psutil.boot_time()).strftime(awsiot.DATE_FORMAT).strip() if platform.system() == 'Darwin': # mac properties["release"] = platform.mac_ver()[0] elif platform.machine().startswith('arm') and platform.system() == 'Linux': # raspberry pi properties["distribution"] = "{} {}".format(platform.dist()...
orm.node() properties["machine"] = platform.machine() properties["system"] = platform.system() properties["totalDiskSpaceRoot"] = int(disk.total / (1024 * 1024)) properties["cpuProcessorCount"] = psutil.cpu_count() properties["ramTotal"] = int(mem.total / (1024 * 1024)) for iface in NET_INTERFAC...
jjscarafia/l10n-canada
res_partner_attributes_add_SIN/__openerp__.py
Python
agpl-3.0
1,378
0
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Management Solution # Copyright (C) 2010 - 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program is free software: y
ou can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT AN...
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Canada Soci...
pm5/python-moretext
setup.py
Python
mit
466
0.045064
from distutils.core import setup setup( name = 'moretext', packages = ['moretext'], version = '0.1',
description = 'Get dummy Chinese text (lorem ipsum) with Handlino serivce.', author = 'Pomin Wu', author_email = '[email protected]', url = 'https://github.com/pm5/python-
moretext', download_url = 'https://github.com/pm5/python-moretext/tarball/v0.1', keywords = ['test', 'lorem', 'ipsum', 'placeholder'], classifiers = [], )
jeremiahsavage/cwltool
cwltool/expression.py
Python
apache-2.0
5,948
0.002522
import subprocess import json import logging import os import re from typing import Any, AnyStr, Union, Text, Dict, List import schema_salad.validate as validate import schema_salad.ref_resolver from .utils import aslist, get_feature from .errors import WorkflowException from . import sandboxjs from . import docker ...
tack) > 1: raise SubstitutionError("Substitution error, unfinished block starting at position {}: {}".format(start, scan[start:])) else: return None def next_seg(remain, obj): # type: (Text, Any)->Text if remain: m = segment_re.match(remain) if m.group(0)[0] == '.': ...
key = m.group(0)[2:-2].replace("\\'", "'").replace('\\"', '"') return next_seg(remain[m.end(0):], obj[key]) else: key = m.group(0)[1:-1] return next_seg(remain[m.end(0):], obj[int(key)]) else: return obj def evaluator(ex, jslib, obj, fullJS=False, tim...
LLNL/spack
var/spack/repos/builtin/packages/guidance/package.py
Python
lgpl-2.1
1,752
0.001142
# Copy
right 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import glob from spack import * class Guidance(MakefilePack
age): """Guidance: Accurate detection of unreliable alignment regions accounting for the uncertainty of multiple parameters.""" homepage = "http://guidance.tau.ac.il/ver2/" url = "http://guidance.tau.ac.il/ver2/guidance.v2.02.tar.gz" version('2.02', sha256='825e105dde526759fb5bda1cd539b24d...
bmwiedemann/linuxcnc-mirror
configs/sim/axis/remap/iocontrol-removed/python/tooltable.py
Python
lgpl-2.1
6,047
0.017529
# This is a component of LinuxCNC # Copyright 2011, 2013 Dewey Garrett <[email protected]>, Michael # Haberler <[email protected]> # # 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; ei...
offset.w: print >> fp, "W%+f" % (t.offset.w), if t.frontangle: print >> fp, "I%+f" % (t.frontangle), if t.backangle: print >> fp, "J%+f" % (t.backangle), if t.orientation: print >> fp, "Q%+d" % (t.orientation), if comments.has_key(p) and comments[p]: ...
, ";%s" % (comments[p]) else: print >> fp fp.close() def assign(self,tooltable,entry,comments,fms): pocket = entry['P'] if not self.random_toolchanger: self.fakepocket += 1 if self.fakepocket >= len(tooltable): prin...
georgistanev/django-dash
src/dash/contrib/plugins/dummy/dash_widgets.py
Python
gpl-2.0
1,869
0.00214
__author__ = 'Artur Barseghyan <[email protected]>' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__
= 'GPL 2.0/LGPL 2.1' __all__ = ( 'BaseDummyWidget', 'Dummy1x1Widget', 'Dummy1x2Widget', 'Dummy2x1Wid
get', 'Dummy2x2Widget', 'Dummy3x3Widget' ) from django.template.loader import render_to_string from dash.base import BaseDashboardPluginWidget # ************************************************************************ # ************************* Base widget for Dummy plugin ***************** # ******************...
rbuffat/pyidf
tests/test_curvedoubleexponentialdecay.py
Python
apache-2.0
3,329
0.003905
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.performance_curves import CurveDoubleExponentialDecay log = logging.getLogger(__name__) class TestCurveDoubleExponentialDecay(unittest.TestCase): def setUp(self): s...
ialdecays[0].maximum_value_of_x, var_maximum_value_of_x) self.assertAlmostEqual(idf2.curvedoubleexponentialdecays[0].minimum_curve_output, var_minimum_curve_output) self.assertAlmostEqual(idf2.curvedoubleexponentialdecays[0].maximum_curve_output, var_maximum_curve_output) self.assertEqual(idf2.c...
_for_x) self.assertEqual(idf2.curvedoubleexponentialdecays[0].output_unit_type, var_output_unit_type)
g-goessel/mathdoku_solve
InterfaceMathDoku.py
Python
mpl-2.0
1,799
0.021861
# Interface MathDoku from fonctions import * from bruteforce import * from numpy import array donnees = {} taille=int(input('Taille de la grille ? ')) n = int(input('Nombre de blocs dans la grille \n')) grille=array([[0 for i in range(taille)] for j in range(taille)]) try: for i in range(1,n+1): print('Vo...
esultat[2],'secondes :\n',array(resultat[0])) except: print('Une er
reur s\'est produite, veuillez réessayer')
tensorflow/tensorflow
tensorflow/python/kernel_tests/random/stateless_random_ops_test.py
Python
apache-2.0
23,279
0.009236
# 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...
at import compat from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tens
orflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_stateless_random_ops_v2 from tensorflow.python.ops import math_ops from tensorflow.python.ops import ...
idlesign/uwsgiconf
tests/presets/test_nice.py
Python
bsd-3-clause
4,893
0.002452
from os import environ from uwsgiconf.presets.nice import Section, PythonSection def test_nice_section(assert_lines): assert_lines([ 'env = LANG=en_US.UTF-8', 'workers = %k', 'die-on-term = true', 'vacuum = true', 'threads = 4', ], Section(threads=4)) assert_lin...
at = %(method) %(uri) -> %(status)', 'log-req-encoder = json {"dt": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S%%z}", "src": "uwsgi.req"', 'log-req-encoder = nl', '"src": "uwsgi.out"', ], section) def test_configure_certbot_https(assert_lines, monkeypatch): monkeypatch.setattr('pathlib.Path....
/var/www/', address=':4443') assert_lines([ 'static-map2 = /.well-known/=/var/www/', 'https-socket = :4443,/etc/letsencrypt/live/mydomain.org/fullchain.pem,' '/etc/letsencrypt/live/mydomain.org/privkey.pem', ], section) section = Section.bootstrap(['http://:80']) section.config...
sigmunau/nav
python/nav/web/business/urls.py
Python
gpl-2.0
472
0.002119
"""URL config for business
tool""" from django.conf.urls import url, patterns from nav.web.business import views urlpatterns = patterns('', url(r'^$', views.BusinessView.as_view(), name='business-index'), url('^device_availability/$', views.DeviceAvailabilityReport.as_view(), name='business-report-device-availability')...
)
inspirehep/invenio-records
invenio_records/upgrades/records_2014_04_14_json_type_fix.py
Python
gpl-2.0
1,655
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio 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...
nullable=True)
) def estimate(): """Estimate running time of upgrade in seconds (optional).""" return 1
Eljee/symfit
symfit/tests/tests.py
Python
gpl-2.0
23,874
0.004356
from __future__ import division, print_function import unittest import inspect import sympy from sympy import symbols import numpy as np from symfit.api import Variable, Parameter, Fit, FitResults, Maximize, Minimize, exp, Likelihood, ln, log, variables, parameters from symfit.functions import Gaussian, Exp import scip...
getargspec(fit.scipy_func) self.assertEqual(args, ['x', 'p']) fit_result = fit.execute() self.assertIsInstance(fit_result, FitResults) def test_gaussian_fitting(self): xdata = 2*np.random.rand(10000) - 1 # random betwen [-1, 1] ydata = scipy.stats.norm.pdf(xdata, loc=0.0, s...
er() x = Variable() g = A * Gaussian(x, x0, sig) fit = Fit(g, xdata, ydata) fit_result = fit.execute() self.assertAlmostEqual(fit_result.params.A, 0.3989423) self.assertAlmostEqual(np.abs(fit_result.params.sig), 1.0) self.assertAlmostEqual(fit_result.params.x0, ...
kylon/pacman-fakeroot
test/pacman/tests/sync020.py
Python
gpl-2.0
357
0.008403
self.description = "Install a group f
rom a sync db" sp1 = pmpkg("pkg1") sp1.groups = ["grp"] sp2 = pmpkg("pkg2") sp2.groups = ["grp"] sp3 = pmpkg("pkg3") sp3.groups = ["grp"] for p in sp1, sp2, sp3: self.addpkg2db("sync", p); self.args = "-S %s" % "grp" self.addrule("PACMAN_RETCODE=0") for p in sp1, sp2, sp3: self.addrule("PKG_EXIST=%s" %
p.name)
xpansa/purchase-workflow
purchase_requisition_multicurrency/model/purchase_order.py
Python
agpl-3.0
2,905
0
# -*- coding: utf-8 -*- # # # Author: Yannick Vaucher # Copyright 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License,...
odels, fields, api import openerp.addons.decimal_precision as dp class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' @api.one @api.depends('price_unit', 'price_subtotal', 'order_id.pricelist_id.currency_i
d', 'order_id.requisition_id.date_exchange_rate', 'order_id.requisition_id.currency_id') def _compute_prices_in_company_currency(self): """ """ requisition = self.order_id.requisition_id date = requisition.date_exchange_rate or fields.Date.today() fr...
ufal/neuralmonkey
scripts/preprocess_bert.py
Python
bsd-3-clause
3,940
0.000254
#!/usr/bin/env python3 """Creates training data for the BERT network training (noisified + masked gold predictions) using the input corpus. The masked Gold predictions use Neural Monkey's PAD_TOKEN to indicate tokens that should not be classified during training. We only leave `coverage` percent of symbols for classi...
= 0) log("Loading vocabulary.") vocabulary = from_wordlist( args.vocabulary, contains_header=args.vocab_contains_header, contains_frequencies=args.vocab_contains_frequencies) mask_prob = args.mask_prob replace_prob = args.replace_prob keep_prob = 1 - mask_prob - replace_pro...
ple_probs = (keep_prob, mask_prob, replace_prob) output_prefix = args.output_prefix if output_prefix is None: output_prefix = args.input_file out_f_noise = "{}.noisy".format(output_prefix) out_f_mask = "{}.mask".format(output_prefix) out_noise_h = open(out_f_noise, "w", encoding="utf-8") ...
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam
unittests/Applications/test_CompareDictionary.py
Python
gpl-2.0
116
0.008621
import unittest from PyFoam.Applica
tions.CompareDictionary import CompareDictionary theSuite=unittest.TestSuite()
bkolli/swift
test/__init__.py
Python
apache-2.0
2,485
0.000805
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fil
e 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,...
ions under the License. # See http://code.google.com/p/python-nose/issues/detail?id=373 # The code below enables nosetests to work with i18n _() blocks from __future__ import print_function import sys import os try: from unittest.util import safe_repr except ImportError: # Probably py26 _MAX_LENGTH = 80 ...
zalmanu/Enjoy-City-Admin
admin/models.py
Python
apache-2.0
2,126
0.005644
from django.db import models # Create your models here. from djangotoolbox.fields import ListField, EmbeddedModelField from django_mongodb_engine.storage import GridFSStorage gridfs_storage = GridFSStorage() class Cordinates(models.Model): lat = models.FloatField(null=False, blank=False) lng = models.FloatFi...
orage=gridfs_storage, upload_to='/media/locations/', null=True, blank=True) class Meta: verbose_name_plural = 'Locations' class Content(models.Model): location_id = models.CharField(max_length=15) description = models.TextField(null=True, blank=True) tags = ListF
ield(models.PositiveIntegerField(), null=True, blank=True) photo = models.FileField(storage=gridfs_storage, upload_to='/media/locations/', blank=True, null=True) expiration_date = models.DateTimeField(null=True, blank=True) class Meta: verbose_name_plural = 'Content Item...
neurotechuoft/Wall-EEG
Code/OpenBCIPy/src/machine-learning/other/exercise_01_multichannel.py
Python
mit
4,069
0.019169
# -*- coding: utf-8 -*- """ BCI workshop 2015 Exercise 1b: A neurofeedback interface (multi-channel) Description: In this exercise, we'll try and play around with a simple interface that receives EEG from mulitple electrodes, computes standard frequency band powers and displays both the raw biosignals and the featur...
parameters #%% Set the experiment parameters eeg_buffer_secs = 15 # Size of the EEG data buffer used for plotting the # signal (in seconds) win_test_secs = 1 # Length of the window used for computing the features # (in seconds) overlap_s...
cutive windows (in seconds) shift_secs = win_test_secs - overlap_secs index_channel = 1 # Index of the channnel to be used (with the Muse, we # can choose from 0 to 3) # Get name of features names_of_features = BCIw.feature_names(params['names of channels']) #%% Init...
izberg-marketplace/django-izberg
django_iceberg/models/user_models.py
Python
mit
3,201
0.017182
# -*- coding: utf-8 -*- import json from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .base_models import IcebergBaseModel from icebergsdk.api import IcebergAPI from django_iceberg.conf import ConfigurationDebug, ConfigurationDebugSandbox,\ ...
sername, access_token = self.access_token) return api_handler def sync_shopping_preferences(self): """ Will
forward shopping preference to Iceberg """ api_handler = self.get_api_handler() api_handler._sso_response = json.loads(self.sso_data) shopping_preference = api_handler.me().shopping_preference shopping_preference.country = api_handler.Country.search({"code": self.shipping_country...
ad-m/sledzenie_listow
sledzenie_listow/settings.py
Python
bsd-3-clause
1,203
0.000831
# -*- coding: utf-8 -*- import os os_env = os.environ class Config(object): SECRET_KEY = os_env.get('SLEDZENIE_LISTOW_SECRET', 'secret-key') # TODO: Change me APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) BCRYP...
t the db file in project root DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) DEBUG_TB_ENABLED = True ASSETS_DEBUG = True # Don't bundle/minify static assets CACHE_TYPE = 'simple' # Can be "mem
cached", "redis", etc. class TestConfig(Config): TESTING = True DEBUG = True BCRYPT_LOG_ROUNDS = 1 # For faster tests WTF_CSRF_ENABLED = False # Allows form testing
stoq/stoqdrivers
stoqdrivers/printers/base.py
Python
lgpl-2.1
6,610
0.000605
# -*- Mode: Python; coding: iso-8859-1 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Stoqdrivers # Copyright (C) 2005 Async Open Source <http://www.async.com.br> # All rights reserved # # 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 # ...
sb, serial or ethernet) @param include_virtual: If the virtual printer (for development) should be
included in the results """ # Select the base class depending on which interface has been chosen # TODO: Implement Ethernet interface support base_class = { 'usb': UsbBase, 'serial': SerialBase, 'ethernet': None, None: object, }[protocol] if interface n...
ahmedaljazzar/edx-platform
openedx/core/djangoapps/credit/tests/test_signals.py
Python
agpl-3.0
5,259
0.002282
""" Tests for minimum grade requirement status """ import ddt import pytz from datetime import timedelta, datetime from mock import MagicMock from django.test.client import RequestFactory from course_modes.models import CourseMode from student.models import CourseEnrollment from student.tests.factories import UserFac...
: """Test with failed grades and deadline expire""" self.assert_requirement_status(0.22, self.EXPIRED_DUE_DATE, 'failed') @ddt.data( CourseMode.AUDIT, CourseMode.HONOR, CourseMode.CREDIT_MODE ) def test_requirement_failed_for_non_verified_enrollment(self, mode): ...
line with non-verified enrollment.""" self.enrollment.update_enrollment(mode, True) self.assert_requirement_status(0.8, self.VALID_DUE_DATE, None)
idea4bsd/idea4bsd
python/testData/refactoring/move/function/before/src/a.py
Python
apache-2.0
353
0.002833
from lib1 import urlopen def f(url): '''Retur
n the representation available at the URL. ''' return urlopen(url).read() def f_usage(): return f(14) class C(object): def g(self, x): return x class D(C): def g(self, x,
y): return super(D, self).f(x) + y class E(object): def g(self): return -1
TeamBasedLearning/Service
pgtbl/accounts/tests/test_read_user.py
Python
gpl-3.0
2,537
0
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from accounts.models import User from accounts.serializers import UserSerializer, UserRegisterSerializer class ReadUserTestCase(APITestCase): """ Test to show all or a single user of the system. "...
.get(url) self.assertEquals(response.data, serializer.data) self.assertEquals(response.status_code, status.HTTP_200_OK) def test_invalid_url_user_detail(self): """ Test to not found the specific user. """
url_invalid = reverse('accounts:details', kwargs={'pk': 30}) response = self.client.get(url_invalid) self.assertEquals(response.status_code, status.HTTP_404_NOT_FOUND)
pedropva/AIprojects
sources/Data.py
Python
gpl-3.0
5,965
0.053646
from Node import Node from Utils import Utils class Data: """description of class""" def __init__(self): pass @staticmethod def cities(): neighbors = {'Arad':('Sibiu','Timisoara','Zerind'),'Zerind':('Arad','Oradea'),'Oradea':('Sibiu','Zerind'),'Timisoara':('Arad','Lugoj'),'Lugoj':('Mehadia','...
end(node) return @staticmethod def isInList(list, obj): for item in list: if item[0].getName() == obj.getName():##testing two nodes, i use [0] because every traveled node is a list with the node itself and the string with the path to him return True return Fa...
x: for r in l: if r > maxN or r < minN: return False if r not in numbers: numbers.append(r) else: return False return True @staticmethod def isSolvable(matrix,finalMatrixIsPair): ...
ihaywood3/easygp
db/proda.py
Python
gpl-3.0
882
0.011338
#!/usr/bin/python """ An interface to the web-based PROvider Direct Access (PRODA) system of Medicare Australia """ import mechanize # available via PIP import re m = mechanize.Browser() m.open("https://proda.humanservices.gov.au/prodalogin/pages/public/login.jsf?TAM_OP=l
ogin&USER") m.select_form(name="loginFormAndStuff") m['loginFormAndStuff:inputPassword'] = "Drc232crq838" m['loginFormAndStuff:username'] = 'ihaywood' m.submit() m.select_form(nr=0) m['otp.user.otp'] = raw_input("Emailed code") m.submit() print m.reply() #m.open("https://www2.medicareaustralia.gov.au:5447/pcert/hpo...
itionsForm") #m['action'] = "I agree" #m.submit() #m.follow_link(text_regex=re.compile("Claims")) #m.follow_link(text_regex=re.compile("Make a new claim")) #m.follow_link(text_regex=re.compile("Medicare Bulk Bill Webclaim")) print m.read()
devilry/devilry-django
devilry/project/develop/testhelpers/soupselect.py
Python
bsd-3-clause
5,265
0.003229
""" soupselect.py - https://code.google.com/p/soupselect/ CSS selector support for BeautifulSoup. soup = BeautifulSoup('<html>...') select(soup, 'div') - returns a list of div elements select(soup, 'div#main ul a') - returns a list of links inside a ul inside div#main """ import re from bs4 import BeautifulSoup t...
SS selector specifying the elements you want to retrieve. """ tokens = selector.split() current_context = [soup] for
token in tokens: m = attribselect_re.match(token) if m: # Attribute selector tag, attribute, operator, value = m.groups() if not tag: tag = True checker = attribute_checker(operator, attribute, value) found = [] for ...
tombstone/models
research/deep_contextual_bandits/bandits/algorithms/variational_neural_bandit_model.py
Python
apache-2.0
12,618
0.004755
# 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 applicab...
om_normal(shape) w = w_mu + w_sigma * w_noise b_mu = self.build_mu_variable([1, shape[1]]) b_sigma = self.sigma_transform(self.build_sigma_variable([1, shape[1]]))
b = b_mu # Store means and stds self.weights_m[layer_id] = w_mu self.weights_std[layer_id] = w_sigma self.biases_m[layer_id] = b_mu self.biases_std[layer_id] = b_sigma # Create outputs output_h = activation_fn(tf.matmul(input_x, w) + b) if self.use_local_reparameterization: # ...
srwalter/yap
yap/plugin.py
Python
gpl-2.0
34
0
class YapPlu
gin(ob
ject): pass
VictorLoren/Crak-card-game-python
Deck.py
Python
mit
803
0.048568
from Card import Card #Deck class Deck(Card): '''Definition of a card deck.''' from random import shuffle as rShuffle def __init__(self,hasJoker=False): #Assemble deck self.cards = [Card(v,s) for v in self.values for s in self.suits] #Add Joker cards (2) as 'WW' if needed #if(hasJoker): # self.cards.exte...
) #Draw a card from th
e deck and return a card def draw(self,fromTop=True): #Remove from the front/top of deck if fromTop: return self.cards.pop(0) #Remove from the back/bottom of deck else: return self.cards.pop() #Shuffle deck and return the newly shuffled deck def shuffle(self): #Use random.shuffle() method rShuffle...
broadinstitute/cfn-pyplates
docs/source/examples/advanced/altered_template.py
Python
mit
899
0.005562
import sys # If our base template isn't on the PYTHONPATH already, we need to do this: sys.path.append('../path/to/base/templates') import basetemplate class AlteredTemplate(basetemplate.BaseTemplate): """This project only needs an S3 bucket, but no EC2 server.""" def add_resources(self): self
.add_bucket() def add_bucket(self): """This will add a bucket using the base template, and then add a custom CORS configuration to it.""" super(AlteredTemplate, self).add_bucket() self.resources['StaticFiles']['Properties']['CorsConfiguration'] = { 'CorsRules': [ ...
], 'AllowedMethods': ['GET'], 'AllowedOrigins': ['*'], } ] } cft = AlteredTemplate("S3 Bucket Project", options) cft.add_resources()
dokterbob/slf-programming-workshops
examples/snowball/main.py
Python
mit
1,795
0
from snowball.utils import SnowMachine from snowball.climate import WeatherProbe # Note: multiline import limits line length from snowball.water.phases import ( WaterVapor, IceCrystal, SnowFlake ) def let_it_snow(): """ Makes it snow, using a SnowMachine when weather doesn't allow it. Returns a list...
.phases.SnowFlake object at 0x101dbc190>, <snowball.water.phases.SnowFlake object at 0x101dbc3d0>, <snowball.water.phases.SnowFlake object at 0x101dbc410>, <snowball.water.phases.SnowFlake object at 0x101dbc450>, <snowball.water.phases.SnowFlake object at 0x101
dbc390>, <snowball.water.phases.SnowFlake object at 0x101dbc310>] """ # Create a WeatherProbe weather_probe = WeatherProbe() if weather_probe.temperature < 0 and weather_probe.clouds: # There's clouds and it's cold enough # Create necessary components vapor = WaterVap...
j-carl/ansible
test/integration/targets/collections/collection_root_user/ansible_collections/testns/othercoll/plugins/module_utils/formerly_testcoll_pkg/submod.py
Python
gpl-3.0
56
0
thing = "hello
from formerly_testcoll_pkg.subm
od.thing"
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Tasking/PyScripts/Lib/tasking/netmap.py
Python
unlicense
259
0.011583
import dsz import os import re from task impo
rt * class Netmap(Task, ):
def __init__(self, file): Task.__init__(self, file, 'Netmap') def CreateCommandLine(self): return ['netmap -minimal'] TaskingOptions['_netmapTasking'] = Netmap
alu042/edx-platform
common/test/acceptance/tests/lms/test_learner_profile.py
Python
agpl-3.0
34,219
0.002835
# -*- coding: utf-8 -*- """ End-to-end tests for Student's Profile Page. """ from contextlib import contextmanager from datetime import datetime from bok_choy.web_app_test import WebAppTest from nose.plugins.attrib import attr from ...pages.common.logout import LogoutPage from ...pages.lms.account_settings import Acc...
'] PUBLIC_PROFILE_EDITABLE_FIELDS = ['country', 'language_proficiencies', 'bio'] USER_SETTINGS_CHANGED_EVENT_NAME = u"edx.user.settings.changed" def log_in_as_
unique_user(self): """ Create a unique user and return the account's username and id. """ username = "test_{uuid}".format(uuid=self.unique_id[0:6]) auto_auth_page = AutoAuthPage(self.browser, username=username).visit() user_id = auto_auth_page.get_user_id() return...
marbiouk/dsmtools
Tools/GenericToolsBatchConvertRastersASCIIMXE.py
Python
mit
4,814
0.003324
#!/usr/bin/env python import sys, os, arcpy class GenericToolsBatchConvertRastersASCIIMXE(object): """This class has the methods you need to define to use your code as an ArcGIS Python Tool.""" def __init__(self): """Define the tool (tool name is the name of the class).""" se...
for raster in rasterlist: arcpy.AddMessage("Converting " + str(raster) + ".") if not arcpy.Exists(os.path.join(output_directory, raster + ".asc")): arcpy.RasterToASCII_conversion(raster, os.path.join(output_directory, raster + ".asc")) if out_mxe: com...
' + os.path.join(path_mxe, "maxent.jar") + '" density.Convert ' + \ output_directory + " asc " + output_directory + " mxe" arcpy.AddMessage("Calling Maxent to convert ASCII to MXE: " + str(command)) os.system(str(command)) return def main(): tool = G...
SINGROUP/pycp2k
pycp2k/classes/_dirichlet_bc2.py
Python
lgpl-3.0
2,187
0.001372
from pycp2k.inputsection import InputSection from ._aa_planar2 import _aa_planar2 from ._planar2 import _planar2 from ._aa_cylindrical2 import _aa_cylindrical2 from ._aa_cuboidal2 import _aa_cuboidal2 class _dirichlet_bc2(InputSection): def __init__(self): InputSection.__init__(self) self.Verbose_...
tion_parameters self.AA_CYLINDRICAL_list.append(new_section) return new_section def PLANA
R_add(self, section_parameters=None): new_section = _planar2() if section_parameters is not None: if hasattr(new_section, 'Section_parameters'): new_section.Section_parameters = section_parameters self.PLANAR_list.append(new_section) return new_section de...
jules185/IoT_Hackathon
.homeassistant/deps/fuzzywuzzy/__init__.py
Python
mit
47
0
# -*- coding: utf-8 -*- __version
__ =
'0.15.0'
ClearingHouse/clearblockd
lib/components/assets.py
Python
mit
14,545
0.008869
import os import logging import decimal import base64 import json from datetime import datetime from lib import config, util, util_bitcoin ASSET_MAX_RETRY = 3 D = decimal.Decimal def parse_issuance(db, message, cur_block_index, cur_block): if message['status'] != 'valid': return def modify_extended_...
os.remove(imagePath) tracked_asset = db.tracked_assets.find_one( {'asset': message['asset']}, {'_id': 0, '_histor
y': 0}) #^ pulls the tracked asset without the _id and history fields. This may be None if message['locked']: #lock asset assert tracked_asset is not None db.tracked_assets.update( {'asset': message['asset']}, {"$set": { '_at_block': cur_block_index, ...
stoivo/GitSavvy
core/interfaces/status.py
Python
mit
26,371
0.001213
import os import sublime from sublime_plugin import WindowCommand, TextCommand from ..commands import * from ...common import ui from ..git_command import GitCommand f
rom ...common import util class GsShowStatusCommand(WindowCommand, GitCommand): """ Open a status view for the active git repository. """ def run(self): StatusInterface(repo_path=self.repo_path) class StatusInterface(ui.Interface, GitCommand): """ Status dashboard. """ in...
file = "Packages/GitSavvy/syntax/status.sublime-syntax" word_wrap = False tab_size = 2 template = """\ BRANCH: {branch_status} ROOT: {git_root} HEAD: {head} {< unstaged_files} {< untracked_files} {< staged_files} {< merge_conflicts} {< no_status_message} {...
Kronuz/Xapiand
contrib/python/xapiand-py/xapiand/transport.py
Python
mit
15,871
0.001764
# Copyright (c) 2019 Dubalu LLC # Copyright (c) 2017 Elasticsearch # # 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 unde...
or implied. # See the License for the specific language gover
ning permissions and # limitations under the License. import time from itertools import chain from .connection import Urllib3HttpConnection from .connection_pool import ConnectionPool, DummyConnectionPool from .serializer import Deserializer, DEFAULT_SERIALIZERS, DEFAULT_SERIALIZER from .exceptions import ConnectionE...
amwelch/a10sdk-python
a10sdk/core/cgnv6/cgnv6_nat64_fragmentation_df_bit_transparency.py
Python
apache-2.0
1,367
0.010241
from a10sdk.common.A10BaseClass import A10BaseClass class DfBitTransparency(A10BaseClass): """Class Description:: Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled). Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`. This cla...
f.ERROR_MSG = "" self.required=[] self.b_key = "df-bit-transparency" self.a10_url="/axapi/v3/cgnv6/nat64/fragmentation/df-bit-transparency" self.DeviceProxy = "" sel
f.df_bit_value = "" self.uuid = "" for keys, value in kwargs.items(): setattr(self,keys, value)
LLNL/spack
var/spack/repos/builtin/packages/amrvis/package.py
Python
lgpl-2.1
6,541
0.000153
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class Amrvis(MakefilePackage): """Amrvis is a visualization package specifically designed to read and display ...
sions' ) variant( 'prec', default='DOUBLE', values=('FLOAT', 'DOUBLE'), multi=False, description='Floating point precision' ) variant('mpi', default=True, description='Enable MPI parallel support') variant('debug', default=False, description='Enable debugging ...
profiling features') depends_on('gmake', type='build') depends_on('mpi', when='+mpi') depends_on('libsm') depends_on('libice') depends_on('libxpm') depends_on('libx11') depends_on('libxt') depends_on('libxext') depends_on('motif') depends_on('flex') depends_on('bison') ...
patricklaw/pants
src/python/pants/backend/java/dependency_inference/types.py
Python
apache-2.0
1,065
0.001878
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from typing import Any, Sequence @dataclass(frozen=True) class JavaImport: name: str is_static: bool = False...
n_dict(cls, imp: dict[str, Any]) -> JavaImport: return cls( name=imp["name"], is_asterisk=imp["isAsterisk"], is_static=imp["isStatic"], ) @dataclass(frozen=True) class JavaSourceDependencyAnalysis: declared_package: str imports: Sequence[JavaImport] top_...
ncyAnalysis: return cls( declared_package=analysis["declaredPackage"], imports=[JavaImport.from_json_dict(imp) for imp in analysis["imports"]], top_level_types=analysis["topLevelTypes"], )
thiagopbueno/mdp-problog
tests/test_mdp.py
Python
gpl-3.0
5,866
0.003409
#! /usr/bin/env python3 # This file is part of MDP-ProbLog. # MDP-ProbLog 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. # MDP-Prob...
assertEqual(actual_next_state_fluents, expected_next_state_fluents) def test_actions(self): expected_actions = ['reboot(c1)', 'reboot(c2)', 'reboot(c3)', 'reboot(none)'] actual_actions = [str(a) for a in self.mdp.actions()]
self.assertEqual(actual_actions, expected_actions) def test_transition(self): states = StateSpace(self.mdp.current_state_fluents()) actions = ActionSpace(self.mdp.actions()) for state in states: for j, action in enumerate(actions): probabilities = self....
rbernand/transfert
tests/fonct/test_copy.py
Python
mit
916
0
import os import transfert from transfert import Resource import transfert.actions import transfert.exceptions from .utils import delete_files def test_copy(tmpdir, storages): f = tmpdir.join('alpha') f.write_binary(os.urandom(1024 * 40)) f_http = Resource(storages['http']('index.html')) f_file = Reso...
_ftp.exists() transfert.actions.copy(f_http, f_ftp, size=40960) assert f_ftp.exists() and f_http.exists() transfert.actions.copy(f_ftp, f_sftp, size=40960) assert f_ftp.exists() and f_sftp.exists() transfert.actions.copy(f_sftp, f_file, size=40960) assert f_sftp.exists() and f_file
.exists()
stardog-union/stardog-graviton
aws/etc/packer/tools/python/stardog/cluster/update_stardog.py
Python
apache-2.0
1,959
0
import logging import subprocess import sys import stardog.cluster.utils as utils def upload_file(ip, upload_file): scp_opts = "-o StrictHostKeyChecking=no -o
UserKnownHostsFile=/dev/null" cmd = "scp -r %s %s %s:%s" % (scp_opts, uploa
d_file, ip, upload_file) return utils.command(cmd) def refresh_stardog_binaries(ip, release_file): ssh_opts = "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" refresh_cmd = "/usr/local/bin/stardog-refresh-binaries" cmd = "ssh %s %s '%s %s'" % (ssh_opts, ip, refresh_cmd, release_file) ...
genialis/resolwe
resolwe/flow/managers/state.py
Python
apache-2.0
1,297
0.001542
""".. Ignore
pydocstyle D400. ===== State ===== Constants used by the dispatcher. .. autofunction:: resolwe.flow.managers.state.update_constants """ # This module should not import anything local, or there wi
ll be circular # dependencies, since the constants are needed in various sub-modules inside # resolwe.flow.managers. from collections import namedtuple from django.conf import settings ManagerChannelPair = namedtuple("ManagerChannelPair", ["queue", "queue_response"]) MANAGER_CONTROL_CHANNEL = "DUMMY.control" LISTEN...
tseaver/google-cloud-python
monitoring/google/cloud/monitoring_v3/gapic/notification_channel_service_client.py
Python
apache-2.0
52,223
0.002221
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
nnel_descriptor): """Return a fully-qualified n
otification_channel_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/notificationChannelDescriptors/{channel_descriptor}", project=project, channel_descriptor=channel_descriptor, ) @classmethod def project_path(cls, proje...
rananda/cfme_tests
cfme/tests/containers/test_reload_button_provider.py
Python
gpl-2.0
2,719
0.002574
import pytest from cfme.containers.provider import ContainersProvider from utils import testgen, version from cfme.web_ui import toolbar as tb from utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.uncollectif( lambda: version.current_version() < "5.6"), pytest.mark.use...
ist_img_from_registry_splitted_new) num_img_in_cfme = provider.num_image() # TODO Fix num_image_ui() num_img_cfme_56 = len(provider.mgmt.list_image()) num_img_cfme_57 = len(list_img_from_openshift_parsed_new) assert num_img_in_cfme == version.pick({version.LOWEST: num_img_cfme_56, ...
ost for i in list_all_rgstr] list_all_rgstr_new = filter(lambda ch: 'openshift3' not in ch, list_all_rgstr_revised) num_rgstr_in_cfme = provider.summary.relationships.image_registries.value assert len(list_all_rgstr_new) == num_rgstr_in_cfme
talkincode/ToughPORTAL
toughportal/common/secret.py
Python
agpl-3.0
344
0.017442
#!/usr/bin/env python #coding:utf-8 import sys,os from toughportal.common
import utils import shutil import time impo
rt random import ConfigParser def gen_secret(clen=32): rg = random.SystemRandom() r = list('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') return ''.join([rg.choice(r) for _ in range(clen)])
pmacosta/putil
tests/test_ptypes.py
Python
mit
9,287
0.003338
# test_ptypes.py # Copyright (c) 2013-2016 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0103,C0111,W0108 # Standard library imports import sys import numpy # Putil imports import putil.ptypes from putil.test import AE, AI ### # Global variables ### emsg = lambda msg: ( '[START CONTRACT MSG:...
}] for item in items: putil.ptypes.csv_row_filter(item) def test_engineering_notation_number(): """ Test EngineeringNotationNumber pseudo-type """ obj = putil.ptypes.engi
neering_notation_number items = ['3.12b', 'f', 'a1b', ' + 123.45f '] for item in items: check_contract(obj, 'engineering_notation_number', item) items = [' +123.45f ', ' -0 '] for item in items: obj(item) def test_engineering_notation_suffix(): """ Test EngineeringNotatio...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/google-api-python-client/apiclient/ext/django_orm.py
Python
bsd-3-clause
1,509
0.007952
# Copyright (C) 2010 Google 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 or agreed to in writ...
s or implied. # See the License for the specific language governing permissions and # limitations under the License. impor
t apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials...
AlmostBetterNetwork/podmaster-host
podcasts/migrations/0015_auto_20160503_0248.py
Python
apache-2.0
667
0
# -*- coding: utf-8 -*- from __future__ import absolute
_import # Generated by Django 1.9 on 2016-05-03 02:48 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20160503_0247'), ] operations = [ migrations.RemoveField( model_name...
name='tip_last_payout_amount', ), migrations.RemoveField( model_name='podcast', name='tip_value', ), ]
kamsuri/vms
vms/administrator/admin.py
Python
gpl-2.0
217
0
# Django from administrator.models import Administrator # local Django from django.contrib import admin
class AdministratorAdmin(admin.ModelAdmin): pass admin.site.register(Administrator, Administra
torAdmin)
repotvsupertuga/tvsupertuga.repository
script.module.universalscrapers/lib/universalscrapers/modules/js2py/legecy_translators/objects.py
Python
gpl-2.0
11,176
0.008053
""" This module removes all objects/arrays from JS source code and replace them with LVALS. Also it has s function translating removed object/array to python code. Use this module just after removing constants. Later move on to removing functions""" OBJECT_LVAL = 'PyJsLvalObject%d_' ARRAY_LVAL = 'PyJsLvalArray%d_' fro...
f not data or len(data)>1: raise Exception() e
xcept: raise SyntaxError('Could not parse setter: '+setter) prop = data.keys()[0] body, args = data[prop] if len(args)!=1: #setter must have exactly 1 argument raise SyntaxError('Invalid setter. It must take exactly 1 argument.') # now
YoshikawaMasashi/magenta
magenta/models/shared/events_rnn_graph.py
Python
apache-2.0
16,101
0.011738
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
lse: is_training = False dilation = [2**i for i in range(block_size)]*block_num batch_num = tf.shape(inputs)[0] h = tf.reshape(inputs, [batch_num,-1,1,input_size]) dlt_sum = [sum(dilation[:i]) for i in range(len(dilation))] dlt_sum.
append(sum(dilation)) with tf.variable_scope("first_conv"): h = tf.contrib.layers.batch_norm(h, decay=0.999, center=True, scale=True, updates_collections=None, is_training=is_training, scope="first_conv", reuse=True) first_weights = tf.get_variable(...
felipenaselva/felipe.repository
script.module.streamhub/resources/premium/modules/control.py
Python
gpl-2.0
3,906
0.001792
# -*- coding: utf-8 -*- ''' Tulip routine libraries, based on lambda's lamlib Author Twilight0 License summary below, for more details please read license.txt file This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License...
etails. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import os, xbmc, xbmcaddon, xbmcplugin, xbmcgui, xbmcvfs integer = 1000 addon
= xbmcaddon.Addon lang = xbmcaddon.Addon().getLocalizedString setting = xbmcaddon.Addon().getSetting setSetting = xbmcaddon.Addon().setSetting addonInfo = xbmcaddon.Addon().getAddonInfo addItem = xbmcplugin.addDirectoryItem directory = xbmcplugin.endOfDirectory content = xbmcplugin.setContent property = xbmcplugin.se...
Rdbaker/Rank
manage.py
Python
mit
2,039
0.000981
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell, Server from flask_script.commands import Clean, ShowUrls from flask_migrate import MigrateCommand, Migrat
e from flask.ext.sqlalchemy import sqlalchemy import seed_db from rank.app import create_app from rank.settings import DevConfig, ProdConfig from rank.core.models import Base, DB DEFAULT_DB = 'postgres' CREATE_DB = 'create database %s' if os.environ.get("RANK_ENV") == 'prod': application = create_app(ProdConfig)...
= os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') migrate = Migrate(application, Base) manager = Manager(application) def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': applica...
timasjov/famous-algorithms
hashing/BloomFilter.py
Python
mit
1,098
0.004554
from random import randrange MAX_K =16 DEFAULT_K = 8 def hash(word): wordStr = str(word) assert len(wordStr) <= MAX_K value = 0 for n, ch in
enumerate(wordStr): value += ord(ch) * 128 ** n #value += 2 * ord(ch) ** n return value class BloomFilter(object): allchars = "".join([chr(i) for i in range(128)]) def __init__(self, tablesizes, k=DEFAULT_K): self.table
s = [(size, [0] * size) for size in tablesizes] self.k = k def add(self, word): val = hash(word) for size, ht in self.tables: ht[val % size] = 1 def __contains__(self, word): val = hash(word) return all(ht[val % size] for (size, ht) in self.tables) bloomFil...
syscoin/syscoin
test/functional/wallet_keypool_topup.py
Python
mit
4,455
0.004265
#!/usr/bin/env python3 # Copyright (c) 2017-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test HD Wallet keypool restore function. Two nodes. Node1 is under test. Node0 is providing transactio...
assert address_details["isscript"] and not address_details["iswitness"] else: assert not address_details["isscript"] and address_details["iswitness"] self.log.info("Send funds to wallet") self.nodes[0].sendtoaddress(addr_oldpool, 10) self.generate(s...
[0].sendtoaddress(addr_extpool, 5) self.generate(self.nodes[0], 1) self.log.info("Restart node with wallet backup") self.stop_node(idx) shutil.copyfile(wallet_backup_path, wallet_path) self.start_node(idx, self.extra_args[idx]) self.connect_nodes(...
Cedev/a10-neutron-lbaas
a10_neutron_lbaas/tests/unit/v1/test_base.py
Python
apache-2.0
1,417
0
# Copyright 2014, Doug Wiegley (dougwig), A10 Networks # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of
the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # under the License. import a10_neutron_lbaas.tests.unit.test_base as test_base class FakeModel(dict, object): def __getitem__(self, key, default=None): attr = getattr(self, key, default) return attr def get(self...
lscsoft/gwdetchar
gwdetchar/io/datafind.py
Python
gpl-3.0
7,423
0
# coding=utf-8 # Copyright (C) Duncan Macleod (2015) # # This file is part of the GW DetChar python package. # # GW DetChar 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 #...
for more details. # # You should have received a copy of the GNU General Public License # along with GW DetChar. If not, see <http://www.gnu.org/licenses/>. ""
"gw_data_find wrappers """ import re import warnings from six.moves.urllib.error import HTTPError try: # python >= 3 from json.decoder import JSONDecodeError except ImportError: # python == 2.7 JSONDecodeError = ValueError import gwdatafind from ..const import DEFAULT_SEGMENT_SERVER from gwpy.io import g...
detectlanguage/detectlanguage-python
setup.py
Python
mit
843
0.027284
#!/usr/bin/env python from setuptools.depends import get_module_constant from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'detectlanguage', packages = ['detectla
nguage'], version = get_module_constant('detectlanguage', '__version__'), description = 'Language Detection API
Client', long_description=long_description, long_description_content_type="text/markdown", author = 'Laurynas Butkus', author_email = '[email protected]', url = 'https://github.com/detectlanguage/detectlanguage-python', download_url = 'https://github.com/detectlanguage/detectlanguage-pyth...
csferrie/python-qinfer
src/qinfer/distributions.py
Python
agpl-3.0
51,767
0.004057
#!/usr/bin/python # -*- coding: utf-8 -*- ## # distributions.py: module for probability distributions. ## # © 2017, Chris Ferrie ([email protected]) and # Christopher Granade ([email protected]). # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
ibutions. :param weights: Length ``n_dist`` list or ``np.ndarray`` of probabilites summing to 1. :param dist: Either a length ``n_dist`` list of ``Distribution`` instances, or a ``D
istribution`` class, for example, ``NormalDistribution``. It is assumed that a list of ``Distribution``s all have the same ``n_rvs``. :param dist_args: If ``dist`` is a class, an array of shape ``(n_dist, n_rvs)`` where ``dist_args[k,:]`` defines the arguments of the k'th distributio...
gitmill/gitmill
django/repository/views.py
Python
mit
245
0.004082
from django.
shortcuts import render from user.decorators import user_view from repository.decorators import repository_view @user_
view @repository_view def repository(request, user, repository, **kwargs): return render(request, 'app.html')
StongeEtienne/dipy
dipy/fixes/argparse.py
Python
bsd-3-clause
85,208
0.000012
# emacs: -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # Copyright 2006-2009 Steven J. Bethard <[email protected]>. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fol...
return result # silence Python 2.6 buggy warnings about Exception.message if _sys.version_info[:2] == (2, 6): import warnings warnings.filterwarnings( action='ignore', message='BaseException.message has been deprecated as of Python 2.6', category=DeprecationWarning, module='...
==PARSER==' # ============================= # Utility functions and classes # ============================= class _AttributeHolder(object): """Abstract base class that provides __repr__. The __repr__ method returns a string in the format:: ClassName(attr=name, attr=name, ...) The attributes are ...
Batchyx/parsethisshit
parsethis.py
Python
gpl-3.0
21,672
0.045268
#!/usr/bin/python # -*- encoding:iso8859-15 -*- """A module to parse specificaly designed HTML calendars""" # Copyright (C) 2005-2009 Batchyx # # 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 F...
defaulttimes def header_cell_found(self, cell): if self.groups_max_x is None: self.groups_max_x = cell.x else: self.groups_max_x = min(cell.x, self.groups_max_x) def
extract_days_positions(self): """Find days positions.""" days = ['lundi','mardi','mercredi','jeudi','vendredi'] for linenum, row in enumerate(self.rows): self.daycols=[] for x, cell in enumerate(row): if not cell: continue value = cell.data().lower() current_day = len(self.daycols) if ...
timabbott/zulip
zerver/lib/test_classes.py
Python
apache-2.0
43,104
0.004918
import base64 import os import re import shutil import tempfile import urllib from contextlib import contextmanager from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Union from unittest import mock import ujson from django.apps import apps from django.conf import settings from dja...
actor_login from zerver.lib.actions import ( bulk_add_subscriptions, bulk_remove_subscriptions, check_send_message, check_send_stream_message, gather_subscriptions, ) from zerver.lib.initial_password import initial_password from zerver.lib.sessions import get_session_dict_user from zerve
r.lib.stream_subscription import get_stream_subscriptions_for_user from zerver.lib.streams import ( create_stream_if_needed, get_default_value_for_history_public_to_subscribers, ) from zerver.lib.test_helpers import find_key_by_email, instrument_url from zerver.lib.users import get_api_key from zerver.lib.valid...
dgreisen/u2db
u1db/remote/utils.py
Python
gpl-3.0
800
0
# Copyright 2012 Canonical Ltd. # # This file is part of u1db. # # u1db is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # u1db is distributed in the hope that it will be useful, # but
WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License f
or more details. # # You should have received a copy of the GNU Lesser General Public License # along with u1db. If not, see <http://www.gnu.org/licenses/>. """Utilities for details of the procotol.""" def check_and_strip_comma(line): if line and line[-1] == ',': return line[:-1], True return line, ...
nmercier/linux-cross-gcc
win32/bin/Lib/lib2to3/fixes/fix_unicode.py
Python
bsd-3-clause
1,311
0.002288
r"""Fixer for unicode. * Changes unicode to str and unichr to chr. * If "...\u..." is not unicode literal change it into "...\\u...". * Change u"..." into "...". """ from ..pgen2 import token from .. import fixer_base _mapp
ing = {u"unichr" : u"chr", u"unicode" : u"str"}
class FixUnicode(fixer_base.BaseFix): BM_compatible = True PATTERN = "STRING | 'unicode' | 'unichr'" def start_tree(self, tree, filename): super(FixUnicode, self).start_tree(tree, filename) self.unicode_literals = 'unicode_literals' in tree.future_features def transform(self,...
dezede/dezede
libretto/migrations/0044_auto_20190917_1200.py
Python
bsd-3-clause
987
0.002033
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-09-17 10:00 from __future__ import unicode_literals f
rom django.db import migrations, models import django.db.models.deletion class Migration(mig
rations.Migration): dependencies = [ ('libretto', '0043_auto_20190905_1126'), ] operations = [ migrations.AlterModelOptions( name='source', options={'ordering': ('date', 'titre', 'numero', 'parent__date', 'parent__titre', 'parent__numero', 'position', 'page', 'lieu_...
nesl/sos-2x
modules/unit_test/modules/kernel/post_raw/source_trick/reciever/source_trick_reciever.py
Python
bsd-3-clause
3,085
0.014263
import sys import os import pysos import signal # these two variables should be changed depending on the test drivers PID # and the type of message it will be sending, If you are using the generic_test.c # then it is likely these two values can stay the same TEST_MODULE = 0x81 MSG_TEST_DATA= 33 ALARM_LEN = 60 START_...
sensor (node_id, node_state, data) = pysos.unpack("<BBB", msg['data']) if node_id not in state.keys(): state[node_id] = 0 oldstate[node_id] = 0 # these are some simple calculations to test the sensor value we have gotten # this is the part which you need to fill in in order to verify that the functi...
ate == START_DATA): print "initialization began correctly" if (node_state == 0): state[node_id] = data if (node_state == TEST_FAIL): print >> sys.stderr, "the test for item %d has failed" %data if (node_state == TEST_PASS): print "the test for item %d has passed" %data if (node_state == 1 and state[...
htygithub/bokeh
bokeh/models/widgets/dialogs.py
Python
bsd-3-clause
1,502
0.001332
""" Various kinds of dialog and message box widgets. """ from __future__ import absolute_import from ...properties import Bool, String, List, Instance, Either from .widget import Widget from .layouts import BaseBox, HBox from .buttons import Button class Dialog(Widget): """ Simple dialog box with string message....
t = Either(String(), Instance(BaseBox), default="", help=""" Either a message to be displayed by this dialog or a BaseBox to be used as dialog body. """) buttons = List(Instance(Button), help=""" A list of buttons to be placed on the bottom of the dialog. "
"") buttons_box = Instance(BaseBox, help=""" A BaseBox with buttons to be used as dialog footer. """) def __init__(self, **kwargs): if "buttons" in kwargs and "buttons_box" in kwargs: raise ValueError("'buttons' keyword cannot be used with 'buttons_box' argument") if 'butt...
antoinecarme/pyaf
tests/artificial/transf_Logit/trend_MovingAverage/cycle_0/ar_/test_artificial_32_Logit_MovingAverage_0__100.py
Python
bsd-3-clause
264
0.087121
import pyaf.Bench.TS_datasets as tsds i
mport tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 0, transform = "Logit", sigma = 0.0, exog_count = 100, ar_orde
r = 0);
AnykeyNL/uArmProPython
svg_example.py
Python
gpl-3.0
1,467
0.019087
# Example made by OssiLehtinen # from svgpathtools import svg2paths, wsvg import numpy as np import uArmRobot import time #Configure Serial Port #serialport = "com3" # for windows serialport = "/dev/ttyACM0" # for linux like system # Connect to uArm myRobot = uArmRobot.robot(serialport,0) # user 0 for ...
, np.imag(cp)*scale]) coords.append(segcoords) # The starting point myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000) for seg in coords: myRobot.goto(seg[0][0], seg[0][1], height, 6000) time.sleep(0.15) for p in seg: myRobot.goto_laser(p[0], p[1], height, draw_speed) # B
ack to the starting point (and turn the laser off) myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000)
avathardev/matchine-learning
kmeans.py
Python
mit
3,350
0.000896
import json import math import random import os class KMeans(object): # TO-DO: Richard def __init__(self, dataset=None): file_path = os.path.dirname(os.path.realpath(__file__)) if dataset is None: self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read...
# update centroids centroids = [self._get_centroid(c) for c in clusters] return clusters, centroids def calculate(self, attr, to_file=False): self.dataset = [] for data in self.mega_data
set[attr]: self.dataset.append(tuple(data)) self.dataset = set(self.dataset) champ2stat = {} for i in xrange(len(self.mega_dataset['champions'])): champ2stat[tuple(self.mega_dataset[attr][i])] = self.mega_dataset['champions'][i] clusters, centroids = sel...
AxelDelmas/ansible
lib/ansible/parsing/__init__.py
Python
gpl-3.0
11,072
0.002619
# (c) 2012-2014, Michael DeHaan <[email protected]> # # 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) an...
rsed_data # return a deep copy here, so the cache is not affected return copy.deepcopy(parsed_data
) def path_exists(self, path): path = self.path_dwim(path) return os.path.exists(path) def is_file(self, path): path = self.path_dwim(path) return os.path.isfile(path) or path == os.devnull def is_directory(self, path): path = self.path_dwim(path) return os...
patrick-winter-knime/mol-struct-nets
molstructnets/experimentbatch/batch_entry.py
Python
gpl-3.0
1,435
0.000697
from util import file_util class BatchEntry: def __init__(self, csv_line, experiment_location=None): values = csv_line.split(',') self.experiment_location = experiment_location self.experiment = BatchEntry.get_value(values, 0) if s
elf.experiment is None: raise ValueError('Experiment is not defined') self.data_set = BatchEntry.get_value(values, 1) self.target = BatchEntry.get_value(values, 2) self.partition = BatchEntry
.get_value(values, 3) def get_execution_arguments(self): arguments = list() if self.experiment_location is not None: arguments.append(file_util.resolve_subpath(self.experiment_location, self.experiment)) else: arguments.append(file_util.resolve_path(self.experiment))...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/email/generator.py
Python
gpl-3.0
19,988
0.0007
# Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: [email protected] """Classes to generate plain text from a message object tree.""" __all__ = ['Generator', 'DecodedGenerator', 'BytesGenerator'] import re import sys import time import random from copy import deepcopy from io ...
en a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The defau
lt is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used. ...
gakarak/BTBDB_ImageAnalysisSubPortal
app/core/preprocessing_test.py
Python
apache-2.0
3,387
0.007676
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import matplotlib.pyplot as plt import numpy as np import os import glob import nibabel as nib import app.core.pre
processing as preproc import unittest class TestLungDividing(unittest.TestCase): def setUp(self): self.wdir = '../../experimental_data/resize-256x256x64' def test_resize_nii(self): self.assertTrue(os.path.isdir(self.wdir)) lstPathNii = sorted(glob.glob('%s/*.nii.gz' % self.wdir)) ...
, newSize=newSize) self.assertTrue(niiResiz.shape == newSize) def test_divide_morphological(self): self.assertTrue(os.path.isdir(self.wdir)) lstPathNii = sorted(glob.glob('%s/*-msk.nii.gz' % self.wdir)) numNii = len(lstPathNii) self.assertTrue( (numNii>0) ) for ii,pa...
DavidWhittingham/arcpyext
arcpyext/publishing/__init__.py
Python
bsd-3-clause
362
0.008287
try: import arcpy.mapping from ._publishing import (convert_desktop_map_to_service_draft as convert_map_to_service_draft,
convert_toolbox_to_service_draft) except: from ._publishing import (convert_pro_map_to_service_draft as convert_map_to_servi
ce_draft, convert_toolbox_to_service_draft)
kasioumis/invenio
invenio/modules/workflows/views/holdingpen.py
Python
gpl-2.0
16,341
0.000184
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 optio...
PEN_WORKFLOW_STATES[obj.version]["class"] obj.message = HOLDINGPEN_WORKFLOW_STATES[obj.version]["message"]
results = get_rendered_task_results(bwobject) workflow_definition = get_workflow_info(extracted_data['workflow_func']) task_history = bwobject.get_extra_data().get('_task_history', []) return render_template('workflows/details.html', bwobject=bwobject, ...
cgranade/qutip
qutip/tests/test_bofin_solvers.py
Python
bsd-3-clause
32,389
0.000123
""" Tests for qutip.nonmarkov.bofin_solvers. """ import numpy as np import pytest from numpy.linalg import eigvalsh from scipy.integrate import quad from scipy.sparse import csr_matrix from qutip import ( basis, destroy, expect, liouvillian, sigmax, sigmaz, tensor, Qobj, QobjEvo, Options, ) from qutip.fastspa...
n_ados = len(ados.labels) ado_soln = np.random.rand(n_ados, *[2**d for d in rho_dims]) rho = Qobj(ado_soln[0, :], dims=[2, 2]) return rho, ado_soln def test_create(self): ados = self.mk_ados([2, 3], max_depth=2) rho, ado_soln = self.mk_rho_and_soln(ados, [2, 2]) ...
assert ado_state.exponents == ados.exponents assert ado_state.idx((0, 0)) == ados.idx((0, 0)) assert ado_state.idx((0, 1)) == ados.idx((0, 1)) def test_extract(self): ados = self.mk_ados([2, 3], max_depth=2) rho, ado_soln = self.mk_rho_and_soln(ados, [2, 2]) ado_sta...
matthrice/MarkeTouch-TTS
test/logger_tests.py
Python
apache-2.0
684
0.038012
import logging from logging.handlers import RotatingFileHandler import time logging.basicConfig(filemode='a', format='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=loggin
g.DEBUG) def test_createRotatingLog(path): #initiates logging session logger = logging.getLogger("TTS_test") #defines handler for byte size #will roll over after 100 mb, will max out at 10 backup files sizeHandler = RotatingFileHandler(path, maxBytes=20, backupCount=5) logger.addHandler(sizeHandler) ...
ingLog(log_file)
frankyrumple/smc
modules/pytube/api.py
Python
mit
12,801
0.000234
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from .exceptions import MultipleObjectsReturned, YouTubeError, CipherError from .tinyjs import JSVM from .models import Video from .utils import safe_filename try: from urllib2 import urlopen from urlparse import urlparse, pa...
lution=None, profile="High"): """Return a single video given an extention and resolution. :params extention: The desired file extention (e.g.: mp4).
:params resolution: The desired video broadcasting standard. :params profile: The desired quality profile. """ result = [] for v in self.videos: if extension and v.extension != extension: continue elif resolution and v.resolution != resolution: ...
hopr/hopr
script/evlogger.py
Python
gpl-3.0
8,419
0.006295
#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr 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 o...
General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Hopr. If not, see <http://www.gnu.org/lice
nses/>. from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range from past.builtins import basestring from builtins import object import csv import sys from pickle import dump, load from collections import defaultdict from evdev import ecodes as e fro...
edx-solutions/edx-platform
common/djangoapps/xblock_django/tests/test_user_service.py
Python
agpl-3.0
5,271
0.002087
""" Tests for the DjangoXBlockUserService. """ from django.test import TestCase from opaque_keys.edx.keys import CourseKey from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from openedx.core.djangoapps.external_user_ids.models import ExternalIdType from student.models import anonymous_...
EFERENCES] ) ) def test_convert_anon_user(self): """ Tests for convert_django_user_to_xblock_user behavior when django user is AnonymousUser. """ django_user_service = DjangoXBlockUserService(self.anon_user) xb_user = django_user_service.get_current_user(...
def test_convert_authenticate_user(self): """ Tests for convert_django_user_to_xblock_user behavior when django user is User. """ django_user_service = DjangoXBlockUserService(self.user) xb_user = django_user_service.get_current_user() self.assertTrue(xb_user.is_cur...
rakhi27/microurl
microurl/bitly.py
Python
gpl-2.0
22,925
0.033544
import requests import base64 import urllib class bitlyapi(object): def __init__(self,access_token): self.host = 'https://api.bit.ly/' self.ssl_host = 'https://api-ssl.bit.ly/' self.access_token=access_token def shorturl(self,url,preferred_domain=None): params...
response=self.send_request('get',self.ssl_host+'v3/link/lookup',params) return response def link_edit(self,link,edit,title=None,note=None,private=None,user_ts=None,archived=None): params=dict(link=link) params['edit']=edit if title: params['title']=titl...
if note: params['note']=note if private: params['private']=private if user_ts: params['user_ts']=user_ts if archived: params['archived']=archived params['access_token']=self.access_token response=self.send_request('get',self.ssl_...
tfroehlich82/picamera
picamera/camera.py
Python
bsd-3-clause
173,859
0.001202
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python camera library for the Rasperry-Pi camera module # Copyright (c) 2013-2017 Dave Jones <[email protected]> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # ...
mmal.MMAL_PARAM_EXPOSUREMETERINGMODE_MATRIX, } EXPOSURE_MODES = { 'off': mmal.MMAL_PARAM
_EXPOSUREMODE_OFF, 'auto': mmal.MMAL_PARAM_EXPOSUREMODE_AUTO, 'night': mmal.MMAL_PARAM_EXPOSUREMODE_NIGHT, 'nightpreview': mmal.MMAL_PARAM_EXPOSUREMODE_NIGHTPREVIEW, 'backlight': mmal.MMAL_PARAM_EXPOSUREMODE_BACKLIGHT, 'spotlight': mmal.MMAL_PARAM_EXPOSU...
OpenGenus/cosmos
code/online_challenges/src/project_euler/problem_067/problem_067.py
Python
gpl-3.0
79,937
0.000038
def main(): prob = [ [59], [73, 41], [52, 40, 9], [26, 53, 6, 34], [10, 51, 87, 86, 81], [61, 95, 66, 57, 25, 68], [90, 81, 80, 38, 92, 67, 73], [30, 28, 51, 76, 81, 18, 75, 44], [84, 14, 95, 87, 62, 81, 17, 78, 58], [21, 46, 71, 58, 2,...
24, 25, 46, 78, 79, 5, ], [ 92, 9, 13, 55, 10, 67, 26, 78, 76, 82, 63, 49, 51, ...
21, 67, 43, 17, 63, 12, ], [ 24, 59, 6, 8, 98, 74, 66, 26, 61, 60, 13, 3, 9, ...