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 |
|---|---|---|---|---|---|---|---|---|
amueller/ThisPlace | app.py | Python | mit | 1,992 | 0.006024 | #!/usr/bin/env python
import bottle
from bottle import (
get,
run,
abort,
static_file,
template
)
import thisplace
example_locs = [("sydney", (-33.867480754852295, 151.20700120925903)),
("battery", (40.70329427719116, -74.0170168876648)),
("san_fran", (37.79011487... | turn template('map', lat=lat, lng=lng, fourwords=fourwords)
except:
return template('index',
err="Could not find location {}".format(fourwords),
**example_locs)
# API
@get('/api/<lat: | float>,<lng:float>')
def latLngToHash(lat, lng):
try:
three = thisplace.three_words((lat,lng))
four = thisplace.four_words((lat,lng))
six = thisplace.six_words((lat,lng))
return {'three': three, 'four': four, 'six': six}
except:
return {}
@get('/api/<fourwords>')
def ha... |
rg3915/orcamentos | selenium/selenium_login.py | Python | mit | 613 | 0 | from decouple import config
from selenium import webdriver
HOME = config('HOME' | )
# page = webdriver.Firefox()
page = webdriver.Chrome(executable_path=HOME + '/chromedriver/chromedriver')
page.get('http://localhost:8000/admin/login/')
# pegar o campo de busca onde podemos digitar algum termo
campo_busca = page.find_element_by_id('id_username')
campo_busca.send_keys('admin')
campo_busca = page.fi... | page.findElement(By.cssSelector("input[type='submit']"))
button = page.find_element_by_xpath("//input[@type='submit']")
button.click()
|
furritos/mercado-api | mercado/core/safeway.py | Python | mit | 6,259 | 0.003834 | # -*- coding: UTF-8 -*-
import datetime
import json
import logging
import re
from mercado.core.base import Mercado
from mercado.core.common import nt_merge
log = logging.getLogger(__name__)
class Safeway(Mercado):
def __init__(self, auth, urls, headers, sleep_multiplier=1.0):
self.auth = auth
se... | erId": self.auth.get("username"),
"password": self.auth.get("password")})
rsp = self._run_request(self.urls.login, login_data, self.headers.extra)
rsp_data = json.loads(rsp.content.decode("UTF-8"))
if not rsp_data.get("token") or rsp_data.get("errors"):
raise Exception("... | ryPro": self.r_s.cookies.get_dict().get("swyConsumerDirectoryPro")})
self.headers.extra.update(
{"X-swyConsumerlbcookie": self.r_s.cookies.get_dict().get("swyConsumerlbcookie")})
def _get_store_id(self):
log.info("Determining Safeway store ID")
rsp = self._run_request(self.urls.... |
hawkphantomnet/leetcode | WaterAndJugProblem/Solution.py | Python | mit | 545 | 0 | class Solution(object):
def myGCD(self, x, y):
| if y == 0:
return x
else:
return self.my | GCD(y, x % y)
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
if x == 0 and y == z:
return True
if x == z and y == 0:
return True
if x == z or y == z:
return T... |
EarToEarOak/RTLSDR-Scanner | setup.py | Python | gpl-3.0 | 2,016 | 0.001488 | #
# rtlsdr_scan
#
# http://eartoearoak.com/software/rtlsdr-scanner
#
# Copyright 2012 - 2017 Al Brown
#
# A frequency scanning GUI for the OsmoSDR rtl-sdr library at
# http://sdr.osmocom.org/trac/wiki/rtl-sdr
#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gene... | : Scientific/Engineering :: Visualization'],
keywords='rtlsdr spectrum analyser',
url='http://eartoearoak.com/software/rtlsdr-scanner',
author='Al Brown',
author_email= | 'al@eartoearok.com',
license='GPLv3',
packages=find_packages(),
package_data={'rtlsdr_scanner.res': ['*']},
install_requires=['numpy', 'matplotlib', 'Pillow', 'pyrtlsdr', 'pyserial', 'visvis'])
|
Chilledheart/chromium | tools/valgrind/drmemory/PRESUBMIT.py | Python | bsd-3-clause | 1,175 | 0.009362 | # 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.
"""
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
def Ch... | put_api):
"""Checks the DrMemory suppression files for bad suppressions."""
# TODO(timurrrr): find out how to do relative imports
# and remove this ugly hack. Also, the CheckChange fu | nction won't be needed.
tools_vg_path = input_api.os_path.join(input_api.PresubmitLocalPath(), '..')
import sys
old_path = sys.path
try:
sys.path = sys.path + [tools_vg_path]
import suppressions
return suppressions.PresubmitCheck(input_api, output_api)
finally:
sys.path = old_path
def CheckC... |
rowhit/h2o-2 | py/testdir_0xdata_only/test_hdfs_multi_copies.py | Python | apache-2.0 | 1,029 | 0.013605 | import unittest, time, sys
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@c | lassmethod
def setUpClass(cls):
# assume we're at 0xdata with it's hdfs namenode
h2o.init(1, use_hdfs=True, hdfs_version='cdh4', hdfs_name_node='mr-0x6')
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_hdfs_multi_copies(self):
print "\nUse the new re... | browseTheCloud()
# defaults to /datasets
parseResult = h2i.import_parse(path='datasets/manyfiles-nflx-gz/*', schema='hdfs', hex_key='manyfiles.hex',
exclude=None, header=None, timeoutSecs=600)
print "parse result:", parseResult['destination_key']
sys.stdout.flush()
if __na... |
marvinpinto/charlesbot | tests/util/parse/test_message_parser.py | Python | mit | 1,817 | 0 | import unittest
from charlesbot.util.parse import parse_msg_with_prefix
class TestMessageParser(unittest.TestCase):
def test_prefix_uppercase(self):
msg = "!ALL hi, there!"
retval = parse_msg_with_prefix("!all", msg)
self.assertEqual("hi, there!", retval)
def test_prefix_mixed(self):... | x("!all", msg)
self.assertEqual(None, retval)
def test_prefix_invalid_two(self):
msg = "!allhi, there!"
retval = parse_msg_with_prefix("!all", msg)
self.asse | rtEqual(None, retval)
|
starrify/scrapy | scrapy/settings/default_settings.py | Python | bsd-3-clause | 9,161 | 0.000982 | """
This module contains the default values for all settings used by Scrapy.
For more information about these settings you can read the settings
documentation in docs/topics/settings.rst
Scrapy developers, if you add a setting here remember to:
* add it in alphabetical order
* group similar settings without leaving ... | 'scrapy.extensions.feedexport.GCSFeedStorage',
's3': 'scrapy.extensions.feedexport.S3FeedStorage',
'stdout': | 'scrapy.extensions.feedexport.StdoutFeedStorage',
}
FEED_EXPORT_BATCH_ITEM_COUNT = 0
FEED_EXPORTERS = {}
FEED_EXPORTERS_BASE = {
'json': 'scrapy.exporters.JsonItemExporter',
'jsonlines': 'scrapy.exporters.JsonLinesItemExporter',
'jl': 'scrapy.exporters.JsonLinesItemExporter',
'csv': 'scrapy.exporters.Cs... |
prheenan/BioModel | EnergyLandscapes/InverseWeierstrass/Python/TestExamples/Testing/MainTestingWeightedHistograms.py | Python | gpl-2.0 | 747 | 0.013387 | # force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.py | plot as plt
import sys
sys.path.append("../../../../../../")
from Util import Test
from Util.Test import _f_assert,HummerData,load_simulated_data
from FitUtil.EnergyLandscapes.InverseWeierstrass.Python.Code import \
InverseWeierstrass,WeierstrassUtil,WeightedHistogram
def assert_all_digitization_correct(objs):
... | tion_correct(fwd)
assert_all_digitization_correct(rev)
if __name__ == "__main__":
run()
|
LLNL/spack | var/spack/repos/builtin/packages/tbl2asn/package.py | Python | lgpl-2.1 | 866 | 0.002309 | # 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)
from os import chmod
from spack import *
class Tbl2asn(Package):
"""Tbl2asn is a co | mmand-line program that automates the creation of
sequence records for submission to GenBank."""
homepage = "https://www.ncbi.nlm.nih.gov/genbank/tbl2asn2/"
version('2020-03-01', sha256='7cc1119d3cfcbbffdbd4ecf33cef8bbdd44fc5625c729 | 76bee08b1157625377e')
def url_for_version(self, ver):
return "https://ftp.ncbi.nih.gov/toolbox/ncbi_tools/converters/by_program/tbl2asn/linux.tbl2asn.gz"
def install(self, spec, prefix):
mkdirp(prefix.bin)
install('../linux.tbl2asn', prefix.bin.tbl2asn)
chmod(prefix.bin.tbl2asn... |
zfrenchee/pandas | pandas/tests/test_base.py | Python | bsd-3-clause | 43,476 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
import re
import sys
from datetime import datetime, timedelta
import pytest
import numpy as np
import pandas as pd
import pandas.compat as compat
from pandas.core.dtypes.common import (
is_object_dtype, is_datetimetz,
needs_i8_conversion)
import pa... | result = getattr(o, op)
# these couuld be series, arrays or scalars
if isinstance(result, Series) and isinstance(expected, Series):
tm.assert_series_equal( | result, expected)
elif isinstance(result, Index) and isinstance(expected, Index):
tm.assert_index_equal(result, expected)
elif isinstance(result, np.ndarray) and isinstance(expected,
np.ndarray):
... |
magenta/magenta | magenta/models/onsets_frames_transcription/infer_util_test.py | Python | apache-2.0 | 1,356 | 0.001475 | # Copyright 2022 The Magenta 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 or agreed to in ... | f
tf.disable_v2_behavior()
class InferUtilTest(tf.test.TestCase):
| def testProbsToPianorollViterbi(self):
frame_probs = np.array([[0.2, 0.1], [0.5, 0.1], [0.5, 0.1], [0.8, 0.1]])
onset_probs = np.array([[0.1, 0.1], [0.1, 0.1], [0.9, 0.1], [0.1, 0.1]])
pianoroll = infer_util.probs_to_pianoroll_viterbi(frame_probs, onset_probs)
np.testing.assert_array_equal(
[[... |
whbruce/upm | examples/python/bmx055.py | Python | mit | 2,781 | 0.001798 | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without l... | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_bmx055 as sensorObj
def main():
# Instantiate a BMX055 instance using default i2c bus an... | function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print("Exiting")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
sig... |
romanorac/discomll | discomll/ensemble/core/k_medoids.py | Python | apache-2.0 | 1,504 | 0.001995 | """
Special purpose k - medoids algorithm
"""
import numpy as np
def fit(sim_mat, D_len, cidx):
"""
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contain | s mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetric distance matrix
k: int - number of clusters
"""
min_energy = np.inf
for j in range(3):
# select indices in each sample that maximizes its dimension
... | ent enengy
for i in np.unique(inds):
indsi = np.where(inds == i)[0] # find indices for every cluster
minind, min_value = 0, 0
for index, idy in enumerate(indsi):
if idy in sim_mat:
# value = sum([sim_mat[idy].get(idx,0) for idx in indsi])... |
andreyvit/pyjamas | pyjs/src/pyjs/sm.py | Python | apache-2.0 | 5,725 | 0.003493 | import os
from pyjs import linker
from pyjs import translator
from pyjs import util
from optparse import OptionParser
import pyjs
PLATFORM='spidermonkey'
APP_TEMPLATE = """
var $wnd = new Object();
$wnd.document = new Object();
var $doc = $wnd.document;
var $moduleName = "%(app_name)s";
var $pyjs = new Object();
$pyj... | in__');
} catch(exception)
{
var fullMessage = exception.name + ': ' + exception.message;
var uri = exception.fileName;
//var stack = exception.stack;
var line = exception.lineNumber;
fullMessage += "\\n at " + uri + " | : " + line;
print (fullMessage );
//print (stack.toString() );
}
"""
class SpidermonkeyLinker(linker.BaseLinker):
"""Spidermonkey linker, which links together files by using the
load function of the spidermonkey shell."""
# we derive from mozilla
platform_parents = {
PLATFORM:['mozilla... |
boldprogressives/django-opendebates | opendebates/opendebates_comments/forms.py | Python | apache-2.0 | 7,408 | 0.006479 | import time
from django import forms
from django.forms.util import ErrorDict
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.crypto import salted_hmac, constant_time_compare
from django.utils.encoding import force_text
from django.utils.text import get_text_... | mailField(label=_("Email address"), widget=forms.Hidd | enInput)
url = forms.URLField(label=_("URL"), required=False, widget=forms.HiddenInput)
comment = forms.CharField(label=_('Comment'), widget=forms.Textarea,
max_length=COMMENT_MAX_LENGTH)
def get_comment_object(self):
"""
Return a new (uns... |
idea4bsd/idea4bsd | python/helpers/pydev/build_tools/generate_code.py | Python | apache-2.0 | 5,381 | 0.003531 | '''
This module should be run to recreate the files that we generate automatically
(i.e.: modules that shouldn't be traced and cython .pyx)
'''
from __future__ import print_function
import os
import struct
def is_python_64bit():
return (struct.calcsize('P') == 8)
root_dir = os.path.join(os.path.dirname(__file... | setup_cython.py',
'interpreterInfo.py',
):
pydev_files.append(" '%s': PYDEV_FILE," % (f,))
contents = template % (dict(pydev_files='\n'.join(sorted(pydev_files))))
assert 'pydevd.py' in contents
assert 'pydevd_dont_trace.py' in contents
wit... | emove_if_exists(f):
try:
if os.path.exists(f):
os.remove(f)
except:
import traceback;traceback.print_exc()
def generate_cython_module():
remove_if_exists(os.path.join(root_dir, '_pydevd_bundle', 'pydevd_cython.pyx'))
target = os.path.join(root_dir, '_pydevd_bundle', 'pydevd... |
eonpatapon/contrail-controller | src/nodemgr/config_nodemgr/event_manager.py | Python | apache-2.0 | 616 | 0.006494 | #
# | Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
#
from gevent import monkey
monkey.patch_all()
from pysandesh.sandesh_base import sandesh_global
from sandesh_common.vns.ttypes import Module
from nodemgr.com | mon.event_manager import EventManager, EventManagerTypeInfo
class ConfigEventManager(EventManager):
def __init__(self, config, unit_names):
type_info = EventManagerTypeInfo(
module_type=Module.CONFIG_NODE_MGR,
object_table='ObjectConfigNode')
super(ConfigEventManager, self)... |
uclouvain/osis | program_management/ddd/repositories/program_tree_version.py | Python | agpl-3.0 | 19,400 | 0.002165 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | mmon_queryset().filter(
version_name=entity_id.version_name,
offer__acronym=entity_id.offer_acronym,
offer__academic_year__year=entity_id.year,
transition_nam | e=entity_id.transition_name,
)
try:
return _instanciate_tree_version(qs.get())
except EducationGroupVersion.DoesNotExist:
raise exception.ProgramTreeVersionNotFoundException()
@classmethod
def get_last_in_past(cls, entity_id: 'ProgramTreeVersionIdentity') -> 'Pro... |
nephomaniac/eucio | eucio/topology/userfacing/__init__.py | Python | apache-2.0 | 611 | 0.001637 | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, 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.apach | e.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed un | der 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. |
znegva/pelican-plugins | pelican_comment_system/avatars.py | Python | agpl-3.0 | 2,305 | 0.023861 | # -*- coding: utf-8 -*-
"""
"""
from __future__ import unicode_literals
import logging
import os
import hashlib
logger = logging.getLogger(__name__)
_log = "pelican_comment_system: avatars: "
try:
from . identicon import identicon
_identiconImported = True
except ImportError as e:
logger.warning(_log + "identi... | = True
def _createIdenticonOutputFolder():
if not _ready():
return
if not os.path.exists(_identicon_save_path):
os.makedirs(_identicon_save_path)
def getAvatarPath(comment_id, metadata):
if not _ready():
return ''
md5 = hashlib.md5()
author = tuple()
for data in _identicon_data:
if data in metadata:... | ])
md5.update(string.encode('utf-8'))
author += tuple([string])
else:
logger.warning(_log + data + " is missing in comment: " + comment_id)
if author in _authors:
return _authors[author]
global _missingAvatars
code = md5.hexdigest()
if not code in _missingAvatars:
_missingAvatars.append(code)
r... |
LauritzThaulow/fakelargefile | tests/test_segmenttail.py | Python | agpl-3.0 | 365 | 0 | '''
Created on Nov 10, 2014
@author: lauritz
'''
from mock import Mock |
from fakelargefile.segmenttail import OverlapSearcher
def test_index_iter_stop():
os = OverlapSearcher("asdf")
segment = Mock()
segment.start = 11
try:
os.index_iter(segment, stop=10).next()
except ValueError:
assert True
else:
| assert False
|
anhstudios/swganh | data/scripts/templates/object/static/structure/general/shared_palette_supply_01.py | Python | mit | 455 | 0.048352 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMEN | TATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/general/shared_palette_supp | ly_01.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
duncanmmacleod/gwsumm | gwsumm/plot/__init__.py | Python | gpl-3.0 | 1,636 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013)
#
# This file is part of GWSumm.
#
# GWSumm 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) ... | arranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU | General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.
"""A `Plot` is a representation of an image to be included in the HTML
output a :doc:`tab </tabs>`.
For simple purposes, a `Plot` is just a reference to an existing image file
that can be imported into an HTML page via the ``<im... |
jambonsw/django-improved-user | example_integration_project/config/urls.py | Python | bsd-2-clause | 312 | 0 | """Integration project URL Configuration"""
from django.contrib import admin
from django.urls import re_path
from dj | ango.views.generic import Templat | eView
urlpatterns = [
re_path(r"^admin/", admin.site.urls),
re_path(
r"^$", TemplateView.as_view(template_name="home.html"), name="home"
),
]
|
tzpBingo/github-trending | codespace/python/tencentcloud/ie/v20200304/models.py | Python | mit | 146,031 | 0.003101 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | meber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(m | emeber_set))
class AudioInfo(AbstractModel):
"""音频参数信息
"""
def __init__(self):
r"""
:param Bitrate: 音频码率,取值范围:0 和 [26, 256],单位:kbps。
注意:当取值为 0,表示音频码率和原始音频保持一致。
:type Bitrate: int
:param Codec: 音频编码器,可选项:aac,mp3,ac3,flac,mp2。
:type Codec: str
:para... |
voxelbrain/dibble | dibble/update.py | Python | bsd-3-clause | 2,635 | 0.000759 | # -*- coding: utf-8 -*-
import collections
class InvalidOperatorError(ValueError):
pass
class DuplicateFieldError(ValueError):
pass
class FieldDict(dict):
def __setitem__(self, k, v):
if k in self:
raise DuplicateFieldError('Field "{0}" already set.'.format(k))
super(Field... | >>> update.rename('old', 'new')
>>> dict(update)
{'$rename': {'old': 'new'}}
"""
self._ops['$rename'][old] = new
def unset(self, name):
self._ops['$unset'][name] = 1
def push(self, name, value):
self._ops['$push'][name] = value
def pushAll(self, name, v... | ):
v = (-1 if first else 1)
self._ops['$pop'][name] = v
def pull(self, name, value):
self._ops['$pull'][name] = value
def pullAll(self, name, values):
self._ops['$pullAll'][name] = values
|
ogata-lab/rtmsdk-mac | x86_64/lib/python2.7/site-packages/omniidl_be/cxx/header/template.py | Python | lgpl-2.1 | 39,776 | 0.001282 | # -*- python -*-
# Package : omniidl
# template.py Created on: 2000/01/18
# Author : David Scott (djs)
#
# Copyright (C) 2003-2008 Apasphere Ltd
# Copyright (C) 1999 AT&T Laboratories Cambridge
#
# This file is part of omniidl.
#
# omniidl is free software; you... | 6:10 dpg1
# New object | table behaviour, correct POA semantics.
#
# Revision 1.5.2.11 2001/08/03 17:41:17 sll
# System exception minor code overhaul. When a system exeception is raised,
# a meaning minor code is provided.
#
# Revision 1.5.2.10 2001/07/31 19:25:11 sll
# Array _var should be separated into fixed and variable size ones.
#
... |
Wevolver/HAVE | docs/source/conf.py | Python | gpl-3.0 | 9,459 | 0.006026 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Multiple documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 14 09:34:49 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | test',
# 'sphinx.ext.todo',
# 'sphinx.ext.coverage',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = ' | .rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Multiple'
copyright = '2016, Wevolver'
author = 'Wevolver'
# The version info for the project you're documenting, acts as replacement for
# |ve... |
huangshenno1/algo | project_euler/1.py | Python | mit | 84 | 0.02381 | sum = 0
for i i | n range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
print sum | |
cpennington/edx-platform | common/djangoapps/student/rules.py | Python | agpl-3.0 | 894 | 0.004474 | """
Django rules for student roles
"""
from __future__ import absolute_import
import rules
fro | m lms.djangoapps.courseware.access import has_access
from openedx.core.djangoapps.waffle_utils import CourseWaffleFlag, WaffleFlag, WaffleFlagNamespace
from .roles import CourseDataResearcherRole
# Waffle flag to enable the separate course outline page and full width content.
RESEARCHER_ROLE = CourseWaffleFlag(Waffle... | """
Returns whether the user can access the course data downloads.
"""
is_staff = user.is_staff
if RESEARCHER_ROLE.is_enabled(course_id):
return is_staff or CourseDataResearcherRole(course_id).has_user(user)
else:
return is_staff or has_access(user, 'staff', course_id)
rules.add_per... |
obi-two/Rebelion | data/scripts/templates/object/tangible/component/weapon/shared_projectile_feed_mechanism.py | Python | mit | 498 | 0.044177 | #### | NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/weapon/shared_projectile_feed_mechanism.iff"
result.attribute... | stfName("craft_weapon_ingredients_n","projectile_feed_mechanism")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
BrianLusina/Arco | server/app/mod_home/views.py | Python | mit | 557 | 0.001795 | """
Entry point to API application. This will be for running simple checks on the application
"""
from flask import jsonify, url_for, redirect, request
from flask_login import current_user
from . import home
from ..__meta__ import __version__, __project__, __copyright__
|
@home.route("")
@home.route("home")
@home.route("index")
def index():
"""
Entry point into the app
:return: renders the api information
"""
return jsonify({
"version": __version__,
"pro | ject": __project__,
"copyright": __copyright__
})
|
botswana-harvard/edc-data-manager | edc_data_manager/view_mixins/data_manager_view_mixin.py | Python | gpl-2.0 | 2,162 | 0 | from django.contrib import messages
from django.views.generic.base import ContextMixin
from edc_constants.constants import OPEN
from ..models import DataActionItem
from ..model_wrappers import DataActionItemModelWrapper
from .user_details_check_view_mixin import UserDetailsCheckViewMixin
class DataActionItemsViewMi... | @property
def data_action_item(self):
"""Returns a wrapped saved or unsaved consent version.
"""
model_obj = DataActionItem(subject_identifier=self.subject_identifier)
return DataActionItemModelWrapper(model_obj=model_obj)
def data_action_items(self):
"""Return a list ... | ed', 'resolved']
data_action_items = DataActionItem.objects.filter(
subject_identifier=self.subject_identifier,
status__in=status).order_by('issue_number')
for data_action_item in data_action_items:
wrapped_data_action_items.append(data_action_item)
return wra... |
dims/heat | heat/tests/convergence/scenarios/update_replace_rollback.py | Python | apache-2.0 | 1,550 | 0.000645 | #
# 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
# ... | License for the specific language governing permissions and limitations
# under the License.
def check_c_count(expected_count):
test.assertEqual(expected_count,
len(reality.resources_by_ | logical_name('C')))
example_template = Template({
'A': RsrcDef({'a': 'initial'}, []),
'B': RsrcDef({}, []),
'C': RsrcDef({'!a': GetAtt('A', 'a')}, ['B']),
'D': RsrcDef({'c': GetRes('C')}, []),
'E': RsrcDef({'ca': GetAtt('C', '!a')}, []),
})
engine.create_stack('foo', example_template)
engine.noop(5... |
1kastner/analyse_weather_data | plot_weather_data/__init__.py | Python | agpl-3.0 | 1,869 | 0.003215 | """
"""
import os
import pandas
from matplotlib import pyplot
from matplotlib import dates as mdates
import matplotlib.ticker as mticker
PROCESSED_DATA_DIR = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
"processed_data"
)
def insert_nans(station_df):
"""
Only when NaNs... | _formatter = mdates.DateFormatter('%b')
def strftime(self, dt, fmt=None):
windows_month_name = dt.strftime("%b")
if windows_month_name = | = "Mrz":
return "März"
if windows_month_name == "Mai":
return "Mai"
if windows_month_name == "Jun":
return "Juni"
if windows_month_name == "Jul":
return "Juli"
if windows_month_name == "Sep":
return "Sept."
abbreviated_m... |
CalvinHsu1223/LinuxCNC-EtherCAT-HAL-Driver | src/emc/usr_intf/touchy/mdi.py | Python | gpl-2.0 | 10,007 | 0.006196 | # Touchy is Copyright (c) 2009 Chris Radek <chris@timeguy.com>
#
# Touchy 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.
#
# Touchy i... | ocodes.append(call)
self.codes[call] = args
def get_description(self, gcode):
return self.codes[gcode][0]
| def get_words(self, gcode):
self.gcode = gcode
if gcode[0] == 'M' and gcode.find(".") == -1 and int(gcode[1:]) >= 100 and int(gcode[1:]) <= 199:
return ['P', 'Q']
if not self.codes.has_key(gcode):
return []
# strip description
words = self.codes[gcode]... |
hgl888/chromium-crosswalk-efl | tools/binary_size/run_binary_size_analysis.py | Python | bsd-3-clause | 35,816 | 0.010051 | #!/usr/bin/env python
# Copyright 2014 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.
"""Generate a spatial analysis against an arbitrary library.
To use, build the 'binary_size_tool' target. Then run this tool, passing
... | e=F0401
# Node dictionary keys. These are output in json read by the webapp so
# keep them short to save file size.
# Note: If these change, the webapp must also change.
NODE_TYPE_KEY = 'k'
NODE_NAME_KEY = 'n'
NODE_CHILDREN_KEY = 'children'
NO | DE_SYMBOL_TYPE_KEY = 't'
NODE_SYMBOL_SIZE_KEY = 'value'
NODE_MAX_DEPTH_KEY = 'maxDepth'
NODE_LAST_PATH_ELEMENT_KEY = 'lastPathElement'
# The display name of the bucket where we put symbols without path.
NAME_NO_PATH_BUCKET = '(No Path)'
# Try to keep data buckets smaller than this to avoid killing the
# graphing lib.... |
qunying/gps | docs/tutorial/conf.py | Python | gpl-3.0 | 8,459 | 0.006975 | # -*- coding: utf-8 -*-
#
# Tutorial documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 8 12:57:03 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '../users_guide/favicon.ico'
# | Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at e... |
insolite/alarme | alarme/extras/sensor/web/views/core.py | Python | mit | 386 | 0 | from aiohttp.web import View, HTTPFound
def http_found(func):
| async | def wrapped(self, *args, **kwargs):
await func(self, *args, **kwargs)
return HTTPFound(self.request.rel_url)
return wrapped
class CoreView(View):
sensor = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.logger = self.sensor.logger
|
ESOedX/edx-platform | lms/djangoapps/discussion/rest_api/tests/test_serializers.py | Python | agpl-3.0 | 34,613 | 0.001416 | """
Tests for Discussion API serializers
"""
from __future__ import absolute_import
import itertools
import ddt
import httpretty
import mock
import six
from django.test.client import RequestFactory
from six.moves.urllib.parse import urlparse # pylint: disable=import-error
from lms.djangoapps.discussion.django_comme... | "course_id": six.text_type(self.course.id),
"commentable_id": "test_topic",
"user_id": str(self.author.id),
"username": self.author.username,
"title": "Test Title",
"body": "Test body",
"pinned": True,
"votes": {"up_count": 4},
... | t": 4,
"comment_count": 6,
"unread_comment_count": 3,
"pinned": True,
"editable_fields": ["abuse_flagged", "following", "read", "voted"],
})
self.assertEqual(self.serialize(thread), expected)
thread["thread_type"] = "question"
expected.upd... |
victorkeophila/alien4cloud-cloudify3-provider | src/test/resources/outputs/blueprints/openstack/tomcat/plugins/custom_wf_plugin/setup.py | Python | apache-2.0 | 650 | 0.001538 | from setuptools import setup
# Replace the place holders with values for your project
setup(
# Do not use underscores in the plugin name.
name='custom-wf-plugin',
version='0.1',
author='alien',
author_email='alien@fastc | onnect.fr',
description='custom generated workflows',
# This must correspond to the actual packages in the plugin.
packages=['plugin'],
license='Apache',
zip_safe=True,
install_requires=[
# Necessary dependency for developing plugins, do not rem | ove!
"cloudify-plugins-common>=3.2"
],
test_requires=[
"cloudify-dsl-parser>=3.2"
"nose"
]
) |
ergoregion/pyqt-units | pyqt_units/MeasurementWidgets.py | Python | mit | 6,390 | 0.002191 |
#Created on 14 Aug 2014
#@author: neil.butcher
from PySide2 import QtCore, QtWidgets
from pyqt_units.CurrentUnitSetter import setter
class UnitDisplay(QtWidgets.QWidget):
def __init__(self, parent, measurement=None, measurementLabel='normal'):
QtWidgets.QWidget.__init__(self, parent)
self.layo... | easurementLabel = measurementLabel
self._box.currentIndexChanged.connect(self.changedToIndex)
setter.changed.connect(self.currentUnitChangedElsewhere)
self.setMeasurement(measurement)
self._update()
@QtCore.Slot(str, str, str)
def currentUnitChangedElsewhere(self, measName, unit... | = self.measurement.name:
pass
elif not measurementLabel == self._measurementLabel:
pass
else:
self._update()
def setMeasurement(self, measurement):
self.measurement = None
self._box.clear()
if measurement is None:
pass
... |
onelab-eu/sfa | sfa/util/xrn.py | Python | mit | 10,231 | 0.010849 | #----------------------------------------------------------------------
# Copyright (c) 2008 Board of Trustees, Princeton University
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, i... | n_to_hrn(self):
"""
compute tuple (hrn, type) from urn
"""
# if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
if not Xrn.is_urn(self.urn):
raise SfaAPIError, "Xrn.urn_to_hrn"
parts = Xrn.urn_split(self.urn)
type=parts.pop(2)
... | is is a bad hack, but its either this
# or completely change how record types are generated/stored
if name != 'sa':
type = type + "+" + name
name =""
else:
name = parts.pop(len(parts)-1)
# convert parts (list) into hrn (str) by doing the... |
paul-jean/ud858 | Lesson_2/000_Hello_Endpoints/helloworld_api.py | Python | gpl-3.0 | 1,742 | 0.012055 | """Hello World API implemented using Google Cloud Endpoints.
Contains declarations of endpoint, endpoint methods,
as well as the ProtoRPC message class and container required
for endpoint method definition.
"""
import endpoints
from protorpc import messages
from protorpc import message_types |
from protorpc import remote
# If the request contain | s path or querystring arguments,
# you cannot use a simple Message class.
# Instead, you must use a ResourceContainer class
REQUEST_CONTAINER = endpoints.ResourceContainer(
message_types.VoidMessage,
name=messages.StringField(1)
)
REQUEST_GREETING_CONTAINER = endpoints.ResourceContainer(
period=messages.St... |
vikramsunkara/PyME | pyme/lazy_dict.py | Python | agpl-3.0 | 3,974 | 0.007549 | """
Dictionary with lazy evaluation on access, via a supplied update function
"""
import itertools
class LazyDict(dict):
"""
A dictionary type that lazily updates values when they are accessed.
All the usual dictionary methods work as expected, with automatic lazy
updates occuring behind the | scenes whenever values are read from the
dictionary.
The optional ``items`` argument, if specified, is a mapping instance used
to initialise the items in the :class:`LazyDict`.
The ``update_value`` argument required by the :class:`LazyDict` constructor
must be a function of the form:
... | lue
This function is called whenever an item with the key ``k`` is read
from the :class:`LazyDict`. The second argument ``existing_value``, is
the value corresponding to the key ``k`` stored in the :class:`LazyDict`,
or ``None``, if the key ``k`` is not contained in the :class:`LazyDict`.
The t... |
opencloudinfra/orchestrator | venv/Lib/site-packages/registration/__init__.py | Python | gpl-3.0 | 666 | 0 | VERSION = (2, 0, 4, 'final', 0)
def get_version():
"""
Re | turns a PEP 386-compliant version number from VERSION.
"""
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc relea... | SION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
|
Open365/Open365 | lib/Wrappers/Logger.py | Python | agpl-3.0 | 1,007 | 0.000993 | import logging
import os
from lib.Settings import Settings
from lib.Wrappers.NullLo | gger import NullLogger
class Logger:
def __init__(self, name):
if 'UNITTESTING' in os.environ:
self.logging = NullLogger()
else:
settings = Settings().getSettings()
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
... | self.logging = logging.getLogger(name)
def debug(self, *args, **kwargs):
self.logging.debug(*args, **kwargs)
def info(self, *args, **kwargs):
self.logging.info(*args, **kwargs)
def warning(self, *args, **kwargs):
self.logging.warning(*args, **kwargs)
def error(self, *args... |
nimbusproject/epumgmt | src/python/epumgmt/main/em_args.py | Python | apache-2.0 | 3,947 | 0.00532 | from epumgmt.api.actions import ACTIONS
from epumgmt.main import ControlArg
import optparse
a = []
ALL_EC_ARGS_LIST = a
################################################################################
# EM ARGUMENTS
#
# The following cmdline arguments may be queried via Parameters, using either
# the 'name' as the ar... | (shell script adds the default)."
DRYRUN = ControlArg("dryrun", None, noval=True)
#a.append(DRYRUN)
DRYRUN.help = "Do as little real things as possible, will | still affect filesystem, for example logs and information persistence. (not implemented yet)"
KILLNUM = ControlArg("killnum", "-k", metavar="NUM")
a.append(KILLNUM)
KILLNUM.help = "For the fetchkill action, number of VMs to terminate."
NAME = ControlArg("name", "-n", metavar="RUN_NAME")
a.append(NAME)
NAME.help = "U... |
garoa/pingo | pingo/test/level1/cases.py | Python | mit | 1,331 | 0.000751 | import pingo
'''
In order to use this set of cases, it is necessary to set
the following attributes on your TestCase setUp:
self.analog_input_pin_number = 0
self.expected_analog_input = 1004
self.expected_analog_ratio = 0.98
'''
class AnalogReadBasics(object):
'''
Wire a 10K Ohm resistence fr... | analog_input + 3
def test_pin_ratio(self):
pin = self.board.pins[self.analog_input_pin_number]
pin.mode = pingo.ANALOG
bits_resolution = (2 ** pin.bits) - 1
_input = pin.ratio(0, bits_resolution, 0.0, 1.0)
# print "Value Read: ", _input
# Two decimal places check
... | def test_wrong_output_mode(self):
pin = self.board.pins[self.analog_input_pin_number]
with self.assertRaises(pingo.ModeNotSuported):
pin.mode = pingo.OUT
|
ReconCell/smacha | smacha_ros/test/smacha_diff_test_examples.py | Python | bsd-3-clause | 3,604 | 0.003607 | #!/usr/bin/env python
import sys
import argparse
import os
import unittest2 as unittest
from ruamel import yaml
from smacha.util import Tester
import rospy
import rospkg
import rostest
ROS_TEMPLATES_DIR = '../src/smacha_ros/templates'
TEMPLATES_DIR = 'smacha_templates/smacha_test_examples'
WRITE_OUTPUT_FILES = Fa... | rated', file_b='original'))
if __name__=="__main__":
# Read the configuration file before parsing arguments,
try:
base_path = os.path.dirname(os.path.abspath(__file__))
conf_file_loc = os.path.join(base_path, CONF_FILE)
f | = open(conf_file_loc)
CONF_DICT = yaml.load(f)
except Exception as e:
print('Failed to read the configuration file. See error:\n{}'.format(e))
exit()
if CONF_DICT.has_key('WRITE_OUTPUT_FILES'):
WRITE_OUTPUT_FILES = CONF_DICT['WRITE_OUTPUT_FILES']
if CONF_DICT.has_key('OUTPUT... |
pliniopereira/ccd10 | src/business/shooters/EphemerisShooter.py | Python | gpl-3.0 | 6,596 | 0.001365 | import datetime
import math
import time
import ephem
from PyQt5 import QtCore
from src.business.EphemObserverFactory import EphemObserverFactory
from src.business.configuration.configProject import ConfigProject
from src.business.configuration.settingsCamera import SettingsCamera
from src.business.consoleThreadOutput... | self.max_lunar_elevation = 0
self.max_lunar_phase = 0
infocam = self.camconfig.get_camera_settings()
try:
self.s = int(infocam[4])
except Exception as e:
self.s = 0
|
def calculate_moon(self, obs):
aux = obs
aux.compute_pressure()
aux.horizon = '8'
moon = ephem.Moon(aux)
return aux.previous_setting(moon), aux.next_rising(moon)
def calculate_sun(self, obs):
aux = obs
aux.compute_pressure()
aux.horizon = '-12'
... |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/voicerepublic.py | Python | gpl-3.0 | 3,272 | 0.025978 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urlparse,
)
from ..utils import (
ExtractorError,
determine_ext,
int_or_none,
sanitized_Request,
)
class VoiceRepublicIE(InfoExtractor):
_VALID_URL = r'https?://voicerepublic\.com/(?:... | and companies that operate secret surveillance programs can be surveilled.',
'thumbnail': r're:^https?://.*\.(?:png|jpg)$',
'duration': 1800,
'view_count': int,
}
}, {
'url': 'http://voicerepublic.com/embed/watching-the-watchers-building-a-sousveillance-state',
'only_matching': True,
}]
def _real_ext... | rlparse.urljoin(url, '/talks/%s' % display_id))
# Older versions of Firefox get redirected to an "upgrade browser" page
req.add_header('User-Agent', 'youtube-dl')
webpage = self._download_webpage(req, display_id)
if '>Queued for processing, please stand by...<' in webpage:
raise ExtractorError(
'Audio i... |
brettwooldridge/buck | programs/buck_project.py | Python | apache-2.0 | 6,332 | 0.000632 | # Copyright 2018-present Facebook, 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 i... | elf.root, ".buckjavaargs")
self.buck_javaargs = get_file_contents_if_exists(buck_javaargs_path)
buck_javaargs_path_local = os.path.join(self.root, ".buckjavaargs.local")
self.buck_javaargs_local = get_file_contents_if_exists(buck_javaargs_path_local)
def get_root_hash(self):
return... | t_file_path(self):
if os.name == "nt":
return u"\\\\.\\pipe\\buckd_{0}".format(self.get_root_hash())
else:
return os.path.join(self.buckd_dir, "sock")
def get_buckd_transport_address(self):
if os.name == "nt":
return "local:buckd_{0}".format(self.get_root... |
palmtree5/Red-DiscordBot | redbot/cogs/audio/core/__init__.py | Python | gpl-3.0 | 5,241 | 0.000382 | import asyncio
import datetime
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Mapping
import aiohttp
import discord
from redbot.core import Config
from redbot.core.bot import Red
from redbot.core.commands import Cog
from redbot.core.data_manager import cog_data_p... | url_keyword_blacklist=[],
url_keyword_whitelist=[],
country_code="US",
)
_playlist: Mapping = dict(id=None, author=None, name=None, playlist_url=None, tracks=[])
self.config.init_custom("EQUALIZER", 1)
self.config.register_custom("EQUALIZER", eq_bands=[], eq_p... | config.init_custom(PlaylistScope.GLOBAL.value, 1)
self.config.register_custom(PlaylistScope.GLOBAL.value, **_playlist)
self.config.init_custom(PlaylistScope.GUILD.value, 2)
self.config.register_custom(PlaylistScope.GUILD.value, **_playlist)
self.config.init_custom(PlaylistScope.USER.valu... |
chemelnucfin/tensorflow | tensorflow/python/data/experimental/kernel_tests/csv_dataset_test.py | Python | apache-2.0 | 20,082 | 0.004531 | # 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 applic... | ']]
self._test_by_comparison(inputs, record_defaults=record_defaults)
def testCsvDataset_string(self):
record_defaults = [['']] * 4
inputs = [['1.0,2.1,hello,4.3', '5.4,6.5,goodbye,8.7']]
self._test_by_com | parison(inputs, record_defaults=record_defaults)
def testCsvDataset_withEmptyFields(self):
record_defaults = [[0]] * 4
inputs = [[',,,', '1,1,1,', ',2,2,2']]
self._test_dataset(
inputs, [[0, 0, 0, 0], [1, 1, 1, 0], [0, 2, 2, 2]],
record_defaults=record_defaults)
def testCsvDataset_errW... |
HAOYU-LI/UniDOE | Scraper/WD2.py | Python | apache-2.0 | 590 | 0.020339 | from scraper import *
WD2_url = "http://www.cms-ud.com/UD/table/WD2.htm"; crit_name_WD2 = "WD2/"
WD2_list = find_urls(url=WD2_url,crit_name=crit_name_WD2)
for url in WD2_list:
try:
| url = url.replace('^','%5E')
url = "http://www.cms-ud.com/UD/table/"+url
design = find_design(url)
#print(design)
run,factor,level = find_design_size(url,"WD2")
file_name = "WD2_"+str(run)+"_"+str(factor)+"_"+str(level)
save_design(desig | n,name=file_name,save_path='./design_data/WD2/')
except:
print("Some errors happen at url: %s",url) |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_v1_generated_metadata_service_create_context_sync.py | Python | apache-2.0 | 1,468 | 0.000681 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | parent="parent_value",
)
# Make the request
response = client.create_context(request=request)
# Handle the response
print(response)
# [END aiplat | form_v1_generated_MetadataService_CreateContext_sync]
|
tensorflow/similarity | tensorflow_similarity/stores/__init__.py | Python | apache-2.0 | 1,292 | 0.000774 | # Copyright 2021 The TensorFlow 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 or agreed to ... | d by a nearest neigboor search performed with the
[`Search()` module](../search/).
Additionally one might want to inspect the content of the index which is why
`Store()` class may implement an export to
a [Pandas Dataframe](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)
via the `to_p... |
"""
from .store import Store # noqa
from .memory_store import MemoryStore # noqa
|
telefonicaid/fiware-keystone-spassword | keystone_spassword/tests/unit/contrib/spassword/test_checker.py | Python | apache-2.0 | 1,246 | 0.002408 | #
# Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
#
# 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... |
# "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.
"""Unit tests for SPASSWORD checker."""
from keystone import tests
from keystone import exception
import keystone_spasswo... | :
new_password = "stronger"
self.assertRaises(exception.ValidationError,
checker.strong_check_password(new_password))
|
cwdtom/qqbot | tom/findbilibili.py | Python | gpl-3.0 | 4,769 | 0.009097 | # -*- coding: utf-8 -*-
__author__ = 'Tom Chen'
import urllib2,sys,re,time
from sgmllib import SGMLParser
from datetime import datetime,date
from urllib import unquote,quote
default_encoding = 'utf-8' #设置文件使用UTF-8编码
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setde... | son_id' and attrs[1][0] == 'id':
if re.match(r's_\ | d+',attrs[1][1]):
self.is_li = 'season'
self.seasonnum.append(attrs[0][1])
except IndexError:
pass
def end_li(self):
self.is_li = ''
def start_a(self,attrs):
try:
if attrs[0][0] == 'class' and attrs[0][1] == 't':
... |
Jozhogg/iris | tools/generate_std_names.py | Python | lgpl-3.0 | 4,434 | 0.001579 | # (C) British Crown Copyright 2010 - 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | help='Path to CF standard name XML')
parser.add_argument('output', type=argparse.FileType('w'),
metavar='OUTPUT',
help='Path to resulting Python code')
args = parser.parse_args( | )
to_dict(args.input, args.output)
|
rh-s/heat | heat_integrationtests/scenario/test_ceilometer_alarm.py | Python | apache-2.0 | 2,412 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | if actual != expected:
LOG.warn('check_instance_count exp:%d, act:%s' % (expected,
actual))
return actual == expected
def test_alarm(self):
"""Confirm we can create an alarm and trigger it."""
# 1. create the sta... | = {}
sample['counter_type'] = 'gauge'
sample['counter_name'] = 'test_meter'
sample['counter_volume'] = 1
sample['counter_unit'] = 'count'
sample['resource_metadata'] = {'metering.stack_id':
stack_identifier.split('/')[-1]}
sample['r... |
pinax/pinax_theme_tester | pinax_theme_tester/configs/stripe.py | Python | mit | 3,913 | 0.0046 | import decimal
from datetime import datetime
from django.conf import settings
from django.conf.urls import url, include
from pinax.stripe.forms import PlanForm
from .base import ViewConfig
invoices = [
dict(date=datetime(2017, 10, 1), subscription=dict(plan=dict(name="Pro")), period_start=datetime(2017, 10, 1),... | 31), total=decimal.Decimal("9.99"), paid=False),
dict(date=datetime(2017, 9, 1), subscription=dict(plan=dict(name="Pro")), period_start=datetime(2017, 9, 1), period_end=datetime(2017, 9, 30), total=decimal.Decimal("9.99"), paid=True),
dict(d | ate=datetime(2017, 8, 1), subscription=dict(plan=dict(name="Beginner")), period_start=datetime(2017, 8, 1), period_end=datetime(2017, 8, 31), total=decimal.Decimal("5.99"), paid=True),
dict(date=datetime(2017, 7, 1), subscription=dict(plan=dict(name="Beginner")), period_start=datetime(2017, 7, 1), period_end=dateti... |
fsalmoir/PyGeM | pygem/stlhandler.py | Python | mit | 3,986 | 0.032614 | """
Derived module from filehandler.py to handle STereoLithography files.
"""
import numpy as np
from mpl_toolkits import mplot3d
from matplotlib import pyplot
from stl import mesh, Mode
import pygem.filehandler as fh
class StlHandler(fh.FileHandler):
"""
STereoLithography file handler class
:cvar string infile: ... | shown.
:return: figure: matlplotlib structure for the figure of the chosen geometry
:rtype: matplotlib.pyplot.figure
"""
if plot_file is None:
plot_file = self.infile
else:
self._check_filename_type(plot_file)
# Create a new plot
| figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
stl_mesh = mesh.Mesh.from_file(plot_file)
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(stl_mesh.vectors))
## Get the limits of the axis and center the geometry
max_dim = np.array([np.max(s... |
nagyistoce/devide | module_kits/vtk_kit/__init__.py | Python | bsd-3-clause | 3,965 | 0.003279 | # $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK clas... | newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlag | s(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(module_manager, pre_import=True):
# first do the VTK pre-imports: this is here ONLY to keep the user happy
# it's not necessary f... |
ivyl/patchwork | patchwork/models.py | Python | gpl-2.0 | 33,987 | 0.000382 | # Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
# Copyright (C) 2015 Intel Corporation
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | on_delete=models.CASCADE)
priority = models.IntegerField(default=0)
|
def __str__(self):
return self.path
class Meta:
ordering = ['-priority', 'path']
unique_together = (('path', 'project'))
@python_2_unicode_compatible
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, related_name='profile',
... |
GordonWang/JM-VIP | JMVIPCrawler/items.py | Python | apache-2.0 | 7,573 | 0.015325 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
import scrapy.log
import datetime
def now():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class JmProductItem(scrapy.Item):
# d... | scrapy.Field()
stored_date = scrapy.Field()
is_hot_sale = scrapy.Field()
def is_crawled(self, db_connection):
cur = db_connection.cursor()
| count = cur.execute("SELECT id FROM promotion WHERE name=%s AND stored_date=%s AND sku_count IS NOT NULL", (self['name'], self['stored_date']))
cur.close()
return count > 0
def record_exist(self, db_connection):
cur = db_connection.cursor()
count = cur.execute("SELECT id FROM pro... |
cheesyc/basicpython | mmm.py | Python | mit | 628 | 0.017516 | howmany = input("How many numbers are you using?: ")
count = howmany
num = []
while count > 0:
for i in howmany:
x = input("Insert number ",i,": ")
num.appe | nd(x)
count -= 1
def sort(num):
size = len(num)
for i in range(size):
for j in range(size-i-1):
if(num[j] > num[j+1]):
tmp = num[j]
num[j] = num[j+1]
num[j+1] = tmp
return num
srted = sort(num)
def mean (num):
mean = sum(num)... | if
|
iesugrace/log-with-git | xmlstorage.py | Python | gpl-2.0 | 13,529 | 0.001626 | import os
from record import Record
from timeutils import isodate
from git import Git
import applib
import re
class XmlStorage:
""" XML storage engine for the record
"""
@staticmethod
def setup(dataDir):
engineDir = os.path.join(dataDir, 'xml')
os.makedirs(engineDir, exist_ok=True)
... | it shall be ignored.
When a single record was collected multiple times,
the redundant shall be removed. It can happen
when the record was changed multiple times (maybe
plus added action) within the range.
"" | "
vCount = count
while True:
ps = XmlStorage.git.last(vCount)
if len(set(ps)) == count:
break
else:
vCount += 1
paths = []
for p in ps:
if p not in paths:
paths.append(p)
records = []
... |
OrkoHunter/nxcpy | setup.py | Python | bsd-3-clause | 1,193 | 0.020117 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from glob import glob
import os
import sys
from setuptools import setup, Extension
from Cython.Build import cythonize
if sys.version_info[:2] < (2, 7):
print(
'nxcpy requires Python version 2.7 or later' +
' ({}.{... | ', ['*/*.pyx'],
include_dirs=['src'],
libraries=['nxcpy']),
Extension('*.* | .*', ['*/*/*.pyx'],
include_dirs=['src'],
libraries=['nxcpy'])]
)
install_requires = ['networkx', 'decorator']
if __name__ == "__main__":
setup(
name = 'nxcpy',
packages = ['nxcpy'],
libraries = libraries,
ext_modules = ext_modules,... |
anyweez/regis | face/management/commands/personalize.py | Python | gpl-2.0 | 8,409 | 0.006541 | from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from operator import itemgetter
import face.models.models as regis
import random, math
class Command(BaseCommand):
args = 'none'
help = 'Analyze user performance and modify individual question orderings.'
... | question.save()
# Commit the new ordering to the database as a single transaction.
| transaction.commit()
print 'Complete!'
# For each user, compute their personal question score. This score
# represents the ratio of questions that they get correct vs. those that they
# have unlocked. Higher scores indicate a higher level of completion.
#
# Note that this sco... |
Quantipy/quantipy | tests/test_rules.py | Python | mit | 81,385 | 0.003883 | import unittest
import os.path
import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
import test_helper
import copy
from operator import lt, le, eq, ne, ge, gt
from pandas.core.index import Index
__index_symbol__ = {
Index.union: ',',
Index.intersection: '&',
Index.diff... | _get_dataset()
x = 'q5'
y = '@'
dataset.sorting(x, on='mean')
stack = self._get_stack_with_links(dataset, x)
stack.add_link(x=x, y=y, views=[' | cbase', 'counts', 'c%', 'mean'])
vks = ['x|f|x:|||cbase', 'x|f|:|||counts', 'x|f|:|y||c%',
'x|d.mean|x:|||mean']
chains = stack.get_chain(data_keys=dataset.name,
filters='no_filter',
x=[x], y=[y], rules=True,
... |
d-qoi/TelegramBots | RoseAssassins/cust_handlers/conversationhandler.py | Python | lgpl-3.0 | 15,351 | 0.004755 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | list of handlers that might be used if
the user is in a conversation, but every handler for their current state returned
``False`` on :attr:`check_update`.
allow_reentry (:obj:`bool`): Optional. Determines if a user can restart a conversation with
an entry point.
run_... | ional. The time-out for ``run_async`` decorated
Handlers.
timed_out_behavior (List[:class:`telegram.ext.Handler`]): Optional. A list of handlers that
might be used if the wait for ``run_async`` timed out.
per_chat (:obj:`bool`): Optional. If the conversationkey should contain the... |
supriti/DeepSea | srv/modules/runners/ui_rgw.py | Python | gpl-3.0 | 5,055 | 0.001583 | # -*- coding: utf-8 -*-
"""
Consolidate any user interface rgw calls for Wolffish and openATTIC.
All operations will happen using the rest-api of RadosGW. The one execption
is getting the credentials for an administrative user which is implemented
here.
"""
import logging
import os
import json
import re
import glob... | if not user:
# No system user
log.error("No system user for radosgw found")
return
self.credentials['access_key'] = user['keys'][0]['access_key']
self.credentials['secret_key'] = user['keys'][0]['secret_key']
self.credentials['success']... | search = "I@cluster:{}".format(self.cluster)
__opts__ = salt.config.client_config('/etc/salt/master')
pillar_util = salt.utils.master.MasterPillarUtil(search, "compound",
use_cached_grains=True,
... |
SBT-community/Starbound_RU | tools/special_cases.py | Python | apache-2.0 | 2,754 | 0.017234 |
from re import compile as regex
def matches(patts, filename):
for p in patts:
if not p.match(filename) is None:
return True
return False
class SpecialSection():
def __init__(self, name, pathPatterns, filePatterns, all_conditions = False):
self.name = name
self.allcond = all_conditions
se... | edText/fluff/2/.*$"],
["^.*quests/generated/templates/spread_rumors.questtemplate$"], True),
SpecialSection("Предложный падеж", ["^.*generatedText/fluff/3/.*$"],
["^.*quests/generated/templates/escort\.questtemplate$"], True),
SpecialSection("Предложный падеж", [".*generatedText/fluff/5/.*$"],
["^.*ques... | сло", ["^.*generatedText/fluff/3/.*$"],
["^.*kill_monster_group\.questtemplate$"], True),
SpecialSection("Родительный падеж", ["^.+/name$"],
["^.*pools/monsterthreats\.config$"], True),
SpecialSection("Префикс названия банды", ["^.*Prefix/.*"], ["^.*quests/bounty/gang\.config"], True),
SpecialSection("Осн... |
cinp/python | cinp/common_test.py | Python | apache-2.0 | 7,291 | 0.055411 | import pytest
from cinp.common import URI
# TODO: test mutli-object setting
def test_splituri_builduri(): # TODO: test invlid URIs, mabey remove some tests from client_test that are just checking the URI
uri = URI( '/api/v1/' )
( ns, model, action, id_list, multi ) = uri.split( '/api/v1/' )
assert ns == []
... | ( '/ns/', root_optional=False )
( ns, model, action, id_list, multi ) = uri.split( '/ns/', root_optional=True )
assert ns == [ 'ns' ]
assert model is None
assert id_list is None
assert action is None
assert multi is False
assert uri.build( ns, model, action, id | _list ) == '/api/v1/ns/'
assert uri.build( ns, model, action, id_list, in_root=False ) == '/ns/'
def test_extract_ids():
uri = URI( '/api/v1/' )
id_list = [ '/api/v1/ns/model:sdf:', '/api/v1/ns/model:234:', '/api/v1/ns/model:rfv:' ]
assert uri.extractIds( id_list ) == [ 'sdf', '234', 'rfv' ]
id_list = [ '... |
wubr2000/googleads-python-lib | examples/dfp/v201411/team_service/create_teams.py | Python | apache-2.0 | 1,762 | 0.007946 | #!/usr/bin/python
#
# Copyright 2014 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 b... | results.
for team in teams:
print ('Team with ID \'%s\' and name \'%s\' was created.'
% (team['id'], team['name']))
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient. | LoadFromStorage()
main(dfp_client)
|
adamwwt/chvac | venv/lib/python2.7/site-packages/sqlalchemy/events.py | Python | mit | 40,130 | 0.0001 | # sqlalchemy/events.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Core event interfaces."""
from . import event, exc
from .pool import Pool
f... | arget: the target object |
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are ge... |
jameskane05/final_helpstl | submit/urls.py | Python | gpl-2.0 | 177 | 0.00565 | from django.conf.urls import include, url
from . import | views
urlpatterns = [
url(r'^$', views.subform, name='subform'), |
url(r'^submit', views.submit, name='submit'),
] |
rogerscristo/BotFWD | env/lib/python3.6/site-packages/pytests/test_inlinequeryresultlocation.py | Python | mit | 5,366 | 0.002795 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens | e 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 usefu | l,
# 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 should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licen... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/ithorian/shared_ith_backpack_s01.py | Python | mit | 470 | 0.046809 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE D | OCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/ithorian/shared_ith_backpack_s01.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","ith_backpack_s01")
#### BEGIN MODIFIC | ATIONS ####
#### END MODIFICATIONS ####
return result |
lucascudo/pytherisk | pytherisk.py | Python | gpl-3.0 | 4,654 | 0.010314 | #!/usr/bin/python
# coding=utf-8
import hashlib
import os
import re
import subprocess
import sys
import tempfile
from datetime import datetime
from gtts import gTTS
while 1:
line = sys.stdin.readline().strip()
if line == '':
break
key, data = line.split(':')
if key[:4] != 'agi_':
#skip input... | derr.write("FAIL (unexpected result '%s')\n" % params)
sys.stderr.flush()
return -2
def hangup():
sys.stdout.write("EXEC Hangup")
sys.stdout.flush()
sys.stderr.writ | e("EXEC Hangup")
sys.stderr.flush()
line = sys.stdin.readline()
result = line.strip()
return int(checkresult(result)) - 48
def read_digit(timeout):
sys.stdout.write("WAIT FOR DIGIT %s\n" %timeout )
sys.stdout.flush()
sys.stderr.write("WAIT FOR DIGIT %s\n" %timeout )
sys.stderr.flush()
... |
praekelt/vumi-go | go/apps/http_api/tests/test_vumi_app.py | Python | bsd-3-clause | 31,622 | 0 | import base64
import json
from twisted.internet.defer import inlineCallbacks, DeferredQueue, returnValue
from twisted.web.http_headers import Headers
from twisted.web import http
from twisted.web.server import NOT_DONE_YET
from vumi.config import ConfigContext
from vumi.message import TransportUserMessage, TransportE... | e, messages.put, errors.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
msg2 = yield self.app_helper.make_dispatch_inbound(
'in 2', message_id='2', conv=self.conversation)
... | ct()
# Sometimes messages arrive out of order if we're hitting real redis.
rm1, rm2 = sorted([rm1, rm2], key=lambda m: m['message_id'])
self.assertEqual(msg1['message_id'], rm1['message_id'])
self.assertEqual(msg2['message_id'], rm2['message_id'])
self.assertEqual(errors.size, ... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_generated_aiplatform_v1_model_service_get_model_async.py | Python | apache-2.0 | 1,466 | 0.000682 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | _v1_ModelService_GetModel_async]
from google.cloud import aiplatform_v1
async def sample_get_model():
# Create a client
client = aiplatform_v1.ModelServiceAsyncClient()
# Initialize request argum | ent(s)
request = aiplatform_v1.GetModelRequest(
name="name_value",
)
# Make the request
response = await client.get_model(request=request)
# Handle the response
print(response)
# [END aiplatform_generated_aiplatform_v1_ModelService_GetModel_async]
|
hachreak/invenio-oaiharvester | invenio_oaiharvester/upgrades/oaiharvester_2015_07_14_innodb.py | Python | gpl-2.0 | 1,535 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 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 later... | o_upgrader.api import op
depends_on = ['invenio_2015_03_03_tag_value']
def info():
"""Return upgrade recipe information."""
return "Fixes foreign key relationship."
def do_upgrade():
"""Carry out the upgrade."""
op.alter_column(
table_name='oaiHARVESTLOG',
| column_name='bibupload_task_id',
type_=db.MediumInteger(15, unsigned=True),
existing_nullable=False,
existing_server_default='0'
)
def estimate():
"""Estimate running time of upgrade in seconds (optional)."""
return 1
def pre_upgrade():
"""Pre-upgrade checks."""
p... |
miguelgrinberg/heat | heat/tests/keystone/test_role_assignments.py | Python | apache-2.0 | 12,401 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | S(%s) title modified.' %
actual_title)
def test_property_roles_validate_schema(self):
schema = (role_assignments.KeystoneRoleAssignment.
properties_schema[
role_assignments.KeystoneRoleAssignment.ROLES])
self.assertEqual(
True,
... | nt.ROLES)
self.assertEqual(properties.Schema.LIST,
schema.type,
'type for property %s is modified' %
role_assignments.KeystoneRoleAssignment.ROLES)
self.assertEqual('List of role assignments.',
schema.d... |
tiffanyjaya/kai | vendors/pdfminer.six/pdfminer/settings.py | Python | mit | 187 | 0 | STRI | CT = False
try:
from django.conf import settings
STRICT = getattr(settings, 'PDF_MINER_IS_STRICT', STRICT)
except Exception:
# in case it's not a django project
pass | |
gencer/sentry | src/sentry/web/api.py | Python | bsd-3-clause | 26,313 | 0.001254 | from __future__ import absolute_import, print_function
import base64
import logging
import six
import traceback
from time import time
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.http... |
# See http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever
PIXEL = base64.b64decode('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=')
PROTOCOL_VERSIONS = frozenset(('2.0', '3', '4', '5', '6', '7'))
pubsub = QueuedPublisher(
RedisPublisher(getattr(settings, 'REQUESTS_PUBSUB_CONNECTION', None))
) if getattr(settin | gs, 'REQUESTS_PUBSUB_ENABLED', False) else None
def api(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
data = func(request, *args, **kwargs)
if request.is_ajax():
response = HttpResponse(data)
response['Content-Type'] = 'application/json'
else:
... |
krischer/wfdiff | src/wfdiff/tests/test_wfdiff.py | Python | gpl-3.0 | 452 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
wfdiff test suite.
Run with pytest.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014-2015
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
import inspect
import os
# Most | generic way to get the data folder path.
DATA | _DIR = os.path.join(os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()))), "data")
|
tachylyte/HydroGeoPy | one_d_numerical.py | Python | bsd-2-clause | 3,784 | 0.013214 | ### Implementation of the numerical Stehfest inversion inspired by J Barker https://www.uni-leipzig.de/diffusion/presentations_DFII/pdf/DFII_Barker_Reduced.pdf
import inversion
import math
def finiteConc(t, v, De, R, deg, x, c0, L, N):
''' t is time (T), v is velocity (L/T), De is effective hydrodynamic dis... | a2 * L)))) / (math.exp(a1 * L) - math.exp(a2 * L))))
return rt * Sum
def infiniteConc(t, v, De, R, deg, x, c0, N):
''' t is time (T), v is velocity (L/T), De is effective hydrodynamic dispersion (including diffusion) (L^2/T), |
R is retardation (-), deg is first order decay constant (1/T), x is position along path (L),
c0 is source concentration (M/L^3), n is effective porosity (-), N is input variable stehfestCoeff().
Return concentration (M/L^3) at position x'''
Vs = inversion.stehfestCoeff(N)
rt = math.log(2.0)... |
ikedumancas/ikequizgen | quizzes/migrations/0005_auto_20150813_0645.py | Python | mit | 1,156 | 0.000865 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('quizzes', '0004_auto_20150811_1354'),
]
operations = [
migrations.AlterModelOptions(
name='choice',
... | eld=models.IntegerField(default=0),
),
migrations.AddField(
model_name='question',
name='order',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='quiz',
name='is_active',
| field=models.BooleanField(default=False, verbose_name=b'active'),
),
]
|
elsigh/browserscope | third_party/appengine_tools/devappserver2/endpoints/discovery_api_proxy.py | Python | apache-2.0 | 3,882 | 0.005667 | #!/usr/bin/env python
#
# Copyright 2007 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 writing, software
# distributed under the License i | s 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.
#
"""Proxy that dispatches Discovery requests to the prod Discovery service."""
import httplib
import js... |
wxgeo/geophar | wxgeometrie/modules/cryptographie/__init__.py | Python | gpl-2.0 | 12,975 | 0.006816 | # -*- coding: utf-8 -*-
##--------------------------------------#######
# Cryptographie #
##--------------------------------------#######
# WxGeometrie
# Dynamic geometry, graph plotter, and more for french mathematic teachers.
# Copyright (C) 2005-2013 Nicolas Pourcelot
#
# ... | timer.timeout.connect(self.OnIdle)
timer.start(100)
# DEBUG:
##self.code.setPlainText('WR IRAMXPZRHRDZ IK HRYYOVR AL IRYYBKY RYZ NOALWLZR POM WR NOLZ FKR W BD O VOMIR WRY YLVDRY IR PBDAZKOZLBD RZ WRY RYPOARY RDZMR WRY HBZY OWBMY FKR I QOELZKIR BD VMBKPR WRY WRZZMRY ALDF POM | ALDF')
def copier(self, evt=None, widget=None):
self.vers_presse_papier(widget.toPlainText())
def DlgModifierCle(self, evt=None):
while True:
text, ok = QInputDialog.getText(self, "Modifier la clé",
"La clé doit être une permutation de l'alphabet,\n"
... |
denz/swarm-crawler | swarm_crawler/dataset/datasource.py | Python | bsd-3-clause | 7,406 | 0.009317 | from string import printable
import re
from urlparse import urlunparse
from itertools import chain, ifilter
from fnmatch import fnmatch
from werkzeug import cached_property
from swarm import transport, swarm
from swarm.ext.http.helpers import parser, URL
from ..text import PageText
from .tree import TrieTree as Tree
... | c,
'cmdopts',
{}).items() | for c in containers))))
@classmethod
def populate_parser(cls, parser):
for optname, kwargs in cls.get_opts().items():
parser.add_argument('--%s'%optname.replace('_', '-'), **kwargs)
def __unicode__(self):
descr = 'Extract ' + ' and '.join(self.info())
opts = []
... |
openlabs/pyes | pyes/rivers.py | Python | bsd-3-clause | 4,849 | 0.000619 | class River(object):
def __init__(self, index_name=None, index_type=None, bulk_size=100, bulk_timeout=None):
self.name = index_name
self.index_name = index_name
self.index_type = index_type
self.bulk_size = bulk_size
self.bulk_timeout = bulk_t | imeout
def serialize(self):
res = self._serialize()
index = {}
if self.name:
index['name'] = self.name
if self.i | ndex_name:
index['index'] = self.index_name
if self.index_type:
index['type'] = self.index_type
if self.bulk_size:
index['bulk_size'] = self.bulk_size
if self.bulk_timeout:
index['bulk_timeout'] = self.bulk_timeout
if index:
res... |
toastedcornflakes/scikit-learn | sklearn/feature_extraction/tests/test_image.py | Python | bsd-3-clause | 11,187 | 0.000089 | # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# License: BSD 3 clause
import numpy as np
import scipy as sp
from scipy import ndimage
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_raises
from sklearn... |
def test_grid_to_graph():
# Checking that the function works with graphs containing no edges
size = 2
roi_size = 1
# Generating two convex parts with one vertex
# Thus, edges will be empty in _to_graph
mask = np.zeros((size, size), dtype=np.bool)
mask[0:roi_size, 0:roi_size] = True
ma... | size:, -roi_size:] = True
mask = mask.reshape(size ** 2)
A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray)
assert_true(connected_components(A)[0] == 2)
# Checking that the function works whatever the type of mask is
mask = np.ones((size, size), dtype=np.int16)
A = grid_to_g... |
userzimmermann/robotframework-python3 | src/robot/output/listeners.py | Python | apache-2.0 | 10,498 | 0.001048 | # Copyright 2008-2014 Nokia Solutions and 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 l... | listener.call_method(listener.log_message, self._create_msg_dict(msg))
def message(self, msg):
for listener in self._listeners:
if listener.version == 2:
listener.call_method(listener.message, self._create_msg_dict(msg))
def _create_msg_dict(self, msg):
return... | ile(self, name, path):
for listener in self._listeners:
listener.call_method(getattr(listener, '%s_file' % name.lower()), path)
def close(self):
for listener in self._listeners:
listener.call_method(listener.close)
def _get_start_attrs(self, item, *extra):
retur... |
rvanharen/SitC | knmi_getdata.py | Python | apache-2.0 | 5,962 | 0.003187 | #!/usr/bin/env python2
'''
Description:
Author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)
Created: -
Last Modified: -
License: Apache 2.0
Notes: -
'''
from lxml.html import parse
import csv
import urllib2
from lxml import html
import numbers
import json
import os
import ut... | ectory',
default=os.path.join(os.getcwd(),'KNMI'),
required=False)
parser.add_argument('-s', '--stationid', help='Station id',
default='', required=False, action='store')
parser.add_argument('-c', '--csvfile', help='CSV data file',
... | n='store_true')
parser.add_argument('-l', '--log', help='Log level',
choices=utils.LOG_LEVELS_LIST,
default=utils.DEFAULT_LOG_LEVEL)
# extract user entered arguments
opts = parser.parse_args()
# define logger
logname = os.path.basename(__file__) + '.lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.