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
DependencyWatcher/crawler
dependencywatcher/crawler/rubygems.py
Python
apache-2.0
1,359
0.003679
from dependencywatcher.crawler.detectors import Detector import urllib2, json, logging, os logger = logging.getLogger(__name__) class RubyGemsDetector(Detector): """ rubygems.org API based information detector """ url = "https://rubygems.org/api/v1/gems/%s.json" auth = "af93e383246a774566bcf661f9c9f591" ...
son.load(urllib2.urlopen(request)) def detect(self, what, options, result): if self.json is None: self.json = self.get(self.manifest["name"]) try: if what == "url": result[what] = self.normalize(what, self.json["homepage_uri"]) elif what == "licen...
, self.json[what]) if what == "description": result[what] = self.normalize(what, self.json["info"]) except KeyError: pass
jnadro/pybgfx
pybgfx/bgfx.py
Python
bsd-2-clause
45,223
0.010548
''' Python bindings for bgfx. ''' __author__ = "Jason Nadro"
__copyright__ = "Copyright 2016, Jason Nadro" __credits__ = ["Jason Nadro"] __license__ = "BSD 2-clause" __version__ = "0.0.1" __maintainer__ = "Jason Nadro" __email__ = "" __status__ = "Development" import ctypes from ctypes import Structure, POINTER, cast, byref, CFUNCTYPE from ctypes import c_bool, c_int, c_int8, ...
int8, c_uint16, c_uint32, c_uint64, c_float, c_char_p, c_void_p, c_size_t, c_char import os bgfx_dll_path = os.path.dirname(__file__) + "\\bgfx-shared-libRelease" _bgfx = ctypes.CDLL(bgfx_dll_path) enum_type = c_int # bgfx_renderer_type bgfx_renderer_type = enum_type ( BGFX_RENDERER_TYPE_NOOP, BGFX_RENDERER_...
lord63/flask_toolbox
flask_toolbox/views/package.py
Python
mit
2,151
0.002789
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from flask import Blueprint, render_template, Markup, url_for from flask_toolbox.models import Package package_page = Blueprint('package_page', __name__, template_folder='templates') @package_page.route(...
ges = [item.name for item in category.packages.order_by(Package.score.desc()).all() if item.name != package] sidebar_title = ( M
arkup("Other related packages in the <a href='{0}'>{1}</a> category".format( url_for('category_page.index', category=category.name), category.name )) ) return render_template( 'score.html', package=the_package, flask=flask, related_packages=related_packages, sid...
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/webdriver/tests/support/fixtures.py
Python
bsd-3-clause
7,196
0.001112
import copy import json import os import asyncio import pytest import webdriver from urllib.parse import urlunsplit from tests.support import defaults from tests.support.helpers import cleanup_session, deep_update from tests.support.inline import build_inline from tests.support.http_request import HTTPRequest # Th...
metafunc.parametrize("capabilities", marker.args, ids=None) @pytest.fixture(scope="session") def event_loop(): """Change event_loop fixture to global.""" global _event_loop if _event_loop is None: _event_loop = asyncio.get_event_loop_policy().new_event_loop() return _event_loop @pytest.f...
r_config(): with open(os.environ.get("WD_SERVER_CONFIG_FILE"), "r") as f: return json.load(f) @pytest.fixture(scope="session") def configuration(): host = os.environ.get("WD_HOST", defaults.DRIVER_HOST) port = int(os.environ.get("WD_PORT", str(defaults.DRIVER_PORT))) capabilities = json.loads(...
Weihonghao/ECM
Vpy34/lib/python3.5/site-packages/theano/tensor/tests/test_blas.py
Python
agpl-3.0
87,605
0.00145
from __future__ import absolute_import, print_function, division from copy import copy from itertools import product as itertools_product from unittest import TestCase import numpy from numpy import (arange, array, common_type, complex64, complex128, float32, float64, newaxis, shape, transpose, zeros...
s_opt.excluding('c_blas') def test_dot_eq(): assert T.Dot() == T.Dot() def sharedX(x, name): return theano.shared(numpy.asarray(x, config.floatX), name=name) class t_gemm(TestCase): """This test suite is supposed to establish that gemm works as it is supposed to. """ def setUp(self): ...
e @staticmethod def _gemm(z, a, x, y, b): assert a.shape == () assert b.shape == () return b * z + a * numpy.dot(x, y) @staticmethod def rand(*args): return numpy.random.rand(*args) def cmp(self, z_, a_, x_, y_, b_): for dtype in ['float32', 'float64', 'com...
mattclark/osf.io
conftest.py
Python
apache-2.0
3,405
0.000881
from __future__ import print_function import logging import mock import pytest from faker import Factory from website import settings as website_settings from framework.celery_tasks import app as celery_app logger = logging.getLogger(__name__) # Silence some 3rd-party logging and some "loud" internal loggers SILEN...
make sure exceptions get propagated celery_app.conf.update({ 'task_always_eager': True, 'task_eager_propagates': True, }) website_settings.ENABLE_EMAIL_SUBSCRIPTIONS = False # TODO: Remove if this is unused? website_settings.BCRYPT_LOG_ROUNDS = 1 # Make sure we don't accidentall...
e # Set this here instead of in SILENT_LOGGERS, in case developers # call setLevel in local.py logging.getLogger('website.mails.mails').setLevel(logging.CRITICAL) @pytest.fixture() def fake(): return Factory.create() _MOCKS = { 'osf.models.user.new_bookmark_collection': { 'mark': 'enable_...
Octoberr/swmcdh
cong/zijixieyige.py
Python
apache-2.0
496
0.014113
import urllib.request import re def getHtml(url): page = urllib.request.urlopen(url) html = page.read().decode('utf-8') return html def getImg
(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.request.urlretrieve(imgurl,'pic/%s.jpg' % x) x+=1 return imglist html = getHtml("http://tieba.baidu.com/p/2460150866") list=getImg(html) for i in...
list: print(i)
csparpa/robograph
robograph/datamodel/tests/test_buffers.py
Python
apache-2.0
703
0
import time from robograph.datamodel.nodes.lib import buffers def test_buffer(): instance = buffers.Buffer() assert instance.requirements == [] expected = dict(a=1, b=2, c=3) instance.input(expected) instance.set_output_label('any') assert instance.output() == expected def test_detlayed_buf...
onds=delay) assert instance.requirements == ['seconds'] expected = dict(a=1, b=2, c=3) in
stance.input(expected) instance.set_output_label('any') start_time = time.time() result = instance.output() end_time = time.time() assert result == expected assert end_time - start_time >= delay
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-vision-face/azure/cognitiveservices/vision/face/operations/_person_group_operations.py
Python
mit
21,247
0.001459
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
her version of recognition model. Person group quota: * Free-tier subscription quota: 1,000 person groups. Each holds up to 1,000 persons. * S0-tier subscription quota: 1,000,000 person groups. Each holds up to 10,000 persons. * to handle larger scale face identif...
:param person_group_id: Id referencing a particular person group. :type person_group_id: str :param name: User defined name, maximum length is 128. :type name: str :param user_data: User specified data. Length should not exceed 16KB. :type user_data: str :param re...
chrismeyersfsu/ansible-modules-core
files/lineinfile.py
Python
gpl-3.0
15,603
0.001795
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # (c) 2014, Ahti Kitsik <ak@ahtik.com> # # 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 S...
ular expressions; see U(http://docs.python.org/2/library/re.html). state: required: false choices: [ present, absent ] default: "present" aliases: [] description: - Whether the line should b
e there or not. line: required: false description: - Required for C(state=present). The line to insert/replace into the file. If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches. backrefs: required: false ...
waldenilson/TerraLegal
project/tramitacao/restrito/relatorio.py
Python
gpl-2.0
111,754
0.016833
# -*- coding: UTF-8 -*- from django.template.context import RequestContext from project.tramitacao.models import Tbpecastecnicas, \ Tbprocessorural,Tbchecklistprocessobase, Tbprocessosanexos, Tbprocessobase,Tbprocessourbano, Tbcaixa, AuthUser, Tbmunicipio, Tbprocessoclausula, Tbpendencia, Tbetapa, Tbtransicao f...
orizon
tal('center').stringValue( 'Gleba' ).setFontSize('14pt').setBold(True).setCellColor("#ccff99") sheet.getCell(9, 6).setAlignHorizontal('center').stringValue( 'Qtd. Pendencias' ).setFontSize('14pt').setBold(True).setCellColor("#ccff99") sheet.getCell(10, 6).setAlignHorizontal('center').stringValue( 'Pen...
baroquebobcat/pants
src/python/pants/goal/pantsd_stats.py
Python
apache-2.0
1,009
0.006938
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import
(absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) class PantsDaemonStats(object): """Tr
acks various stats about the daemon.""" def __init__(self): self.target_root_size = 0 self.affected_targets_size = 0 self.affected_targets_file_count = 0 self.scheduler_metrics = {} def set_scheduler_metrics(self, scheduler_metrics): self.scheduler_metrics = scheduler_metrics def set_target...
tensorflow/benchmarks
scripts/tf_cnn_benchmarks/mlperf_test.py
Python
apache-2.0
7,794
0.003977
# 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...
mlperf.tags.RUN_STOP +
'.*': 1, mlperf.tags.RUN_FINAL: 1 } EXPECTED_LOG_REGEXES = Counter({re.compile(k): v for k, v in EXPECTED_LOG_REGEXES.items()}) def testMlPerfCompliance(self): string_io = six.StringIO() handler = logging.StreamHandler(string_io) data_dir = test_util.create_bla...
turbofish/mcverify
config.py
Python
bsd-2-clause
772
0.009067
# vim: set fileencoding=utf-8 ts=4 sw=4 expandtab fdm=marker: """ Small wrapper around the python ConfigParser module. """ import ConfigParser CONFIG = ConfigParser.ConfigParser() DEFAULTS = { 'patterns': {
'path' : '(?P<artist>\w+) - (?P<year>\d+) - (?P<album>\w+)' } } def get_param(section, name): try: param = CONFIG.get(section, name) except ConfigParser.NoOp
tionError or ConfigParser.NoSectionError: param = None if not param: # Do a default lookup try: param = DEFAULTS[section][name] except KeyError: # Parameter is not in defaults LOG.error("Error: Parameter [%s][%s] does not exist", section, name) ...
aldmbmtl/FloatingTools
tools/utilities.py
Python
mit
10,347
0.002996
""" Validate the dependencies are installed. """ from __future__ import print_function __all__ = [ 'installRequiredToolbox', 'downloadDependency', 'addExtensionPath', 'loadExtensions', 'installPackage', 'tokenRefresher', 'validateToken', 'checkInstall', 'updateToken', 'TokenErro...
if test: # verify install __import__(package) # handle token system def updateToken(token): """ For internal use. """ with open(tools.HFX_TOKEN, 'w') as tokenFil
e: tokenFile.write(token) validateToken() # relaunch the initialize process with the new token tools.initialize() def validateToken(): """ Checks the token created. """ global TOKEN import requests response = requests.get(tools.buildCall('shed'), headers={'Authorization'...
MAndelkovic/pybinding
pybinding/support/alias.py
Python
bsd-2-clause
5,869
0.001704
import numpy as np from scipy.sparse import csr_matrix class AliasArray(np.ndarray): """An ndarray with a mapping of values to user-friendly names -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter transla...
d to return `True` even if only the first
part matches. Examples -------- >>> s = SplitName("first|second") >>> s == "first|second" True >>> s != "first|second" False >>> s == "first" True >>> s != "first" False >>> s == "second" False >>> s != "second" True """ @property def first(self):...
polyaxon/polyaxon-api
polyaxon_lib/datasets/converters/base.py
Python
mit
2,397
0.001252
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import tensorflow as tf class BaseConverter(object): @staticmethod def to_int64_feature(values): """Returns a TF-Feature of int64s. Args: values: A scalar or list of values. Returns:...
'int': return cls.to_int64_feature(value) if value_type == 'float': retu
rn cls.to_float_feature(value) if value_type == 'bytes': return cls.to_bytes_feature(value) raise TypeError("value type: `{}` is not supported.".format(value_type)) @classmethod def to_sequence_feature(cls, sequence, sequence_type): """Returns a FeatureList based on a list ...
scheib/chromium
tools/grit/grit/tool/postprocess_interface.py
Python
bsd-3-clause
1,031
0.00388
# 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. ''' Base class for postprocessing of RC files. ''' from __future__ import print_function class PostProcessor(object): ''' Base class for postprocessi...
gs: rctext: string containing the contents of the RC file being processed. rcpath: the path used to access the file. g
rdtext: the root node of the grd xml data generated by the rc2grd tool. Return: The root node of the processed GRD tree. ''' raise NotImplementedError()
mindriot101/bokeh
examples/plotting/file/pie.py
Python
bsd-3-clause
1,053
0.004748
from math import pi import pandas as pd from bokeh.io import output_file, show from bokeh.palettes import Category20c from bokeh.plotting import figure from bokeh.transform import cumsum output_file("pie.html") x = { 'United States': 157, 'United Kingdom': 93, 'Japan': 89, 'China': 63, 'Germany'...
e']/data['
value'].sum() * 2*pi data['color'] = Category20c[len(x)] p = figure(plot_height=350, title="Pie Chart", toolbar_location=None, tools="hover", tooltips="@country: @value", x_range=(-0.5, 1.0)) p.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), ...
piquadrat/django
tests/postgres_tests/test_array.py
Python
bsd-3-clause
34,363
0.001659
import decimal import json import unittest import uuid from django import forms from django.core import checks, exceptions, serializers, validators from django.core.exceptions import FieldError from django.core.management import call_command from django.db import IntegrityError, connection, models from django.test imp...
eld=[[1, 2], [3, 4]]), [instance] ) def test_isnull(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__isnull=True), self.objs[-1:] ) def test_gt(self): self.assertSequenceEqual( NullableIntegerArrayM...
] ) def test_lt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__lt=[2]), self.objs[:1] ) def test_in(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[1], [2]]), ...
weso/CWR-DataApi
tests/parser/dictionary/encoder/record/test_component.py
Python
mit
2,680
0.000373
# -*- coding: utf-8 -*- import unittest import datetime from cwr.parser.encoder.dictionary import ComponentDictionaryEncoder from cwr.work import ComponentRecord """ ComponentRecord to dictionary encoding tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __stat...
TITLE', writer_1_last_name='LAST NAME 1', submitter_work_n='ABCD123',
writer_1_first_name='FIRST NAME 1', writer_2_first_name='FIRST NAME 2', writer_2_last_name='LAST NAME 2', writer_1_ipi_base_n='I-000000229-7', writer_1_ipi_name_n=14107338, ...
missionpinball/mpf
mpf/platforms/opp/opp.py
Python
mit
53,276
0.003942
# pylint: disable-msg=too-many-lines """OPP Hardware interface. Contains the hardware interface and drivers for the Open Pinball Project platform hardware, including the solenoid, input, incandescent, and neopixel boards. """ import asyncio from collections import defaultdict from typing import Dict, List, Set, Union,...
cfg_resp, ord(OppRs232Intf.READ_GEN2_INP_CMD): self.read_gen2_inp_resp_initial, ord(OppRs232Intf.GET_VERS_CMD): self.vers_resp, ord(OppRs232Intf.READ_MATRIX_INP): self.read_matrix_inp_resp_initial, } async def initialize(self): """Initialis
e connections to OPP hardware.""" await self._connect_to_hardware() self.opp_commands[ord(OppRs232Intf.READ_GEN2_INP_CMD)] = self.read_gen2_inp_resp self.opp_commands[ord(OppRs232Intf.READ_MATRIX_INP)] = self.read_matrix_inp_resp self._light_system = PlatformBatchLightSystem(self.machin...
PhenoImageShare/PhenoImageShare
VFB_import/src/VFB2PhisXML.py
Python
apache-2.0
15,991
0.00863
#!/usr/bin/env python import sys sys.path.append("../build/") import phisSchema import pyxb import warnings # Strategy: # Perhaps cleanest would be to build a separate interface for data that may vary from VFB. # This also allows separation of Jython code # OTOH - this gives another layer of mappings to maintain. ...
def add_signal_channel_visualisation_method(self, sfid): """sfid is the shortFormId o
f and FBbi visualisation method""" self.signal_channel_visualisation_methods.append(gen_OntologyTerm(self.ont_dict, sfid)) def add_background_channel_visualisation_method(self, sfid): """sfid is the shortFormId of and FBbi visualisation method""" self.background_channel_visualisatio...
t3dev/odoo
addons/test_mass_mailing/tests/test_mail_auto_blacklist.py
Python
gpl-3.0
4,008
0.002994
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common import datetime class TestAutoBlacklist(common.TransactionCase): def test_mail_bounced_auto_blacklist(self): mass_mailing_contacts = self.en
v['mail.mass_mailing.contact'] mass_mailing = self.env['mail.mass_mailing'] mail_blacklist = self.env['mail.blacklist'] mail_statistics = self.env['mail.mail.statistics'] mail_thread = self.env['mail.thread'] # create mailing contact record self.mailing_contact_1 = mass_...
wikimedia/pywikibot-wikibase
pywikibase/wbtime.py
Python
mit
4,755
0
# -*- coding: utf-8 -*- """ Exceptions """ # # (C) Pywikibot team, 2008-2015 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals import re import json try: long except NameError: long = int class WbTime(object): """A Wikibase time representation.""" PREC...
self.day = day self.hour = hour self.minute = minute self.second = second self.after = after self.before = before self.timezone = timezone self.calendarmodel = calend
armodel # if precision is given it overwrites the autodetection above if precision is not None: if (isinstance(precision, int) and precision in self.PRECISION.values()): self.precision = precision elif precision in self.PRECISION: ...
YiqunPeng/Leetcode-pyq
solutions/229MajorityElementII.py
Python
gpl-3.0
671
0.007452
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int]
""" num1, cnt1 = 0, 0 num2, cnt2 = 1, 0 for num in nums: if num == num1: cnt1 += 1 elif num == num2: cnt2 += 1 else: if cnt1 == 0: num1, cnt1 = num
, 1 elif cnt2 == 0: num2, cnt2 = num, 1 else: cnt1, cnt2 = cnt1 - 1, cnt2 - 1 return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
OpusVL/odoo
addons/share/wizard/share_wizard.py
Python
agpl-3.0
50,754
0.006147
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
hare."), 'view_type': fields.char('Current View Type',
required=True), 'domain': fields.char('Domain', help="Optional domain for further data filtering"), 'user_type': fields.selection(lambda s, *a, **k: s._user_type_selection(*a, **k),'Sharing method', required=True, help="Select the type of user(s) you would like to share data with.")...
nwjs/chromium.src
content/test/gpu/flake_suppressor/data_types_unittest.py
Python
bsd-3-clause
2,947
0.004411
#!/usr/bin/env vpython3 # Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from flake_suppressor import data_types class ExpectationUnittest(unittest.TestCase): def testAppliesToResultNon...
rror): _ = data_types.Result('suite', 't*', ('win', 'nvidia'), 'id') def testHashability(self): """Tests that Result objects are hashable.""" r = data_types.Result('suite', 'test', ('win', 'nvidia'), 'id') _ = set([r]) def testEquality(self): """Tests that
equality is properly calculated.""" r = data_types.Result('suite', 'test', ('win', 'nvidia'), 'id') other = data_types.Result('suite', 'test', ('win', 'nvidia'), 'id') self.assertEqual(r, other) other = data_types.Result('notsuite', 'test', ('win', 'nvidia'), 'id') self.assertNotEqual(r, other) ...
krischer/LASIF
lasif/window_selection.py
Python
gpl-3.0
36,635
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Window selection algorithm. This module aims to provide a window selection algorithm suitable for calculating phase misfits between two seismic waveforms. The main function is the select_windows() function. The selection process is a multi-stage process. Initially all...
be printed. """ print "[Window selection for %s] %s" % (tr_id, msg) # Dictionary to cache the TauPyModel so there is no need to reinitialize it # each time which is a fairly expensive operation. TAUPY_MODEL_CACHE = {} def select_windows(data_trace, synthetic_trace, event_latitude,
event_longitude, event_depth_in_km, station_latitude, station_longitude, minimum_period, maximum_period, min_cc=0.10, max_noise=0.10, max_noise_window=0.4, min_velocity=2.4, threshold_shift=0.30, threshold_correla...
belokop/indico_bare
indico/modules/rb/forms/reservations.py
Python
gpl-3.0
8,391
0.003814
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
dt')
super(ModifyBookingForm, self).__init__(*args, **kwargs) del self.room_id del self.submit_book del self.submit_prebook def validate_start_dt(self, field): super(NewBookingSimpleForm, self).validate_start_dt(field) new_start_dt = field.data now = datetime.now() ...
rizen1892/SmartHomeSolutions-Web
app/recording.py
Python
gpl-2.0
3,094
0.001616
class RecordingException(Exception): pass class Recording(object): def __init__(self, stream, lenght): import command self.name = None self.time = None self.lenght = lenght self.path = None self._temp_path = None self._processing_list = [] if i...
.path): os.unlink(self.path) def save(self, path): import os if not os.path.isdir(path): raise RecordingException("Input path does not exist or is not a folder: " + path) self.path = os.path.join(path, self.name) for command in self._processing_list: ...
import tempfile import datetime import timezone import os self.time = datetime.datetime.utcnow() self.time = self.time.replace(tzinfo=timezone.utc) self.name = self.time.strftime("%Y%m%d%H%M%S%f.mp4") name_h264 = self.time.strftime("%Y%m%d%H%M%S%f.h264") ...
colaftc/webtool
top/api/rest/TradePostageUpdateRequest.py
Python
mit
327
0.030581
''' Created by au
to_sdk on 2015.11.10 ''' from top.api.base import RestApi class TradePostageUpdateRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.post_fee = None self.tid = None def getapiname(self): return 'taobao.trade.p
ostage.update'
yishayv/lyacorr
physics_functions/delta_f_snr_bins.py
Python
mit
1,610
0.003106
""" A helper class for working with 2D bins of goodness-of-fit as a function of log(SNR). """ import numpy as np class DeltaFSNRBins(object): NUM_SNR_BINS = 50 NUM_DELTA_F_BINS = 50 LOG_SNR_RANGE = 6. LOG_SNR_OFFSET = 2. DELTA_F_RANGE = 1. DELTA_F_
OFFSET = 0. def __init__(self): pass def snr_to_bin(self, snr): if snr <= 0: return 0 return self.log_snr_to_bi
n(np.log(snr)) def log_snr_to_bin(self, log_snr): # type: (np.ndarray) -> np.ndarray return (np.clip((log_snr + self.LOG_SNR_OFFSET) * self.NUM_SNR_BINS / self.LOG_SNR_RANGE, 0, self.NUM_SNR_BINS - 1)).astype(np.int) def bin_to_log_snr(self, bin_num): # type: (n...
mdhaman/superdesk-core
tests/vocabularies_tests.py
Python
agpl-3.0
4,647
0.000215
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os im...
'copyrightHolder': 'foo holder', 'copyrightNotice': 'foo notice', 'usageTerms': 'foo terms' }, ] } with patch.object(service, 'find_one', return_value=vocab): info = service.get_rightsinfo({}) self.assertEqual...
info = service.get_rightsinfo({'source': 'foo'}) self.assertEqual('foo holder', info['copyrightholder']) self.assertEqual('foo notice', info['copyrightnotice']) self.assertEqual('foo terms', info['usageterms']) def test_get_locale_vocabulary(self): items = [ ...
arunkgupta/gramps
gramps/plugins/quickview/ageondate.py
Python
gpl-2.0
2,780
0.002518
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2009 Douglas S. Blank # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
tabase, date, return_range=True) # Doesn't show people probably alive but no way of figuring an age: if alive and birth: diff_span = (date - birth) stab.row(person, str(d
iff_span)) stab.row_sort_val(1, int(diff_span)) matches += 1 document.has_data = matches > 0 sdoc.paragraph(_("\n%d matches.\n") % matches) stab.write(sdoc) sdoc.paragraph("") def get_event_date_from_ref(database, ref): date = None if ref: handle = ref.get_refer...
ortutay/23andme-phenotypes-hackathon
my_app/my_app/migrations/0001_initial.py
Python
mit
829
0.003619
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-25 00:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models impor
t django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoF...
ld(max_length=1000, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
KelSolaar/sIBL_GUI
utilities/get_package_path.py
Python
gpl-3.0
2,062
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **get_package_path.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Write given package path to stdout. **Others:** """ from __future__ import unicode_literals import argparse import sys import foundations.decorators import foundations.verbo...
ath to stdout. :param package: Package to retrieve the path. :type package: unicode :return: Definition success. :rtype: bool """ package = __import__(package) sys.stdout.write(package.__path__[0]) return True def get_command_line_arguments(): """ Retrieves command line argu...
:return: Namespace. :rtype: Namespace """ parser = argparse.ArgumentParser(add_help=False) parser.add_argument("-h", "--help", action="help", help="'Displays this help message and exit.'") parser.add_argument("-p", ...
plotly/python-api
packages/python/plotly/plotly/validators/volume/slices/z/_fill.py
Python
mit
517
0.001934
import _plotly_utils.basevalidators class FillValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="fill", parent_name="volume.slices.z", **kwargs): super(FillValidator, self).__init__( plotly_n
ame=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 1), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"),
**kwargs )
brianhelba/pylibtiff
libtiff/bitarray-a1646c0/examples/compress.py
Python
bsd-3-clause
953
0
""" Demonstrates how the bz2 module may be used to create a compressed object which represents a bitarray. """ import bz2 from bitarray import bitarray def compress(ba): """ Given a bitarray, return an object which represents all information wi
thin the bitarray in a compresed form. The function `decompress` can be used to restore the bitarray from the compresed object. """ assert isinstance(ba, bitarray) return ba.length(), bz2.compress(ba.tobytes()), ba.endian() def decompress(obj): """ Given an object (created by `compress`), ...
a)) del res[n:] return res if __name__ == '__main__': a = bitarray(12345) a.setall(0) a[::10] = True c = compress(a) print(c) b = decompress(c) assert a == b, a.endian() == b.endian()
garoa/pingo
pingo/examples/rpi_examples/display7_anim.py
Python
mit
363
0
import pingo from time import sleep rpi = pingo.rpi.RaspberryPi() # A B C D E F G dp led_locations = [11, 7, 21, 24, 26, 13, 15, 19] pins = [rpi.pins[loc] for loc in
led_locations[:6]] for pin in pins: pin.mode = pingo.OUT pin.low() while True: for pin in pi
ns: pin.high() sleep(.04) pin.low()
scholer/cadnano2.5
cadnano/extras/fasta/__init__.py
Python
mit
102
0
""" This convenience module is t
o hard-code some example FASTA files for testing and development.
"""
zhupengjia/beampackage
beampackage/signalfilter.py
Python
gpl-3.0
32,657
0.043268
#!/usr/bin/env python import re,os,glob,sys,gc,ctypes,time import numpy as np try:import ROOT except:print "Error!! pyroot didn't compile! please recompile your root!" from array import array #from pylab import plot,show,subplot from bcmconst import * from runinfo import getpklpath,runinfo,zload,zdump try:from scipy.si...
(n,fc) if len(b)==len(a): normok=True break n-=1 if n<0: print "filter failed!you only have %i events for bpm, that's not enough for using filter!will use raw data instead!"%len(raw) return raw #w,h=freqz(b,a,n) sf=lfilter(b,a,raw) return np.float32(...
#trigger rate,here is helicity rate if 2*avefreq>=fs:return raw aveevents=int(fs/avefreq) Vave=avestack(aveevents) rawlen=len(raw) averaw=np.zeros(rawlen,dtype=np.float32) for i in range(rawlen): Vave.push(raw[i]) averaw[i]=Vave.ave() del Vave return averaw #get the total r...
lizardsystem/lizard-blockbox
lizard_blockbox/management/commands/parse_shapes_blockbox.py
Python
gpl-3.0
276
0
from django.core.management.base import BaseCommand from lizard_bl
ockbox import i
mport_helpers class Command(BaseCommand): help = "Parse the shapes for the blockbox data." def handle(self, *args, **kwargs): import_helpers.parse_shapes_blockbox(self.stdout)
firebase/grpc-SwiftPM
tools/run_tests/artifacts/artifact_targets.py
Python
apache-2.0
16,432
0.000609
#!/usr/bin/env python # Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
rsion): self.name = 'python_%s_%s_%s' % (platform, arch, py_version) self.platform = platform self.arch = arch self.labels = ['artifact', 'python', platform, arch, py_version] self.py_version = py_version if 'm
anylinux' in platform: self.labels.append('linux') def pre_build_jobspecs(self): return [] def build_jobspec(self): environ = {} if self.platform == 'linux_extra': # Raspberry Pi build environ['PYTHON'] = '/usr/local/bin/python{}'.format( ...
ollej/piapi
pidaemon.py
Python
mit
2,568
0.002336
"""pidaemon.py Usage: pidaemon.py [--brightness=<b>] [--sleep=<s>] [--interval=<s>] [--wait=<s>] pidaemon.py (-h | --help) pidaemon.py --version Options: -h --help Show this screen. --version Show version --brightness=<b> Default brightness level 1-255 [default: 2] --interval=<s> Def...
self.session.commit() def setup_signal_handlers(self): signal.signal(signal.SIGINT, self.cleanup) signal.signal(signal.SIGTERM, self.cleanup) def cleanup(self, signum, frame): if self.running
is not None: self.running.cleanup() sys.exit(-1) if __name__ == '__main__': opts = docopt(__doc__, version='PiDaemon v1.0') PiDaemon(opts).run()
cpennington/edx-platform
lms/djangoapps/instructor/tests/utils.py
Python
agpl-3.0
3,206
0.000624
""" Utilities for instructor unit tests """ import datetime import json import random import six from pytz import UTC from util.date_utils import get_default_time_display class FakeInfo(object): """Parent class for faking objects used in tests""" FEATURES = [] def __init__(self): for feature ...
s FakeTarget(object): """ Corresponding fake target for a fake email """ target_type = "expected" def long_display(self): """ Mocks out a class method """ return self.target_type class FakeTargetGroup(object): """ Mocks out the M2M relationship between FakeE
mail and FakeTarget """ def all(self): """ Mocks out a django method """ return [FakeTarget()] class FakeEmailInfo(FakeInfo): """ Fake email information object """ FEATURES = [ u'created', u'sent_to', u'email', u'number_sent', u'requester', ] ...
iw3hxn/LibrERP
product_extended/models/__init__.py
Python
agpl-3.0
1,187
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (C) 2016 Didotech srl
(<http://www.didotech.com>). # # 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 # the Free Software Foundation, either version 3 of the L
icense, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You s...
lokiteitor/ikol
ikol/config.py
Python
gpl-2.0
7,992
0.010636
# -*- coding: utf-8 -*- #Copyright (C) 2015 David Delgado Hernandez # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. ...
._CheckDirectory() self.cfgfile = ConfigParser() self.cfgfile.read(self.config_file) # Si todo esta bien requerir las configuraciones hechas por el # usuario en el archivo de configuracion # Directorios
secundarios # TODO : si se establece manualmente revisar que no se sobrepongan self.CACHE_DIR = self.getCacheDir() self.FINAL_DIR = self.getFinalDir() def _CheckDirectory(self): # Registro: (Client_secret,Archivo de Configuracion,URL.conf) check = [False,False,False] ...
lablup/sorna-manager
tests/manager/test_scheduler.py
Python
lgpl-3.0
16,173
0.000618
from __future__ import annotations from decimal import Decimal from typing import ( Any, Mapping, Sequence, ) import uuid from pprint import pprint import pytest from ai.backend.common.docker import ImageRef from ai.backend.common.types import ( AccessKey, AgentId, KernelId, ResourceSlot, Session...
ort load_scheduler from ai.backend.manager.scheduler.fifo import FIFOSlotScheduler, LIFOSlotScheduler from ai.backend.manager.scheduler.drf import DRFScheduler from ai.backend.manager.scheduler.mof import MOFScheduler def test_load_intrinsic(): assert isin
stance(load_scheduler('fifo', {}), FIFOSlotScheduler) assert isinstance(load_scheduler('lifo', {}), LIFOSlotScheduler) assert isinstance(load_scheduler('drf', {}), DRFScheduler) assert isinstance(load_scheduler('mof', {}), MOFScheduler) example_group_id = uuid.uuid4() example_total_capacity = ResourceSlo...
colossalbit/cssypy
cssypy/scanners/scanners.py
Python
bsd-3-clause
4,679
0.005984
from __future__ import absolute_import from __future__ import print_function import re import itertools from ..utils.py3compat import range from .. import csstokens as tokens class ScannerBase(object): def __init__(self, data): self._tokeniter = tokens.re_tokens.finditer(data) self._lineno = 1 ...
tokens.URI, tokens.BADCOMMENT, tokens.BADSTRING, tokens.BADURI, tokens.IDENT, tokens.ATKEYWORD_OTHER, tokens.DIMENSION, tokens.HASH, tokens.FUNCTION)) def advance_position(self, toktype, value): ...
es self._column = nlast + 1 else: self._column += len(value) else: self._column += len(value) def get_next(self): m = self._tokeniter.next() toktype = tokens.tokens[m.lastgroup] value = m.group() tok = tokens.To...
jishnuv/Toy-Python-Virtual-Machine
Testcases/Functions/f2.py
Python
gpl-2.0
131
0.045802
def sqr(x): return x*x def cube(x): return x*x*x def quad(x): return cube
(x)*x a =
10 print sqr(a) print cube(a) print quad(a)
RightToResearch/OpenCon-Rating-App
project/rating/urls.py
Python
mit
365
0
""" Applicati
on urlconfig """ from __future__ import absolute_import from django.conf.urls import url from . import views
urlpatterns = [ url( r"^(?P<uuid>[0-9a-f-]{36})/$", views.RateView.as_view(), name="rate" ), url( r"^2/(?P<uuid>[0-9a-f-]{36})/$", views.Rate2View.as_view(), name="rate2" ) ]
RewrZ/RewrZ
rewrz/blog/templatetags/blog_tags.py
Python
agpl-3.0
698
0.010479
from ..models import Post, Category, Tag from django.db.models.aggregates import Count from django import template register = template.Library() # 最近文章 @register.simple_tag def get_recent_posts(num=9): return Post.obj
ects.all().order_by('-modified_time')[:num] # 按月归档 @register.simple_tag def archives(): return Post.objects.dates('created_time', 'month', order='DESC') # 分类归档 @register
.simple_tag def get_categories(): return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0) # 标签云 @register.simple_tag def get_tags(): return Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
monikagrabowska/osf.io
website/addons/s3/tests/test_view.py
Python
apache-2.0
12,215
0.001474
# -*- coding: utf-8 -*- import httplib as http import mock from nose.tools import * # noqa from boto.exception import S3ResponseError from framework.auth import Auth from tests.base import get_default_metaschema from tests.factories import ProjectFactory, AuthUserFactory from website.addons.base import testing from...
_bucket_name(' leadingspace')) assert_false(validate_bucket_name('trailingspace ')) assert_false(validate_bucket_name('bogus naMe')) assert_false(validate_bucket_name('.cantstartwithp')) assert_false(validate_bucket_name('or.endwith.')) assert_fa
lse(validate_bucket_name('..nodoubles')) assert_false(validate_bucket_name('no_unders_in'))
pyoceans/gridded
examples/make_test_grid.py
Python
mit
1,437
0.004871
import numpy as np import matpl
otlib.pyplot as plt from shapely.geometry.polygon import Polygon from shapely.geometry import MultiPolygon import cell_tree2d # create a rotated Cartesian grid xc, yc = np.mgrid[1:10:15j, 1:20:18j] yc
= yc**1.2 + xc**1.5 def rot2d(x, y, ang): '''rotate vectors by geometric angle''' xr = x*np.cos(ang) - y*np.sin(ang) yr = x*np.sin(ang) + y*np.cos(ang) return xr, yr x, y = rot2d(xc, yc, 0.2) y /= 10.0 x -= x.mean() y -= y.mean() # Create nodes and faces from grid nodes = np.ascontiguousarray(np.co...
manti-by/Churchill
churchill/apps/profiles/models.py
Python
bsd-3-clause
2,037
0
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class StatsCalculationStrategy(model...
xt day"), ) avg_consumption = models.IntegerField( blank=True, default=settings.AVG
_ALCOHOL_CONSUMPTION, help_text=_("Average alcohol consumption in ml per year"), ) avg_price = models.DecimalField( max_digits=5, decimal_places=2, blank=True, default=settings.AVG_ALCOHOL_PRICE, help_text=_("Average alcohol price for 1000 ml"), ) stats_ca...
pgroudas/pants
src/python/pants/backend/android/targets/android_resources.py
Python
apache-2.0
1,346
0.008172
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pant...
\' that contains the target\'s '
'resource files.') def globs_relative_to_buildroot(self): return {'globs' : os.path.join(self.resource_dir, '**')}
technologiescollege/Blockly-rduino-communication
scripts_XP/Lib/site-packages/autobahn/wamp/test/test_uri_pattern.py
Python
gpl-3.0
24,741
0.001495
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
oduct': u'123456'}), (u"com.myapp..update", None), ] ), (u"com.myapp.<product>.update", [ (u"com.myapp.0.update", {u'product': u'0'}), (u"com.myapp.abc.update", {u
'product': u'abc'}), (u"com.myapp..update", None), ] ), (u"com.myapp.<category:string>.<subcategory:string>.list", [ (u"com.myapp.cosmetic.shampoo.list", {u'category': u'cosmetic', u'subcategory': u'shampoo'}), (u"com.myapp...list", Non...
bapril/cfa_635
cfa635/crc16.py
Python
apache-2.0
4,254
0.019041
#!/usr/bin/env python # crc16.py by Bryan G. Olson, 2005 # This module is free software and may be used and # distributed under the same terms as Python itself. """ CRC-16 in Python, as standard as possible. This is the 'reflected' version, which is usually what people want. See Ross N. Williams' /A Pain...
0x0BAF3, 0x05285, 0x0430C, 0x07197, 0x0601E, 0x014A1, 0x00528, 0x037B3, \ 0x0263A, 0x0DECD, 0x0CF44, 0x0FDDF, 0x0EC56, 0x098E9, 0x08960, 0x0BBFB, \ 0x0AA72, 0x06306, 0x0728F, 0x04014, 0x0519D, 0x02522, 0x034AB, 0x00630, \ 0x017B9, 0x0EF4E, 0x0FEC7, 0x0CC5C, 0x0DDD5, 0x0A96A, 0x0B8E3, 0x08A78, \ 0x09BF1,...
x0DCDD, 0x0CD54, 0x0B9EB, 0x0A862, 0x09AF9, \ 0x08B70, 0x08408, 0x09581, 0x0A71A, 0x0B693, 0x0C22C, 0x0D3A5, 0x0E13E, \ 0x0F0B7, 0x00840, 0x019C9, 0x02B52, 0x03ADB, 0x04E64, 0x05FED, 0x06D76, \ 0x07CFF, 0x09489, 0x08500, 0x0B79B, 0x0A612, 0x0D2AD, 0x0C324, 0x0F1BF, \ 0x0E036, 0x018C1, 0x00948, 0x03BD3, ...
hyperNURb/ggrc-core
src/tests/ggrc_workflows/generator.py
Python
apache-2.0
5,290
0.00397
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: miha@reciprocitylabs.com # Maintained By: miha@reciprocitylabs.com from datetime import date from ggrc import db from ggrc import builder from ggrc...
lf.modify(wf, obj_name, default) return response, workflow def modify_object(self, obj, data={}): obj = self._session_add(obj) obj_name = obj._inflector.table_singular obj_dict = builder.json.publish(obj) builder.json.publish_representation(obj_dict) obj_dict.update(data) obj_data = {...
sion_add(self, obj): """ Sometimes tests throw conflicting state present error.""" try: db.session.add(obj) return obj except: return obj.__class__.query.get(obj.id)
se-esss-litterbox/ess-its
IceCubeIocPython/OldItsPowerMeterIoc.py
Python
gpl-3.0
3,050
0.003279
import paho.mqtt.client as mqtt import time import json import sys import usbtmc #should be unique for each Ioc clientId = "itsPowerMeter01Ioc" subscribeTopic = "itsPowerMeter01/set/#" publishtopic = "itsPowerMeter01/get" periodicPollPeriodSecs = 1 # Power meter initialization usbInst = usbtmc.Instrument(2733, 27) u...
e, userKey) client.connect(brokerAddress, brokerPort, brokertimeout) client.loop_start() while True: time.sleep(periodicPollPeriodSecs) dataFromDevice = getDataFromDevice() if len
(dataFromDevice) > 0: client.publish(publishtopic, dataFromDevice, publishQos, True) if newIncomingMessage: handleIncomingMessage(incomingMessageTopic, incomingMessage) newIncomingMessage = False
shaneHowearth/Statutory_Holidays
Christmas_and_New_Year/Boxing_day.py
Python
gpl-2.0
1,049
0.003813
import datetime import astropy '''Boxing day is celebrated on the 26th of December, each year. If Boxing day falls on the weekend it is moved to the following Monday or Tuesday Boxing Day is observed on the 28th if the 26th falls on a Saturday or Sunday ''' def get_holiday(year): ''' Calculate the observed da...
ueError("Year must be > 1") DECEMBER = 12 if datetime.date(year, DECEMBER, 26).weekday() in (5,6): # Christmas_and_New_Year falls on the weekend return datetime.date(year, DECEMBER, 28) else: return datetime.date(year, DECEMBER, 26) def get_actual(year): ''' Boxing Day is ...
:return: datetime object set for the observed date ''' if year < 1: raise ValueError("Year must be > 1") DECEMBER = 12 return datetime.date(year, DECEMBER, 26)
jefftc/changlab
Betsy/Betsy/modules/plot_geneset_score_bar.py
Python
mit
1,784
0.006726
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib import os from genomicode imp...
.mkdir(outfile) for one_data in data: value = one_data[1:] value = [float(i
) for i in value] pair = [(value[i], sample[i]) for i in range(len(value))] pair.sort() gene_value = [i[0] for i in pair] label = [i[1] for i in pair] ylabel = one_data[0] from genomicode import mplgraph fig = mplgraph.barplot(gene_valu...
DS-100/sp17-materials
sp17/labs/lab06/ok_tests/q4.py
Python
gpl-3.0
642
0.003115
test = { 'name': 'Question 4', 'points': 1, 'suites': [ {
'cases': [ { 'code': r""" >>> rows7 = {('Joey', 7), ('Henry', 7)} >>> rows6 = {('Ian', 6), ('Joyce', 6)} >>> q4_answer[0] == ("John", 8) True >>> all([tuple(row) in rows7 for row in q4_answer[1:3]]) True >>> all([tuple(row...
answer[3:5]]) True """, 'hidden': False, 'locked': False }, ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
showell/zulip
analytics/management/commands/stream_stats.py
Python
apache-2.0
2,358
0.003393
from argparse import ArgumentParser from typing import Any from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from zerver.models import Message, Realm, Recipient, Stream, Subscription, get_realm class Command(BaseCommand): help = "Generate statistics on the streams ...
e stream count private_count = 0 # public stream count public_count = 0 for stream in streams: if stream.
invite_only: private_count += 1 else: public_count += 1 print("------------") print(realm.string_id, end=' ') print("{:>10} {} public streams and".format("(", public_count), end=' ') print(f"{private_count} private s...
hatwar/buyback-erpnext
erpnext/accounts/doctype/account/account.py
Python
agpl-3.0
8,576
0.024254
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint from frappe import throw, _ from frappe.model.document import Document class RootNotEditable(frappe.V...
d account exists for this account. You can not delete this account.")) def on_trash(self): self.validate_trash() self.update_nsm_model() def before_rename(self, old, new, merge=False): # Add company abbr if not provided from erpnext.setup.doctype.company.company import get_name_with_abbr new_account = get...
ount {0} does not exist").format(new)) val = list(frappe.db.get_value("Account", new_account, ["is_group", "root_type", "company"])) if val != [self.is_group, self.root_type, self.company]: throw(_("""Merging is only possible if following properties are same in both records. Is Group, Root Type, Company...
FedoraScientific/salome-smesh
src/SMESH_SWIG/PAL_MESH_041_mesh.py
Python
lgpl-2.1
2,975
0.009748
# -*- coding: iso-8859-1 -*- # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE # # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesse...
------------------------------------ #----------Vertexes------------ p1 = geompy.
MakeVertex(20.0,30.0,40.0) p2 = geompy.MakeVertex(90.0,80.0,0.0) p3 = geompy.MakeVertex(30.0,80.0,200.0) #----------Edges--------------- e1 = geompy.MakeEdge(p1,p2) e2 = geompy.MakeEdge(p2,p3) e3 = geompy.MakeEdge(p3,p1) #----------Wire---------------- ListOfEdges = [] ListOfEdges.append(e3) ListOfEdges.append(e2) Li...
nurhandipa/python
codecademy/string_methods.py
Python
gpl-3.0
72
0
//co
decademy cour
se answer parrot = "Norwegian Blue" print len(parrot)
mcalmer/spacewalk
client/rhel/rhn-client-tools/src/actions/reboot.py
Python
gpl-2.0
1,358
0.005891
#!/usr/bin/python2 # Client code for Update Agent # Copyright (c) 1999--2018 Red Hat, Inc. Distributed under GPLv2. # # Author: Adrian Likins <alikins@redhat.com # import os __rhnexport__ = [ 'reboot'] from up2date_client import up2dateLog from up2date_client import config cfg = config.initUp2dateConfig() log...
if test: os.execvp("/sbin/shutdown", ['/sbin/shutdown','-r','-k', '+3', reboot_message]) else: os.execvp("/sbin/shutdown", ['/sbin/shutdown','-r', '+3', reboot_message]) except OSError: data['name'] = "reboot.reboot.shutdown_fail
ed" return (34, "Could not execute /sbin/shutdown", data) log.log_me("Rebooting the system now") # no point in waiting around return (0, "Reboot sucessfully started", data) def main(): print(reboot(test=1)) if __name__ == "__main__": main()
helix84/activae
deployment/__init__.py
Python
bsd-3-clause
3,590
0
# Copyright (C) 2010 CENATIC: Centro Nacional d
e Referencia de # Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # Redistributions in binary f...
erasche/argparse2tool
argparse2tool/cmdline2gxml/__init__.py
Python
apache-2.0
1,040
0.002885
import logging impor
t sys from argparse2tool import load_argparse logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Arg2GxmlParser: def __init__(self): ap = load_argparse() # avoid circular imports help_text = ( "argparse2tool forms Galaxy XML and CWL tools from Python s...
tly using the Galaxy XML invocation which may have different options from the CWL invocation." ) arg2tool_parser = ap.ArgumentParser( prog=sys.argv[0], description=help_text, formatter_class=ap.RawDescriptionHelpFormatter, add_help=False ) arg2tool_parser.add_arg...
firmlyjin/brython
www/tests/unittests/test/test_syslog.py
Python
bsd-3-clause
1,104
0.005435
from test import support syslog = support.import_module("syslog") #skip if not supported import unittest # XXX(nnorwitz): This test sucks. I don'
t know of a platform independent way # to verify that the messages were really logged. # The only purpose of this test is to verify the code doesn't crash or leak. class Test(unittest.TestCase): def test_openlog(self): syslog.openlog('python') # Issue #6697. self.assertRaises(UnicodeEncode...
slog('test message from python test_syslog') syslog.syslog(syslog.LOG_ERR, 'test error from python test_syslog') def test_closelog(self): syslog.openlog('python') syslog.closelog() def test_setlogmask(self): syslog.setlogmask(syslog.LOG_DEBUG) def test_log_mask(self): ...
remitamine/youtube-dl
youtube_dl/extractor/vimeo.py
Python
unlicense
46,520
0.001721
# coding: utf-8 from __future__ import unicode_literals import base64 import functools import json import re import itertools from .common import InfoExtractor from ..compat import ( compat_kwargs, compat_HTTPError, compat_str, compat_urlparse, ) from ..utils import ( clean_html, determine_ext...
rce_url, 'preference': 1, }) subtitles = {} text_tracks = config['request'].get('text_tracks') if text_tracks: for tt in text_tracks: subtitles[tt['lang']] = [{ 'ext': 'vtt', 'url': urljoin('https://...
}] thumbnails = [] if not is_live: for key, thumb in video_data.get('thumbs', {}).items(): thumbnails.append({
mxOBS/deb-pkg_trusty_chromium-browser
native_client/PRESUBMIT.py
Python
bsd-3-clause
7,031
0.008107
# Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Documentation on PRESUBMIT.py can be found at: # http://www.chromium.org/developers/how-tos/depottools/presubmit-scripts import os import sys # ...
igrate code_hygiene to a common location so that # it can be used by the commit queue. old_sys_path = list(sys.path) try: sys.path.append(os.path.join(NACL_TOP_DIR, 'tools')
) sys.path.append(os.path.join(NACL_TOP_DIR, 'build')) import code_hygiene finally: sys.path = old_sys_path del old_sys_path affected_files = input_api.AffectedFiles(include_deletes=False) exclude_dirs = [ NACL_TOP_DIR + '/' + x + '/' for x in EXCLUDE_PROJECT_CHECKS_DIRS ] fo...
xibosignage/xibo-pyclient
plugins/media/MicroblogMedia.py
Python
agpl-3.0
27,626
0.010715
#!/usr/bin/python # -*- coding: utf-8 -*- # # Xibo - Digitial Signage - http://www.xibo.org.uk # Copyright (C) 2010-11 Alex Harrington # # This file is part of Xibo. # # Xibo 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...
tmpIdentica = self.updateIdentica()
tmpPosts = [] # Deduplicate the posts we've pulled in from Twitter against Identica and __posts for post in tmpTwitter: inIdentica = False inPosts = False # See if the post is in the t...
onepesu/django_transmission
torrents/views.py
Python
mit
371
0.002695
import json from django.http import HttpResponse from django.shortcuts import render from torrents.logic import active_torrents_info def active(request): if request.is_ajax(): content = {"torrents
": active_torrents_info()} return HttpResponse(json.dumps(content), content_type="application/json") return render(request, "torrents/ac
tive.html")
eliasdesousa/indico
indico/modules/events/logs/controllers.py
Python
gpl-3.0
1,324
0.001511
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from indico.modules.events.logs.models.entries import EventLogEntry from indico.modules.events.logs.views import WPEventLogs from indico.modules.events.management...
lf): entries = self.event.log_entries.order_by(EventLogEntry.logged_dt.desc()).all() realms = {e.realm for e in entries} return WPEventLogs.render_template('logs.html', self.event, entries=entries, realms=realms)
unicef/rhizome
rhizome/tests/test_api_source_object_map.py
Python
agpl-3.0
5,601
0.005892
from rhizome.tests.base_test_case import RhizomeApiTestCase from rhizome.models.indicator_models import Indicator from rhizome.models.document_models import SourceObjectMap, \ DocumentSourceObjectMap from pandas import read_csv from rhizome.tests.setup_helpers import TestSetupHelpers class SourceObjectMapResour...
f, '/api/v1/source_object_map/%s/' % self.som_0.id) self.assertHttpOK(get_resp_1) response_data_1 = self.deserialize(get_resp_1) self.ass
ertEqual(response_data_1['master_object_id'], -1) def test_som_get_doc_id(self): get_data = {'document_id': self.document.id, 'is_mapped': 1} resp = self.test_setup.get( self, '/api/v1/source_object_map/', get_data) self.assertHttpOK(resp) data = self.deserialize(resp) ...
pawkoz/dyplom
blender/intern/cycles/blender/addon/osl.py
Python
gpl-2.0
4,371
0.002974
# # Copyright 2011-2013 Blender Foundation # # 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...
shutil.copy2(oso_path, dst_path) except: report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path) elif os.p
ath.dirname(node.filepath) == "": # module in search path oso_path = node.filepath oso_file_remove = False ok = True else: # unknown report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name") ...
liupangzi/codekata
leetcode/Algorithms/110.BalancedBinaryTree/Solution.py
Python
mit
712
0.001404
# 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 isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self.dfsHeight(root) != -1 def dfsHeight(self, root): if not root: return 0 left_height = self.dfsHeight(ro...
.left) right_height = self.dfsHeight(root.right) if left_height == -1 or right_height == -1: return -1 if abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1
Vb2341/image-junk
fhead.py
Python
mit
217
0.018433
#! /usr/bin/env python import sys, glo
b from astropy.io import fits try: ext = int(sys.argv[2]) except: ext = 0 prin
t sys.argv[1] ims = glob.glob(sys.argv[1]) for im in ims: print repr(fits.getheader(im, ext))
brantje/telegram-github-bot
captain_hook/services/telegram/__init__.py
Python
apache-2.0
77
0
from __fu
ture__ import absolute_import from .telegram import TelegramService
marcindulak/accts
accts/asegpaw/3.6.0-0.9.0.8965/ase/test.py
Python
gpl-3.0
142
0.007042
i
mport sys import subprocess result = subprocess.Popen('sh test.sh', shell=True) text = result.communic
ate()[0] sys.exit(result.returncode)
pmisik/buildbot
master/buildbot/test/unit/www/test_roles.py
Python
gpl-2.0
3,892
0.000514
# redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICUL...
username="homer", groups=["employee", "buildbot-maintainer", "buildbot-admin"])) self.assertEqual(ret, ["maintainer", "admin"]) class RolesFromEmails(unittest.TestCase): def setUp(self): self.roles = roles.RolesFromEmails( employee=["homer@plant.com", "burns@plant.com"],...
om"]) def test_noUser(self): ret = self.roles.getRolesFromUser(dict( username="lisa", email="lisa@school.com")) self.assertEqual(ret, []) def test_User1(self): ret = self.roles.getRolesFromUser(dict( username="homer", email="homer@plant.com")) self.asser...
bradfortner/Convergence-Jukebox-Experimental
working_popup_progress_bar rewrite.py
Python
gpl-3.0
1,763
0.016449
import kivy from kivy.app import App from kivy.clock import Clock from kivy.uix.popup import Popup from kivy.uix.progressbar import ProgressBar from kivy.uix.widget import Widget from kivy.properties import ObjectProperty kivy.require("1.9.1") class MyPopupProgressBar(Widget): progress_bar = ObjectProperty() # Ki...
if self.progress_bar.value >= 100: # Checks to see if progress_bar.value has met 100 return False # Returning False schedule is canceled and won't repeat self.progress_bar.value += 1 # Updates progress_bar's progress def puopen(self, instance): # Called from bind. Clock.schedule_i...
t() every 5-1000th of a second. class MyApp(App): def build(self): return MyPopupProgressBar() if __name__ in ("__main__"): MyApp().run()
ElofssonLab/pcons-fold
pconsc/plotting/parse_fasta.py
Python
mit
3,026
0.004296
#!/usr/bin/env python import string, copy import sys def read_fasta(afile, query_id=''): """Parses any fasta, a2m, a3m file, sequence or alignment file. @param afile input file @param query_id ID of query sequence (default='') Ensures: key of a given query ID only contains its ID...
r = aline[1:] # otherwise concatenate sequence else: #aline_seq = aline.translate(None, '
.-').upper() seq += aline # add last entry if header != '': if seq_dict.has_key(header): seq_dict[header].append(seq) else: seq_dict[header] = [seq] else: sys.stderr.write('ERROR: file empty or wrong file format') return seq_dict ...
wallarelvo/rover
rover/plot.py
Python
apache-2.0
3,026
0.00033
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm def plot_risk_grid(risk_grid, filename): fig = plt.figure("Risk Map") ax = fig.add_subplot(111) ax.set_xlabel("X Location") ax.set_ylabel("Y Location") x_step = 1 y_step = 1 x_min = 0 y_min = 0 x_max = r...
x_max = time_grid.width - 1 self.y_max = time_grid.height - 1 self.x = np.arange(self.x_min, self.x_max, self.x_step) self.y = np.arange(self.y_min, self.y_max, self.y_step) self.X, self.Y = np.meshgrid(self.x, self.y) plt.ion() self.get_zs() self.ax.set_xlim(self...
def get_zs(self): zs = np.array( [ self.time_grid.get_raw(x_i, y_i) for x_i, y_i in zip(np.ravel(self.X), np.ravel(self.Y)) ] ) return zs def update(self): try: self.graph.remove() except: p...
CaptainDesAstres/Frames-Animated-By-Curve
single_track/SingleTrack.py
Python
gpl-3.0
1,451
0.052378
from .Peaks import Peaks from .Amplitude import Amplitude from .Combination import Combination from .OutputFrame import OutputFrame from .Track import Track from .panels import Panel import bpy class SingleTrack( bpy.types.PropertyGroup, Panel, Track, Amplitude, Combination, OutputFrame, Peaks ): ''' ...
on = bpy.data.actions.new( name= clip.name
+'Action') # check and get peaks shapes peak_shapes = self.check_and_get_peaks_shapes() if type(peak_shapes) is str: return peak_shapes # update amplitude net curve amplitude_net_curve = self.update_net_amplitude_curve( clip, context ) # update peaks curve peaks_curve = self.update_peaks_cu...
voidabhi/python-scripts
webhook-fb-messenger.py
Python
mit
1,193
0.003353
import json import requests from django.views.decorators.csrf import csrf_exempt FB_MESSENGER_ACCESS_TOKEN = "[TOKEN]" def respond_FB(sender_id, text): json_data = { "recipient": {"id": sender_id}, "message": {"text": text + " to you!"} } params = { "access_token": FB_MESSENGER_A...
uest.method == "GET": if (request.GET.get('hub.verify_token') == 'this_is_a_verify_token_created_by_sean'): return HttpResponse(request.GET.get('hub.challenge')) return HttpResponse('Error, wrong validation token') if request.method == "POST": body = request.body
print("BODY", body) messaging_events = json.loads(body.decode("utf-8")) print("JSON BODY", body) sender_id = messaging_events["entry"][0]["messaging"][0]["sender"]["id"] message = messaging_events["entry"][0]["messaging"][0]["message"]["text"] respond_FB(sender_id, messag...
kimlab/GPyM
granule2map.py
Python
mit
1,360
0.025735
#! /usr/bin/python #-------------------------------------------------------------------- # PROGRAM : granule2map.py # CREATED BY : hjkim @IIS.2015-07-13 11:56:07.989735 # MODIFED BY : # # USAGE : $ ./granule2map.py # # DESCRIPTION: #------------------------------------------------------cf0.2@20120401 import ...
'^001',BBox=BBox) # default mapCode:^001 aOut = zeros( (Grid.lat.size,Grid.lon.size), 'float32' )-9999.9 yIdx = nearest_idx(Grid.lat, lat.flatten()) xIdx = nearest_idx(Grid.lon, lon.flatten()) aOut[yIdx, xIdx] = aSrc.flatten() nFold = int( res/Grid.res ) aOut = upscale(...
, mode='s', missing=-9999.9) if verbose: print '\t[GRANULE2MAP] Domain:%s %s -> %s'%( BBox, aSrc.shape, aOut.shape) return aOut
bodleian/stats-time-cache
collate/custom_variables.py
Python
gpl-3.0
8,288
0.009411
'''A collection of tasks to perform related to Piwik custom variables.''' import logging import re import dbsources import dbengine class Populate(object): '''Take existing data and populate custom variables.''' def __init__(self): self.CONFIG = None # tables and fields to use self.CONNECTION ...
) source.setup_source1() host, username, password, database = source.get_settings() self.CONFIG = dbengine.PiwikConfig(
) #self.CONFIG.setup_custom_vars(1) # check count finds stuff self.CONNECTION = dbengine.Connection() self.CONNECTION.setup(host, username, password, database) # Count existing data def sql_count_customvar_scode(self): count = self.CONFIG.FIELD_CUSTOM_VARS_SCODE ...
skuda/client-python
kubernetes/client/models/v1_label_selector.py
Python
apache-2.0
4,559
0.001535
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if b...
al """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
pmitros/DoneXBlock
tests/conftest.py
Python
agpl-3.0
842
0
import pytest from mock import Mock from workbench.runtime import WorkbenchRuntime from xblock.fields import ScopeIds from xblock.runtime import DictKeyValueStore, KvsFieldData from done.done import DoneXBlock def generate_scope_ids(runtime, block_type): """ helper to generate scope IDs for an XBlock """ de...
_id = runtime.id_generator.create_definition(block_type) usage_id = runtime.id_generator.create_usage(def_id) return ScopeIds('user', block_type, def_id, usage_id) @pytest.fixture def done_xblock(): """Done XBlock pytest fixture.""" runtime = WorkbenchRuntime() key_store = DictKeyValueStore() ...
e, 'done') done_xblock = DoneXBlock(runtime, db_model, scope_ids=ids) done_xblock.usage_id = Mock() return done_xblock
Zertifica/evosnap
evosnap/merchant_applications/pos_device.py
Python
mit
806
0.007444
from evosnap import constants cl
ass POSDevice: def __init__(self,**kwargs): self.__order = [ 'posDeviceType', 'posDeviceConnection', 'posDeviceColour', 'posDeviceQuantity', ] self.__lower_camelcase = constants.ALL_FIELDS
self.pos_device_type = kwargs.get('pos_device_type') self.pos_device_connection = kwargs.get('pos_device_connection') self.pos_device_colour = kwargs.get('pos_device_colour') self.pos_device_quantity = kwargs.get('pos_device_quantity') @property def hash_str(self): required = ...
OpenHumans/open-humans
public_data/migrations/0003_auto_20190508_2341.py
Python
mit
834
0
# Generated by Django 2.2.1 on 2019-05-08 23:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("private_sharing", "0022_auto_20190507_1843"), ("public_data", "0002_auto_20171213_1947"), ] operations = [ ...
null=True, on_delete=django.db.models.deletion.CASCADE, to="private_sharing.DataRequestProjectMember", ), ), migrations.AlterField( model_name="publicdataaccess", name="data_source", field=models.CharField(max_length=100, ...
), ]
kohr-h/tomok
ctf.py
Python
gpl-3.0
3,242
0.000925
# -*- coding: utf-8 -*- """ ctf.py -- contrast transfer function in electron tomography Copyright 2014 Holger Kohr This file is part of tomok. tomok 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 versio...
.polyval(self.env_polycoeff, freq2)) return np.where(freq2 < self.cutoff2, ctfval, 0.0) # TODO: display method class ContrTransFuncA
CR(object): """Callable class for the constant acr CTF. TODO: finish this.""" def __init__(self, emcfg, acr=0.1): ocoeff = emcfg.osc_polycoeff ocoeff[3] = np.arctan(acr) self.osc_polycoeff = ocoeff self.env_polycoeff = emcfg.env_polycoeff self.cutoff2 = (emcfg.waven...
xlqian/navitia
source/tyr/tests/integration/autocomplete_test.py
Python
agpl-3.0
9,528
0.001364
# coding: utf-8 # Copyright (c) 2001-2018, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to...
_parameters/')
assert len(resp) == 1 def test_get_last_datasets_autocomplete(create_autocomplete_parameter): """ we query the loaded datasets of idf we loaded 3 datasets, but by default we should get one by family_type, so one for bano, one for osm """ resp = api_get('/v0/autocomplete_parameters/idf/last_dat...
ContinuumIO/dask
dask/array/tests/test_atop.py
Python
bsd-3-clause
17,215
0.00151
import collections import warnings from operator import add import pytest import numpy as np import dask import dask.array as da from dask.highlevelgraph import HighLevelGraph from dask.blockwise import Blockwise, rewrite_blockwise, optimize_blockwise, index_subs from dask.array.utils import assert_eq from dask.array...
cts.values() if isinstance(layer, Blockwise)]) == 1 ) def test_blockwise_non_blockwise_output(): x = da.ones(10, chunks=(5,)) y = ((x + 1) + 2) + 3 w = y.sum() z = ((y * 2) * 3) * 4 z_top_before = tuple(z.dask.dicts[z.name].indices) (zz,) = dask.optimize(z) z_top_after = tuple...
isinstance(dsk, HighLevelGraph) assert ( len([layer for layer in dsk.dicts.values() if isinstance(layer, Blockwise)]) == 1 ) dsk = optimize_blockwise( HighLevelGraph.merge(w.dask, z.dask), keys=list(dask.core.flatten([w.__dask_keys__(), z.__dask_keys__()])), ) assert...
chrsrds/scikit-learn
sklearn/feature_selection/univariate_selection.py
Python
bsd-3-clause
28,149
0.000355
"""Univariate features selection.""" # Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay. # L. Buitinck, A. Joly # License: BSD 3 clause import numpy as np import warnings from scipy import special, stats from scipy.sparse import issparse from ..base import BaseEstimator from ..prepr...
functions # The following function is a rewriting of scipy.stats.f_oneway # Contrary to the scipy.stats.f_oneway implementation it does not # copy the data while keeping the inputs unchanged. def f_oneway(*args): """Performs a 1-way ANOVA. The one-way ANOVA tests the null hypothesis that 2 or more groups hav...
the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- *args : array_like, sparse matrices sample1, sample2... The sample measurements should be given as arguments. Returns ------- F-value : float The computed F-value of the test. p-value : floa...
antoinecarme/pyaf
tests/artificial/transf_Difference/trend_Lag1Trend/cycle_7/ar_12/test_artificial_128_Difference_Lag1Trend_7_12_20.py
Python
bsd-3-clause
266
0.086466
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cy
cle_length = 7, transform = "Difference", si
gma = 0.0, exog_count = 20, ar_order = 12);