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 |
|---|---|---|---|---|---|---|---|---|
williamjmorenor/mkdocs | mkdocs/utils/__init__.py | Python | bsd-2-clause | 13,602 | 0.000588 | # coding: utf-8
"""
Standalone file utils.
Nothing in this module should have an knowledge of config or the layout
and structure of the site and pages in the site.
"""
from __future__ import unicode_literals
import logging
import markdown
import os
import pkg_resources
import shutil
import sys
import yaml
import fn... | tput_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
open(output_path, 'wb').write(content)
def clean_directory(directory):
"""
Rem | ove the content of a directory recursively but not the directory itself.
"""
if not os.path.exists(directory):
return
for entry in os.listdir(directory):
# Don't remove hidden files from the directory. We never copy files
# that are hidden, so we shouldn't delete them either.
... |
physicalattraction/kerstpuzzel | src/Conundrum/repeated_letters.py | Python | mit | 853 | 0.001172 | from pprint import pprint
from Conundrum.utils import sanitize
def decrypt(msg: str, repeated_letter: str) -> str:
"""
Extract every letter after an occurrence of the repeated letter
"""
msg = sanitize(msg)
result = []
remove_next = False
for letter in msg:
take_this = remove_nex... | eated_letter
if take_this:
result += letter
return ''.join(result)
def decrypt_try_all(msg: str) -> [str]:
msg = sanitize(msg)
letters_to_try = sorted({letter for letter in msg})
return {letter: decrypt(msg, letter) for letter in letters_to_try}
if __name__ == '__main__':
# U... | et pews or leisure chains can seem to stink of effort, george, under no illusions of vanity'
pprint(decrypt_try_all(encrypted_msg))
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/spyderlib/widgets/externalshell/pythonshell.py | Python | gpl-3.0 | 27,927 | 0.003688 | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""External Python Shell widget: execute Python script in a separate process"""
import sys
import os
import os.path as osp
import socket
from spyderlib.qt.QtGui imp... | def get_arglist(self, objtxt):
"""Get func/method argument list"""
return self.ask_monitor("__get_arglist__('%s')" % objtxt)
def get__doc__(self, objtxt):
"""Get object __doc__"""
return self.ask_monitor("__get | __doc____('%s')" % objtxt)
def get_doc(self, objtxt):
"""Get object documentation dictionary"""
return self.ask_monitor("__get_doc__('%s')" % objtxt)
def get_source(self, objtxt):
"""Get object source"""
return self.ask_monitor("__get_source__('%s')" % objtxt)
... |
JudoWill/ResearchNotebooks | Woundy.py | Python | mit | 2,781 | 0.023013 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os, os.path
from matplotlib import pyplot as plt
from pylab import get_cmap
import SimpleCV as cv
from glob import glob
# <codecell>
def show_img(img, ax = None):
if ax is not None:
plt.sca(ax)
nimg = img | .getNumpy()
return plt.imshow(nimg, aspect='equal')
# <codecell>
path = '/home/will/Dropbox/burnimages/*.jpg'
norm_files = sorted(f for f in glo | b(path) if '-e' not in f)
masked_files = sorted(f for f in glob(path) if '-e' in f)
fig, axs = plt.subplots(6,6, figsize = (10,10))
for f, ax in zip(norm_files, axs.flatten()):
img = cv.Image(f)
show_img(img, ax = ax)
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
# <codecell>
from itertools ... |
sonofeft/ODPSlides | odpslides/zip_file.py | Python | lgpl-3.0 | 882 | 0.006803 | # Support Python 2 and 3
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import zipfile
import time
from odpslides.template_xml_file import TemplateXML_File
here = os.path.abspath(os.path.dirname(__file__))
def zipfile_insert... | with non-ascii characters
#data = | data.encode('utf-8')
now = time.localtime(time.time())[:6]
info = zipfile.ZipInfo(filename)
info.date_time = now
info.compress_type = zipfile.ZIP_DEFLATED
zipfileobj.writestr(info, data)
|
Ziemin/telepathy-gabble | tests/twisted/olpc/olpc-muc-prop-change.py | Python | lgpl-2.1 | 14,987 | 0.001802 | """
Test OLPC MUC properties.
"""
import dbus
from twisted.words.xish import domish, xpath
from gabbletest import exec_test, acknowledge_iq, make_muc_presence
from servicetest import call_async, EventPattern, wrap_channel
import constants as cs
import ns
from mucutil import echo_muc_presence
def test(q, bus, conn,... | ost', 'test'))
event = q.expect('dbus-signal', signal='MembersChanged')
assert event.args == ['', [room_self_handle], [], [], [], 0, 0]
call_async(q, buddy_iface, 'SetActivities', [('foo_id', room_handle)])
event = q.expect('stream-iq', iq_type='set')
# Now that it's not private, it'll go in my P... | a['type'] = 'result'
event.stanza['to'] = 'test@localhost'
event.stanza['from'] = 'test@localhost'
stream.send(event.stanza)
q.expect('dbus-return', method='SetActivities')
# Bob changes the properties and tells the room he's done so
message = domish.Element(('jabber:client', 'message'))
m... |
AdrianGaudebert/configman | configman/tests/test_option.py | Python | bsd-3-clause | 12,635 | 0.000237 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | ertEqual(o.doc, "lucy's integer")
self.assertEqual(o.from_string_converter, int)
| self.assertEqual(o.value, 1)
data = {
'name': 'lucy',
'default': 1,
'doc': "lucy's integer",
'value': '1'
}
o = Option(**data)
self.assertEqual(o.name, 'lucy')
self.assertEqual(o.default, 1)
self.assertEqual(o.doc, "lucy's i... |
CSC-IT-Center-for-Science/pouta-blueprints | pebbles/services/openstack_service.py | Python | mit | 23,846 | 0.001048 | import novaclient
from novaclient.exceptions import NotFound
import novaclient.client
from keystoneauth1 import loading
from keystoneauth1 import session
import neutronclient.v2_0.client
import cinderclient.v2.client
from osc_lib.utils import wait_for_delete
import taskflow.engines
from taskflow.patterns import line... | .debug("no root volume defined")
return ""
def revert(self, config, **kwargs):
logging.debug("revert: delete root volume")
try:
if getattr(self, 'volume_id', None):
nc = get_openstack_cinder_client(config)
nc. | volumes.delete(
nc.volumes.get(self.volume_id))
else:
logging.debug("revert: no volume_id stored, unable to revert")
except Exception as e:
logging.error('revert: deleting volume failed: %s' % e)
class CreateDataVolume(task.Task):
def execute(sel... |
qilicun/python | python3/tutorials/fibonacci.py | Python | gpl-3.0 | 355 | 0.011268 | # - | *- coding: utf-8 -*-
#!/usr/bin/env python3
def fib(n):
"""This a simple fibonacci function"""
result = []
a, b = 0, 1
while a < n:
result.append(a)
# prin | t(a, end=' ')
a, b = b, a+b
return result
if __name__ == "__main__":
import sys
print(fib(int(sys.argv[1])))
#print(fib.__doc__)
#fib = fib(100)
|
mozaik-association/mozaik | mozaik_event_question_thesaurus/models/event_question.py | Python | agpl-3.0 | 573 | 0 | # Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models |
class EventQuestion(models.Model):
_inherit = "event.question"
# invisible for simple_choice and text_input questions, intended to
# be used for other types of questions when inheriting this module
interest_ids = fields.Many2many("thesaurus.term", string="Interests")
class EventQuestionAnswer(mod... | hesaurus.term", string="Interests")
|
Eficent/odoo-operating-unit | account_operating_unit/wizard/account_report_account_balance.py | Python | agpl-3.0 | 1,755 | 0 | # -*- coding: utf-8 -*-
# © 2016 Eficent Business and IT Consulting Services S.L. -
# Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from openerp.osv import fields, orm
from openerp.addons.account.report.account_balance import account_balance
from openerp.report import repo... | uid, ids, data, context=context)
data['form'] = self.read(cr, uid, ids, ['operating_unit_ids'],
context=context)[0]
result['operating_unit_ids'] = 'operating_unit_ids' in data['form'] \
| and data['form']['operating_unit_ids'] \
or False
return result
|
xyficu/rts2 | python/testalchemy.py | Python | gpl-2.0 | 575 | 0.006957 | #!/usr/bin/env python
from sqlalchemy import create_engine, and_, or_
from sqlalchemy.orm.session import sessionmaker
from rts2.db import Targets,Grb
Session = sessionmaker()
en | gine = create_engine('postgresql://petr:petr@localhost/stars',echo='debug')
Session.configure(bind=engine)
sess = Session()
targ = sess.query(Targets)
#q = sess.query(ApacheCatalog)
print targ.filter(Targets.tar_id == 1000).all()
print targ.filter(and_ | (Targets.tar_ra < 20, Targets.tar_dec < 0, Targets.tar_dec > -20)).all()
grb = sess.query(Grb)
print grb.filter(Grb.tar_id == 50001).all()
|
kunaltyagi/nsiqcppstyle | rules/RULE_9_2_D_use_reentrant_function.py | Python | gpl-2.0 | 3,067 | 0.00163 | """
Use reentrant functions. | Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {
k = t.ctime(); <== Cor... | n.
}
"""
from nsiqunittest.nsiqcppstyle_unittestbase import *
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import *
no_reenterant_functions = (
'ctime',
'strtok',
'toupper',
)
def RunRule(lexer, contextStack):
"""
Use r... |
ecerulm/python-heatclient | heatclient/tests/functional/base.py | Python | apache-2.0 | 1,527 | 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
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under ... | t pass at a simple read only python-heatclient test.
This only exercises client commands that are read only.
This should test commands:
* as a regular user
* as a admin user
* with and without optional parameters
* initially just check return codes, and later test command outputs
"""
d... |
AnishShah/tensorflow | tensorflow/contrib/data/python/ops/sliding.py | Python | apache-2.0 | 5,041 | 0.004364 | # 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... | bsolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.pyt | hon.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import gen_dataset_ops
from tensorflow.python.util import deprecation
class _SlideDataset(dataset_ops.Dataset):
"""A `Dataset` that passes a sliding window over its... |
bonniejools/cabot | cabot/cabotapp/calendar.py | Python | mit | 638 | 0 | import requests
from django.conf import s | ettings
from icalendar import Calendar
def get_calendar_data():
feed_url = settings.CALENDAR_ICAL_URL
resp = requests.get(feed_url)
cal = Calendar.from_ical(resp.content)
return cal
def get_events():
events = []
for component in get_calendar_data().walk():
if component.name == 'VEVEN... | 'dtstart'),
'end': component.decoded('dtend'),
'summary': component.decoded('summary'),
'uid': component.decoded('uid'),
})
return events
|
helixyte/TheLMA | thelma/tests/entity/test_experiment.py | Python | mit | 3,511 | 0 | import pytest
from everest.repositories.rdb.testing import check_attributes
from everest.repositories.rdb.testing import persist
from thelma.tests.entity.conftest import TestEntityBase
class TestExperimentEntity(TestEntityBase):
def test_init(self, experiment_fac):
exp = experiment_fac()
check_a... | , experiment_design_fac.init_kw)
def test_persist(self, nested_session, experiment_design_fac):
exp_design = experiment_design_fac()
persist(nested_session, exp_design, experiment_design_fac.init_kw,
True)
class TestExperim | entDesignRackEntity(TestEntityBase):
def test_init(self, experiment_design_rack_fac):
exp_dr = experiment_design_rack_fac()
check_attributes(exp_dr, experiment_design_rack_fac.init_kw)
class TestExperimentMetadataEntity(TestEntityBase):
def test_init(self, experiment_metadata_fac):
e... |
wallarelvo/keeper | keeper/point.py | Python | apache-2.0 | 1,627 | 0.000615 |
import math
import random
class Point(object):
def __init__(self, x, y, z=0):
self.x = x
self.y = y |
self.z = z
def get_x(self):
return self.x
def get_y(self):
return self.y
def get_z(self):
return self.z
def set_x(self, x):
self.x = x
return self
def set_y(self, y):
self.y = y
return self
def set_z(self, z):
self.z ... | pow(self.y - other_point.y, 2) +
pow(self.z - other_point.z, 2)
)
def to_unit_vector(self):
mag = self.dist_to(Point(0, 0, 0))
if mag == 0:
return Point(0, 0, 0)
else:
return Point(self.x / mag, self.y / mag, self.z / mag)
def to_list(se... |
saullocastro/pyNastran | pyNastran/f06/dev/f06_classes.py | Python | lgpl-3.0 | 904 | 0.002212 | from six import iteritems
class MaxDis | placement(object):
def __init__(self, data):
self.translations = {}
self.rotations = {}
for line in data:
sid = line[0]
self.translations[sid] = line[1:4]
| self.rotations[sid] = line[4:]
def write_f06(self, page_stamp='%i', pageNum=1):
msg = ['0 MAXIMUM DISPLACEMENTS',
' SUBCASE/',
' DAREA ID T1 T2 T3 R1 R2 ... |
etkirsch/legends-of-erukar | erukar/content/conditions/magical/__init__.py | Python | agpl-3.0 | 394 | 0 | from .AugmentedWeapon import AugmentedWeapon
from .Cloaked import Cloaked
fr | om .Ethereal import Ethereal
from .Muted import Muted
from .TemporaryIllumination import TemporaryIllumination
from .Undead import Undead
from .HealthDrain import HealthDrain
__all__ = [
"AugmentedWeapon",
"Cloa | ked",
"Ethereal",
"Muted",
"TemporaryIllumination",
"Undead",
"HealthDrain"
]
|
MaralAfris/wasp-challenge-lth-team2 | planning/src/world.py | Python | gpl-3.0 | 12,092 | 0.003225 | import sys
from settings import *
from map import *
from copy import deepcopy
import numpy as np
class World(object):
def __init__(self, agents, waypoints, boxes, persons):
self.agents = agents
self.waypoints = waypoints
self.boxes = boxes
self.persons = persons
def add_ma... | with open(json_file) as data_file:
data = json.load(data_file)
agents = []
waypoints = []
boxes = []
persons = []
way | point_dict = {}
names = set()
def check_name(name):
if name in names:
raise Exception("names must be unique among all objects (yahsp3 limitation)" \
+ ", offender: " + name)
names.add(name)
def get_location(data, source):
... |
pabigot/pyxb | tests/drivers/test-mg-sequence.py | Python | apache-2.0 | 8,660 | 0.008199 | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from pyxb.utils import six
from xml.dom import Node
import os.path
schema_path = os.path.abspath(os.path.join(os.path.dirname(__file__),... | nce).toxml("utf-8"), xmld)
def testMissingAtStart (self):
xmlt = six.u('<ns1:altwrapper xmlns:ns1="URN:test-mg-sequence"><third/></ns1:altwrapper>')
dom = pyxb.utils.domutils.StringToDOM(xmlt)
self.assertRaises(UnrecognizedContentError, altwrapper.createFromDOM, dom.documentElement)
... | entContentError, ToDOM, instance)
def testMissingAtEndLeadingContent (self):
xmlt = six.u('<ns1:altwrapper xmlns:ns1="URN:test-mg-sequence"><first/></ns1:altwrapper>')
dom = pyxb.utils.domutils.StringToDOM(xmlt)
self.assertRaises(IncompleteElementContentError, altwrapper.createFromDOM, dom.... |
KennyLv/learnPython | src/24.modules.multiprocessing_Pipe.py | Python | gpl-2.0 | 1,154 | 0.020833 | # Multiprocessing with Pipe
# Written by Vamei
import multiprocessing as mul
def proc1(pipe):
pipe.send('hello')
print('proc1 rec:',pipe.recv())
def proc2(pipe):
print('proc2 rec:',pipe.recv())
pipe.send('hello, too')
if __name__ == '__ | main__':
#1) Pipe可 | 以是单向(half-duplex),也可以是双向(duplex)。
#我们通过mutiprocessing.Pipe(duplex=False)创建单向管道 (默认为双向)。
#一个进程从PIPE一端输入对象,然后被PIPE另一端的进程接收,单向管道只允许管道一端的进程输入,而双向管道则允许从两端输入。
# Build a pipe
#Pipe对象建立的时候,返回一个含有两个元素的表,每个元素代表Pipe的一端(Connection对象)。
pipe = mul.Pipe()
#我们对Pipe的某一端调用send()方法来传送对象,在另一端使用recv()来接收。
... |
apple/swift-clang | utils/check_cfc/check_cfc.py | Python | apache-2.0 | 14,638 | 0.002664 | #!/usr/bin/env python
"""Check CFC - Check Compile Flow Consistency
This is a compiler wrapper for testing that code generation is consistent with
different compilation processes. It checks that code is not unduly affected by
compiler options or other changes which should not have side effects.
To use:
-Ensure that ... | the abso | lute path to the wrapper to the --cc
and --cxx options
e.g.
lnt runtest nt --cc <path to check_cfc>/clang \\
--cxx <path to check_cfc>/clang++ ...
To add a new check:
-Create a new subclass of WrapperCheck
-Implement the perform_check() method. This should perform the alternate compile
and do the co... |
fkolacek/FIT-VUT | bp-revok/python/lib/python2.7/site-packages/cryptography-0.5.2-py2.7-linux-x86_64.egg/cryptography/hazmat/backends/openssl/dsa.py | Python | apache-2.0 | 7,193 | 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
# distributed under the... | f._backend._ffi.gc(self._public_key._dsa_cdata,
self._backend._lib.DSA_free)
data_to_verify = self._hash_ctx.finalize()
# The first parameter passed to DSA_verify is unused by OpenSSL but
# must be an integer.
res = self._backend._l | ib.DSA_verify(
0, data_to_verify, len(data_to_verify), self._signature,
len(self._signature), self._public_key._dsa_cdata)
if res != 1:
errors = self._backend._consume_errors()
assert errors
if res == -1:
assert errors[0].lib == self._... |
andrewebdev/django-ostinato | ostinato/statemachine/forms.py | Python | mit | 2,636 | 0.000379 | import new
from django import forms
from ostinato.statemachine import InvalidTransition
def sm_form_factory(sm_class, state_field='state'):
"""
A factory to create a custom StateMachineModelForm class
"""
class StateMachineModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... | ly generate it here
def clean_action(self):
"""
make sure that the selected action does not pass through to
the actual form cleaned_data, since it can | cause validation
issues on the field.
"""
self._sm_action = self.cleaned_data[state_field]
try:
return sm.action_result(self._sm_action)
except InvalidTransition:
return self.old_state
se... |
EzyInsights/log4mongo-python | log4mongo/test/test_handlers.py | Python | bsd-3-clause | 6,198 | 0.003872 | from log4mongo.handlers import MongoHandler
from pymongo.errors import PyMongoError
from StringIO import StringIO
import unittest
import logging
import sys
class TestMongoHandler(unittest.TestCase):
host_name = 'localhost'
database_name = 'log4mongo_test'
collection_name = 'logs_test'
def setUp(self):... | ptions['max'], 10)
self.assertEqual(options['capped'], 1)
def test_capped_max(self):
for i in range(self.capped_max * 2):
self.log.info('test capped info')
documents = self.handler.collection.find()
self.assertEqual(documents.count(), 10)
def test_override_no_capped... | n=self.collection_name)
self.log.removeHandler(self.handler)
self.log.addHandler(self.handler_no_capped)
self.log.info('test info')
# Creating capped handler
self.handler_capped = MongoHandler(host=self.host_name, database_name=self.database_name,
... |
ROB-Seismology/oq-hazardlib | openquake/hazardlib/gsim/atkinson_wald_2007.py | Python | agpl-3.0 | 2,419 | 0.000827 | # coding: utf-8
# The Hazard Library
# Copyright (C) 2012 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later... | OUT ANY WARRA | NTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module ... |
apexkid/Wikiapiary | apiary/tasks/bot/deletewebsitelogs.py | Python | gpl-2.0 | 837 | 0.003584 | """
Clean up the website log table.
"""
# pylint: disable=C0301,C0103,W1201
from apiary.tasks import BaseApiaryTask
import logging
import datetime
LOGGER = logging.getLogger()
class DeleteWebsiteLogsTask(BaseApiaryTask):
"""Delete old entries from the bot_log."""
def run(self):
"""Execute the task.... | bsite_logs before %s." % delete_before_str)
my_sql = sql_query % (delete_before_str)
(success, rows_deleted) = self.runSql(my_sql)
| LOGGER.info("Deleted %d rows." % rows_deleted)
return rows_deleted
|
manojklm/pywinauto-x64 | pywinauto/controls/__init__.py | Python | lgpl-2.1 | 2,175 | 0.001839 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library 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 2.1
# of the License, or (at you... | (props)
# #pprint(GetDialogPropsFromHandle(handle))
#
#if __name__ == "__main__": |
# _unittests()
|
edx/edx-platform | openedx/core/djangoapps/bookmarks/__init__.py | Python | agpl-3.0 | 390 | 0 | """
# lint-amnesty, pylint: disable=dj | ango-not-configured
# lint-amnesty, pylint: disable=django-not-configured
Bookmarks module.
"""
from collections import namedtuple
DEFAULT_FIELDS = [
'id',
'course_id',
'usage_id',
'block_type',
'created',
]
OPTIONAL_FIELDS = [
'display_name',
'path',
]
PathItem = namedtuple('PathItem',... | '])
|
diagramsoftware/l10n-spain | l10n_es_aeat_mod347/models/mod347.py | Python | agpl-3.0 | 38,108 | 0 | # -*- coding: utf-8 -*-
# © 2004-2011 Pexego Sistemas Informáticos. (http://pexego.es)
# © 2012 NaN·Tic (http://www.nan-tic.com)
# © 2013 Acysos (http://www.acysos.com)
# © 2013 Joaquín Pedrosa Gutierrez (http://gutierrezweb.es)
# © 2014-2015 Serv. Tecnol. Avanzados - Pedro M. Baeza
# (http://www.servicios... | elf._invoice_amount_get(invoices, refunds)
| if amount:
vals['amount'] = amount
vals['invoice_record_ids'] = [
(0, 0, {'invoice_id': x})
for x in (invoices.ids + refunds.ids)]
invoice_record = partner_record_obj.create(vals)
if invoice_record:
records.append(invoic... |
Afnarel/django-forms-builder | forms_builder/forms/south_migrations/0014_auto__chg_field_field_choices.py | Python | bsd-2-clause | 8,984 | 0.008014 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def fo | rwards(self, orm):
# Changing field 'Field.choices'
db.alter_column(u'forms_field', 'choices', self.gf('django.db.models.fields.CharField')(max_length=5000))
def backwards(self, orm):
# Changing field | 'Field.choices'
db.alter_column(u'forms_field', 'choices', self.gf('django.db.models.fields.CharField')(max_length=1000))
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'na... |
HyperloopTeam/FullOpenMDAO | lib/python2.7/site-packages/openmdao.main-0.13.0-py2.7.egg/openmdao/main/factory.py | Python | gpl-2.0 | 2,382 | 0.001259 | import inspect
#public symbols
__all__ = ["Factory"]
class Factory(object):
"""Base class for objects that know how to create other objects
based on a type argument and several optional arguments (version,
server id, and resource description).
"""
def __init__(self):
pass
def create(... | dao entry point groups.
"""
raise NotImplementedError('get_available_types')
de | f get_signature(self, typname, version=None):
"""Return constructor argument signature for *typname,* using the
specified package version. The return value is a dictionary:
args: list
List of 1 or 2-element lists. The first element is the argument
name; the second elemen... |
bwohlberg/sporco | sporco/array.py | Python | bsd-3-clause | 14,977 | 0.000935 | # -*- coding: utf-8 -*-
# Copyright (C) 2015-2020 by Brendt Wohlberg <brendt@ieee.org>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""Functions operating on num... | m future.moves.itertools import zip_longest
import numpy as np
from sporco._util import renamed_function
__author__ = """Brendt Wohlberg <brendt@ieee.org>"""
def ntpl2array(ntpl):
"""Convert a namedtuple to an array.
Convert a :func:`collections.namedtuple` object to a
:class:`numpy.ndarray` object t... | ntpl : collections.namedtuple object
Named tuple object to be converted to ndarray
Returns
-------
arr : ndarray
Array representation of input named tuple
"""
return np.asarray((np.hstack([col for col in ntpl]), ntpl._fields,
ntpl.__class__.__name__), dtype=objec... |
djangogirlstaipei/eshop | bookshop/books/migrations/0006_auto_20161129_0636.py | Python | mit | 747 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-29 06:36
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('books', | '0005_book_tags'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'verbose_name': '書籍', 'verbose_name_plural': '書籍'},
),
migrations.AlterModelOptions(
name='category',
options={'verbose_name': '分類', 'verbose_name_plu... | '分類'},
),
migrations.AlterModelOptions(
name='tag',
options={'verbose_name': '標籤', 'verbose_name_plural': '標籤'},
),
]
|
cryptapus/electrum | electrum/tests/__init__.py | Python | mit | 902 | 0.001109 | import unittest
import threading
from electrum import constants
# Set this locally to make the test suite run faster.
# If set | , unit tests that would normally test functions with multiple implementations,
# will only be run once, using the fastest implementation.
# e.g. libsecp256k1 vs python-ecdsa. pycryptodomex vs pyaes.
FAST_TESTS = False
# some unit tests are modifying globals; sorry.
class SequentialTestCase(unittest.TestCase):
te... | t_lock.release()
class TestCaseForTestnet(SequentialTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
constants.set_testnet()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
constants.set_mainnet()
|
ankur22/Butler | topia/termextract/interfaces.py | Python | mit | 1,701 | 0.000588 | ##############################################################################
| #
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE D... | # FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interfaces
$Id: interfaces.py 100556 2009-05-30 15:42:14Z srichter $
"""
__docformat__ = "reStructuredText"
import zope.interface
class ITagger(zope.interface.Interface):
"""A utility to provide POS tag... |
lixiangning888/whole_project | modules/signatures_orginal_20151110/browser_scanbox.py | Python | lgpl-3.0 | 1,730 | 0.002894 | # Copyright (C) 2015 Will Metcalf william.metcalf@ | gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be... | 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/licenses/>.
from lib.cuckoo.common.abstracts import Signature
class BrowserScanbox(Signature):
... |
nnmware/nnmware | apps/booking/__init__.py | Python | gpl-3.0 | 66 | 0 | default_app_config = "nnm | ware.apps.booking.apps.BookingAppConfi | g"
|
ingenioustechie/zamboni | mkt/api/base.py | Python | bsd-3-clause | 8,836 | 0 | import functools
from django.db.models.sql import EmptyResultSet
import commonware.log
from rest_framework.decorators import api_view
from rest_framework.exceptions import ParseError
from rest_framework.mixins import ListModelMixin
from rest_framework.routers import Route, SimpleRouter
from rest_framework.response im... | ping={
'get': 'list',
'post': 'create'
},
name='{basename}-list',
initkwargs={'suffix': 'List'}
),
# Detail route.
Route(
url=r'^{lookup}/{prefix}{trailing_slash}$',
mapping={
'get': 'retr... | 'post': 'detail_post',
'patch': 'partial_update',
'delete': 'destroy'
},
name='{basename}-detail',
initkwargs={'suffix': 'Instance'}
)
]
class SubRouterWithFormat(SubRouter):
"""
SubRouter that also adds the optional format to ge... |
studybuffalo/rdrhc_calendar | modules/retrieve.py | Python | gpl-3.0 | 1,263 | 0.001584 | """Retrieves the paths to the required schedule files."""
from datet | ime import datetime
import logging
import pytz
from unipath import Path
# Setup Logging
LOG = logging.getLogger(__name__)
def get_date(tz_string):
"""Generates todays date as string (in format yyyy-m | m-dd)"""
schedule_tz = pytz.timezone(tz_string)
today = datetime.now(schedule_tz)
return today.strftime('%Y-%m-%d')
def retrieve_schedule_file_paths(config):
"""Creates the path to the schedules from supplied config file."""
schedule_loc = config['excel']['schedule_loc']
date = get_date(confi... |
phillipgreenii/loan_payoff_tools | loan_payoff_tools/money.py | Python | mit | 4,298 | 0.001396 | from decimal import Decimal
import decimal
from functools import total_ordering
@total_ordering
class Money(object):
_round_amount = Decimal('1.00')
def __init__(self, dollars=None, cents=None):
if isinstance(dollars, Money):
if cents:
raise ValueError("if dollars is Money... | isinstance(other, self.__class__):
return self._cents == other._cents
return NotImplemented
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
return NotImplemented
def __lt__(self, other):
if isinstance(other, s... | if isinstance(other, self.__class__):
return Money(cents=(self._cents + other._cents))
return NotImplemented
def __sub__(self, other):
if isinstance(other, self.__class__):
return Money(cents=(self._cents - other._cents))
return NotImplemented
def __mul__(self, ... |
RomainBrault/operalib | operalib/tests/test_QuantileRegression.py | Python | bsd-3-clause | 1,549 | 0 | """OVK learning, unit tests.
The :mod:`sklearn.tests.test_QuantileRegression` tests OVK quantile regression
estimator.
"""
import operalib as ovk
from sklearn.utils.estimator_checks import check_estimator
import numpy as np
def test_valid_estimator():
"""Test whether ovk.Quantile is a valid sklearn estimator."... | antile():
"""Test OVK quantile estimator fit, predict."""
probs = np.linspace(0.1, 0.9, 5) # Quantile levels of interest
x_train, y_train, _ = ovk.toy_data_quantile(50)
x_test, y_test, _ = ovk.toy_data_quantile(1000, probs=probs)
# | Joint quantile regression
lbda = 1e-2
gamma = 1e1
joint = ovk.Quantile(probs=probs, kernel='DGauss', lbda=lbda,
gamma=gamma, gamma_quantile=1e-2)
# Independent quantile regression
ind = ovk.Quantile(probs=probs, kernel='DGauss', lbda=lbda,
gamma=gamma,... |
jkeifer/pyHytemporal | old_TO_MIGRATE/test5.py | Python | mit | 787 | 0.007624 | __author__ = 'phoetrymaster'
import subprocess
nodatain = -3000
nodataout = -3000
inputshape = "'/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/DepartmentSelection/ARG_adm/pellegrini.shp'"
inputimg = "'/Users/phoetrymaster/Documents/School/Geography/Thesis | /Data/MODIS 7_2012-2013/argentina_1/test.tif'"
outputimg = "'/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS 7_2012-2013/argentina_1/MODIS_pellegrini_clip.tif'"
outprj = "'+proj=utm +zone=20 +datum=WGS84'"
outformat = "ENVI"
#Need to reproject | input shapefile to outprj before warping...
subprocess.call("gdalwarp -t_srs {0} -srcnodata {1} -dstnodata {2} -crop_to_cutline -cutline {3} {4} {5} -of {6}".format(outprj, nodatain, nodataout, inputshape, inputimg, outputimg, outformat), shell=True) |
WesleyHsieh/policy_gradient | policy_gradient/policy_gradient.py | Python | mit | 10,569 | 0.028101 | import numpy as np
import numpy.linalg as la
import collections
import IPython
import tensorflow as tf
from utils import *
import time
from collections import defaultdict
class PolicyGradient(Utils):
"""
Calculates policy gradient
for given input state/actions.
Users should primarily be calling main
PolicyGrad... | vals = self.prev_weight_inverse_hess = self.prev_bias_inverse_hess = \
self.total_weight_grad = self.total_bias_grad = None
self.init_action_neural_net(net_dims, output_function, filepath)
if seed_state is not None:
np.random.set_state(seed_state)
tf.set_random_seed(seed)
def train_agent(self, dynamics_f... | ntum=0.5, normalize=True):
"""
Trains agent using input dynamics and rewards functions.
Parameters:
dynamics_func: function
User-provided function that takes in
a state and action, and returns the next state.
reward_func: function
User-provided function that takes in
a state and action, and ret... |
DMPwerkzeug/DMPwerkzeug | rdmo/questions/models.py | Python | apache-2.0 | 27,506 | 0.001927 | from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.core.cache import caches
from django.db import models
from django.utils.translation import ugettext_lazy as _
from rdmo.conditions.models import Condition
from rdmo.core.constants impo... | _name=_('Label'),
help_text=_('The path part of the URI of this section (auto-generated).')
)
comment = models.TextField(
blank=True,
verbose_name=_('Comment'),
help_text=_('Additional internal information about this section.')
)
locked = models.BooleanField(
defa... | ether this section (and it\'s question sets and questions) can be changed.')
)
catalog = models.ForeignKey(
Catalog, on_delete=models.CASCADE, related_name='sections',
verbose_name=_('Catalog'),
help_text=_('The catalog this section belongs to.')
)
order = models.IntegerField(
... |
nikesh-mahalka/nova | nova/tests/functional/test_legacy_v2_compatible_wrapper.py | Python | apache-2.0 | 3,299 | 0.000606 | # Copyright 2015 Intel Corporation.
# 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 requir... | created_server = self.api.post_server(post)
| self._wait_for_state_change(created_server, 'BUILD')
response = self.api.post_server_metadata(created_server['id'],
{'a': 'b'})
self.assertEqual(response, {'a': 'b'})
def test_request_with_pattern_properties_with_avoid_metadata(self):
fake_n... |
Akrog/cinder | cinder/zonemanager/drivers/brocade/brcd_fc_san_lookup_service.py | Python | apache-2.0 | 10,817 | 0 | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack 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
#
# ... | .append(self.get_formatted_wwn(t))
for i in initiator_wwn_list:
formatted_initiator_list.append(self.
get_formatted_wwn(i))
for fabric_name in fabrics:
fabric_ip = self.fabric_configs[fabric_name].safe_get(
... | ic_user')
fabric_pwd = self.fabric_configs[fabric_name].safe_get(
'fc_fabric_password')
fabric_port = self.fabric_configs[fabric_name].safe_get(
'fc_fabric_port')
# Get name server data from fabric and find the targets
... |
maxalbert/sumatra | sumatra/datastore/davfs.py | Python | bsd-2-clause | 3,618 | 0.00387 | '''
Datastore via remote webdav connection
'''
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
import os
import tarfile
import logging
from fs.contrib.davfs import DAVFS
from urllib.parse import urlparse
from contextlib import closing # needed for Python ... | chive_paths.append(archive_path)
tf.close()
tf_obj.close()
# Delete original files.
if delete_originals:
for file_path in files:
os.remove(os.path.join(self.root, file | _path))
self._last_label = label # useful for testing
return archive_paths
|
Kuwagata/md5crack | LocallyThreaded/client_mod.py | Python | mit | 1,033 | 0.03001 | import os, sys, socket, hashlib, pickle
hashedword = "4f9c4e19748be021372db6d5e10cfd02"
def main():
target = '127.0.0.1'
port = 5555
chars = "abcdefghijklmnopqrstuvwxyz"
charl = len(chars)
while True:
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.conn... | sock.send(word)
sock.close()
s.close()
if __name__ == '__main__':
main()
| |
Naeka/vosae-app | www/contacts/models/entity.py | Python | agpl-3.0 | 3,242 | 0.002159 | # -*- coding:Utf-8 -*-
from mongoengine import Document, fields
from django_gravatar.helpers import get_gravatar_url
from core.mixins import ZombieMixin, AsyncTTLUploadsMixin
from notification.mixins import NotificationAwareDocumentMixin
from core.tasks import es_document_index, es_document_deindex
__all__ = (
... | status = fields.StringField(choices=STATUSES, required=True, default=ZombieMixin.DEFAULT_STATUS)
private = fields.BooleanField(required=True, default=False)
photo_source = fields.StringField(choices=["LOCAL", "GRAVATAR"])
photo = fields.ReferenceField("VosaeFile")
gravatar_mail = fields.EmailField(max_l... | ds.ListField(fields.EmbeddedDocumentField("Address"))
emails = fields.ListField(fields.EmbeddedDocumentField("Email"))
phones = fields.ListField(fields.EmbeddedDocumentField("Phone"))
invoicing_settings = {} # fields.ReferenceField("InvoicingSettings")
meta = {
"indexes": ["tenant"],
"... |
aio-libs/aiohttp_session | demo/memcached_storage.py | Python | apache-2.0 | 788 | 0 | import time
from aiohttp import web
import asyncio
import aiomcache
from aiohttp_session import setup, get_session
from aioht | tp_session.memcached_storage import MemcachedStorage
async def handler(request: web.Request) -> web.Response:
session = await get_session(request)
last_visit = session['last_visit'] if 'last_visit' in se | ssion else None
session['last_visit'] = time.time()
text = 'Last visited: {}'.format(last_visit)
return web.Response(text=text)
async def make_app() -> web.Application:
app = web.Application()
mc = aiomcache.Client("127.0.0.1", 11211, loop=loop)
setup(app, MemcachedStorage(mc))
app.router.... |
jeffbaumes/jeffbaumes-vtk | Utilities/vtkTclTest2Py/vtkTclToPyConvertor.py | Python | bsd-3-clause | 18,843 | 0.005148 | # This is the translator that converts Tcl test to python.
# Not all Tcl test are translatable.
# To ensure that a test can be translated :
# 1) do not use Tcl arrays
# 2) do not use string substitution except in variable names
# eg. obj${i} GetOutput is okay
# obj12 GetOutputAs${i} is not okay.
# 3) do not ... | d_cmd = self.translate_command(arguments[0], arguments[1:])
pass
elif command == "catch" and len(arguments) == 1:
translated_cmd = "catch.catch(globals(),\"\"\"%s\"\"\")" % \
| self.translate_block(arguments[0]).strip()
elif command == "expr":
translated_cmd = "expr.expr(globals(), locals(),["
i = False
for arg in arguments:
if i:
translated_cmd += ","
translated_cmd += "\"%s\"" % arg
... |
slivingston/flymovieformat | motmot/FlyMovieFormat/ffmpeg2fmf.py | Python | bsd-3-clause | 1,625 | 0.008615 | import pyglet
import pyglet.media as media
import numpy as np
import sys, os
import motmot.FlyMovieFormat.FlyMovieFormat as fmf_mod
from optparse import OptionParser
def get_frame(source):
ts = source.get_next_video_timestamp()
im = source.get_next_video_frame()
if im is None:
return None, None
... | n.resize((im.height,im.width,n_8bit_chans))
imn = np.mean(imn,axis=2) # collapse last dim, convert to | float64
imn = imn.astype(np.uint8) # convert back to uint8
imn2 = np.array(imn,copy=True)
return imn2, ts
def main():
usage = '%prog [options] FILE'
parser = OptionParser(usage)
parser.add_option("--format", type='string', default=None)
(options, args) = parser.parse_args()
in_f... |
yunlongliukm/chm1_scripts | ClassifyRepeats.py | Python | mit | 1,195 | 0.005021 | #!/usr/bin/env python |
import argparse
ap = argparse.ArgumentParser(description="count masked repeats.")
ap.add_argument("table", help="Repeat table.")
ap.add_argument("--fraction", help="Calls | must be at least this fraction to be made.", type=float, default=0.51)
args = ap.parse_args()
table = open(args.table, 'r')
table.readline()
table.readline()
table.readline()
indels = dict([("insertion", {}), ("deletion", {})])
for line in table:
vals = line.split()
title = vals[4]
titleVals = title.sp... |
coUrbanize/django-rest-framework-jwt | tests/test_authentication.py | Python | mit | 9,810 | 0.000102 | from django.http import HttpResponse
from django.test import TestCase
from django.utils import unittest
from django.conf.urls import patterns
from rest_framework import permissions, status
try:
from rest_framework_oauth.authentication import OAuth2Authentication
except ImportError:
try:
from rest_frame... | ""
response = self.csrf_client.post('/jwt/', {'example': 'example'},
format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate' | ], 'JWT realm="api"')
def test_post_no_jwt_header_failing_jwt_auth(self):
"""
Ensure POSTing over JWT auth without credentials fails
"""
auth = 'JWT'
response = self.csrf_client.post(
'/jwt/', {'example': 'example'},
HTTP_AUTHORIZATION=auth, format='j... |
opalmer/aws | awsutil/__init__.py | Python | mit | 75 | 0.013333 | """ |
The modules and packages responsible for wrapping boto |
functions.
"""
|
bdestombe/flopy-1 | flopy/pakbase.py | Python | bsd-3-clause | 35,922 | 0.001392 | """
pakbase module
This module contains the base package class from which
all of the other packages inherit from.
"""
from __future__ import print_function
import os
import webbrowser as wb
import numpy as np
from numpy.lib.recfunctions import stack_arrays
from .modflow.mfparbc import ModflowParBc as mfparbc
f... | fmtin=old_value.format.fortran,
locat=old_value.locat,
array_free_format=old_value.format.array_free_format)
elif isinstance(old_value, Util3d):
value = Util3d(self.parent, old_value.shape,
... | |
aronsky/home-assistant | homeassistant/components/counter/__init__.py | Python | apache-2.0 | 9,477 | 0.000633 | """Component to count within automations."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.const import (
ATTR_EDITABLE,
CONF_ICON,
CONF_ID,
CONF_MAXIMUM,
CONF_MINIMUM,
CONF_NAME,
)
from homeassistant.core import HomeAssistant, callback
from hom... | "
CONF_RESTORE = "restore"
CONF_STEP = "step"
DEFAULT_INITIAL = 0
DEFAULT_STEP = 1
DOMAIN = "counter"
ENTITY_ID_FORMAT = DOMAIN + ".{}"
SERVICE_DECREMENT = "decrement"
SERVICE_INCREMENT = "increment"
SERVICE_RESET = "reset"
SERVICE_CONFIGURE = "configure"
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
CREATE_FIELDS = {
... | ): vol.All(cv.string, vol.Length(min=1)),
vol.Optional(CONF_MAXIMUM, default=None): vol.Any(None, vol.Coerce(int)),
vol.Optional(CONF_MINIMUM, default=None): vol.Any(None, vol.Coerce(int)),
vol.Optional(CONF_RESTORE, default=True): cv.boolean,
vol.Optional(CONF_STEP, default=DEFAULT_STEP): cv.positive_i... |
Aluriak/24hducode2016 | pocs/test_doc_turinsoft.py | Python | unlicense | 529 | 0.005671 | """
Test de la doc turinsoft:
http://api-doc.tourinsoft.com/#/questionnaire-web
prospose quelques fonctions de wrapping
""" |
import requests
URL = 'http://wcf.tourinsoft.com/QuestionnaireWeb/QuestionnaireWebService.svc/{}/{}/{}'
AUTH = ('cdt72', '969e24f9-75a2-4cc6-a46c-db1f6ebbfe97')
def access(service, client, questionnaire, auth=AUTH):
"""Return json object on given data"""
return requests.get(
URL.format(service, cl... | th
).json()
print(access()) # TODO
|
plotly/plotly.py | packages/python/plotly/plotly/validators/funnelarea/hoverlabel/font/_familysrc.py | Python | mit | 456 | 0 | import _plotly_utils.basevalidators
class FamilysrcValidator( | _plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="familysrc",
parent_name="funnela | rea.hoverlabel.font",
**kwargs
):
super(FamilysrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
rememberlenny/google-course-builder | tools/etl/etl.py | Python | apache-2.0 | 30,584 | 0.000458 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | land code and will cause conflicts.
_LOCAL_WHITELIST_EXCLUDES = frozenset(['assets/lib'])
# logging.Logger. Module logger.
_LOG = logging.getLogger('coursebuilder.tools.etl')
logging.basicConfig()
# List of string. Valid values for --log_level.
_LOG_LEVEL_CHOICES = ['DEBUG', 'ERROR', 'INFO', 'WARNING']
# String. Name o... | tring. Identifier for upload mode.
_MODE_UPLOAD = 'upload'
# List of all modes.
_MODES = [_MODE_DOWNLOAD, _MODE_RUN, _MODE_UPLOAD]
# Int. The number of times to retry remote_api calls.
_RETRIES = 3
# String. Identifier for type corresponding to course definition data.
_TYPE_COURSE = 'course'
# String. Identifier for ty... |
inspirehep/inspire-next | inspirehep/modules/authors/forms.py | Python | gpl-3.0 | 17,833 | 0.001123 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2018 CERN.
#
# INSPIRE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | field.data and "checked" or "",
field_id)]
return HTMLString(u''.join(html))
class WrappedSelect(Select):
"""Widget to wrap select input in further markup."""
wrapper = '<div>%(field)s</div>'
wrapped_widget = Select()
def __init__(self, widget=None, wrapper=None, *... | get = widget or self.wrapped_widget
self.wrapper_args = kwargs
if wrapper is not None:
self.wrapper = wrapper
def __call__(self, field, **kwargs):
"""Render wrapped input."""
return HTMLString(self.wrapper % dict(
field=self.wrapped_widget(field, **kwargs),
... |
ferustigris/battleship | simplelevel.py | Python | gpl-3.0 | 552 | 0.007246 | from levels import Abst | ractLevel, LevelsFactory, check
import bomblevel
def allBombed(self, player):
""" Check, is all players units are bombed """
return player.units.count('default_unit') == self.fieldSize()
class Level(AbstractLevel):
def fieldSize(self):
return 5
def units(self):
return ["default_unit" ... | "default"] = Level()
|
FedoraScientific/salome-paravis | test/VisuPrs/dump_study/A5.py | Python | lgpl-2.1 | 7,364 | 0.003802 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library 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 2.1 of the License, or (at your option) any later version.
#
# This library ... | 02111-1307 USA
#
# See http://www.salome-platform.org/ | or email : webmaster.salome@opencascade.com
#
# This case corresponds to: /visu/dump_study/A5 case
from paravistest import datadir, delete_with_inputs
from presentations import *
import pvserver as paravis
from pvsimple import *
my_paravis = paravis.myParavis
settings = {"Offset": [0.0001, 0.0002, 0], "ScalarMode"... |
johnrocamora/ImagePy | max_tiff.py | Python | mit | 1,346 | 0.005201 | from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1'... | mage.new(img1.mode, img1.size)
print(img1.mode)
print(img1.size)
fAvg = list()
pix = imgAvg.load()
for i in range(512):
for j in range(512):
pixVal = (f1[i*512+j] + f1[i*512+j]) / 2
# fAvg.append(pixVal)
fAvg.insert(i*512+j,pixVal)
imgAvg.putdata(fAvg)
imgAvg.save('avg.tiff')
plt.imshow(imgA... |
# The following is necessary to keep the above figures 'alive'
input()
# data = random.random((256, 256))
# img1 = Image.fromarray(data)
# img1.save('test.tiff')
|
AlexisTM/Indoor_Position_lasers | laserpack/bin/Scenari/scenario_circle.py | Python | mit | 1,452 | 0.013085 | #!/usr/bin/env python
from tasks import *
from math import cos, sin, pi
| import rospy
from signal import signal, SIGINT
from geometry_msgs.msg import Point
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C')
print('Leaving the Controller & closing the UAV')
Controller.__exit__()
sys.exit(0)
def PointsInCircum(r,z= | 3,n=8):
#return (x,y,z) points of a circle
#PointsInCircum(Rayon(m), Altitude{defaut:3}(m), NombreDePoints{defaut:8})
return [(round(cos(2*pi/n*x)*r,3),round(sin(2*pi/n*x)*r,3),z) for x in range(0,n+1)]
rospy.init_node('test_tasks')
Controller = taskController(rate=3, setpoint_rate=10)
rospy.loginfo("Contr... |
internap/fake-switches | tests/juniper/assertion_tools.py | Python | apache-2.0 | 679 | 0 | f | rom hamcrest import assert_that, not_, is_
from hamcrest import has_length
from hamcrest.core.base_matcher import BaseMatcher
def has_xpath(xpath, matcher):
return XPathMatcher(xpath, matcher)
class XPathMatcher(BaseMatcher):
def __init__(self, xpath, matcher):
self.xpath = xpath
self.matche... | r.xpath(self.xpath)
assert_that(nodes, has_length(1), "Nodes length should be 1 element")
assert_that(nodes[0].text, self.matcher)
return True
def describe_to(self, description):
pass
|
avedaee/DIRAC | RequestManagementSystem/test/RequestDBFileTests.py | Python | gpl-3.0 | 7,036 | 0.014639 | ########################################################################
# $HeadURL $
# File: RequestDBFileTests.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2012/06/13 07:51:20
########################################################################
""" :mod: RequestDBFileTests
=======================
... | 2012-06-01 04:57:02]]></SubmissionTime>
<Operation element_type="leaf"><![CDATA[replicateAndRegister]]></Operation>
</Attributes>
</TRANSFER_SUBREQUEST>
<REMOVAL_SUBREQ | UEST element_type="dictionary">
<Files element_type="list">
<EncodedString element_type="leaf"><![CDATA[lds6:Addlers8:cf4f13f9s7:Attempti1es6:FileIDi18es4:GUIDs36:5D5F45D5-9565-7AFB-3896-DB8695F2B35As3:LFNs33:/lhcb/user/c/cibak/cert-test1k-18s3:Md5ns3:PFNs75:srm://srm-lhcb.cern.ch/castor/cern.c... |
FePhyFoFum/quartetsampling | pysrc/quartet_sampling.py | Python | gpl-3.0 | 18,821 | 0.000053 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8 |
"""
quartet_samping.py: Quartet Sampling method for
phylogenetic branch support evaluation
<http://www.github.com/FePhyFoFum/quartetsampling>
"""
import argparse
import os
import sys
import time
from multiprocessing import Manager, Pool
from shutil import copyfile
from tree_data import TreeData, write_test_trees
fr... | om rep_data import process_replicate_raxmlng, process_replicate_raxmlng_lrt
from rep_data import process_replicate_iqtree, process_replicate_iqtree_lrt
from rep_data import process_replicate_paup
from rep_data import get_replicates_exhaustive, get_replicates_random
from rep_data import write_run_stats
from paramset imp... |
tomaash/gaeo | gaeo/controller/helper.py | Python | apache-2.0 | 792 | 0.002525 | # -*- coding: utf-8 -*-
#
# Copyright 2008 Lin-Chieh Shangkuan & Liang-Heng Chen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may o | btain a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing per... |
elbeardmorez/quodlibet | quodlibet/quodlibet/util/dbusutils.py | Python | gpl-2.0 | 11,310 | 0.000177 | # -*- coding: utf-8 -*-
# Copyright 2012, 2013 Christoph Reiter
#
# 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.
impor... | pect DBus method returning all combined.
All classes need to call set_introspection with their interface
and provided signals, properties, methods in the introspection
xml format.
The dbus bindings already provide a Introspect method, but it doesn't
understand properties, also having them in text ... | = "org.freedesktop.DBus.Introspectable"
ISPEC = """
<method name="Introspect">
<arg type="s" name="xml_data" direction="out"/>
</method>
"""
def __init__(self):
self.__ispec = {}
self.set_introspection(DBusIntrospectable.IFACE,
DBusIntrospectable.ISPEC)
... |
RoboCupULaval/StrategyIA | ai/STA/Action/GoBehind.py | Python | mit | 3,560 | 0.005073 | # Under MIT licence, see LICENCE.txt
from typing import Optional
from Util.ai_command import MoveTo
__author__ = "Maxime Gagnon-Legault"
import math
import numpy as np
from Util import Pose
from Util.position import Position
from Util.geometry import wrap_to_pi
from ai.GameDomainObjects import Player
RAYON_AVOID ... | errière un objet dont la position
est passée | en paramètre, de sorte que cet objet se retrouve entre le robot et la seconde position passée
en paramètre
Méthodes :
exec(self): Retourne la pose où se rendre
Attributs (en plus de ceux de Action):
player_id : L'identifiant du joueur
position1 : La position de l'objet derrière lequ... |
artisan-roaster-scope/artisan | src/artisanlib/qrcode.py | Python | gpl-3.0 | 1,715 | 0.009913 | # -*- coding: utf-8 -*-
#
import qrcode
try:
#pylint: disable = E, W, R, C
from PyQt6.QtGui import QImage, QPixmap,QPainter # @UnusedImport @Reimport @UnresolvedImport
from PyQt6.QtCore import Qt # @UnusedImport @Reimport @UnresolvedImport
except Exception:
#pylint: disable = E, W, R, C
from PyQ... | t @Reimport @UnresolvedImport
from PyQt5.QtCore import Qt # @UnusedImport @Rei | mport @UnresolvedImport
##########################################################################
##################### QR Image #####################################
##########################################################################
class QRImage(qrcode.image.base.BaseImage):
def new_image(self,... |
jolyonb/edx-platform | lms/djangoapps/lms_xblock/runtime.py | Python | agpl-3.0 | 8,551 | 0.001988 | """
Module implementing `xblock.runtime.Runtime` functionality for the LMS
"""
from completion.services import CompletionService
from django.conf import settings
from django.urls import reverse
from edx_django_utils.cache import DEFAULT_REQUEST_CACHE
import xblock.reference.plugins
from badges.service import BadgingSe... | def _get_current_user(self):
"""Returns the real, not anonymized, current user."""
real_user = self.runtime.get_real_user(self.runtime.anonymous_student_id)
return real_user
def get_tag(self, scope, key):
"""
Get a user tag for the current course and the current user for a | given key
scope: the current scope of the runtime
key: the key for the value we want
"""
if scope != user_course_tag_api.COURSE_SCOPE:
raise ValueError(u"unexpected scope {0}".format(scope))
return user_course_tag_api.get_course_tag(
self._get_cu... |
adrienbrunet/EulerProject | problem_030.py | Python | gpl-2.0 | 863 | 0.003476 | # coding: utf-8
'''
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1 ** 4 + 6 ** 4 + 3 ** 4 + 4 ** 4
8208 = 8 ** 4 + 2 ** 4 + 0 ** 4 + 8 ** 4
9474 = 9 ** 4 + 4 ** 4 + 7 ** 4 + 4 ** 4
As 1 = 1 ** 4 is not a sum it is not included.
The sum of these nu... | return result(5)
if __name__ == '__main__':
assert result(4) == 19316
print(main())
# 4438 | 39 in 967ms
|
magayorker/magatip | crypto.py | Python | mit | 10,464 | 0.002771 | import datetime
import getpass
import logging
import time
import traceback
from bitcoinrpc.authproxy import AuthServiceProxy
import bot_logger
import config
import models
import user_function
def get_rpc():
return AuthServiceProxy("http://%s:%s@%s:%s" % (
config.rpc_config['doge_rpc_username'], config.r... | , 9999999 | 9, [sender_address])
unspent_amounts = []
raw_inputs = []
fee = 1
for i in range(0, len(list_unspent), 1):
unspent_amounts.append(list_unspent[i]['amount'])
# check if we have enough |
altai/nova-billing | setup.py | Python | lgpl-2.1 | 1,852 | 0.00216 | #!/usr/bin/python2
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Nova Billing
# Copyright (C) 2010-2012 Grid Dynamics Consulting Services, Inc
# All Rights Reserved
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by t... | ftware Foundation; either
# version 2.1 of | the License, 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
# Lesser General Public License for more details.
#
# You should ha... |
rmvanhees/pys5p | src/pys5p/ckd_io.py | Python | bsd-3-clause | 23,526 | 0.000043 | """
This file is part of pyS5p
https://github.com/rmvanhees/pys5p.git
Provides access to the S5P Tropomi CKD (static and dynamic)
ToDo
----
- access to UVN CKD, still incomplete
- identify latest Static CKD product, e.g. using the validity period
Copyright (c) 2018-2021 SRON - Netherlands Institute for Space Rese... | ed. This product contained
the OCAL CKD and was not updated automatically. For version 2, all CKD are
stored in one product, where some CKD have a time-axis to correct any
in-flight degradation.
Therefore, the logic to find a CKD is implemented as follows:
1) ckd_dir, defines the base directory to ... | y
Version 1:
* Static CKD are stored in one file: glob('*_AUX_L1_CKD_*')
* Dynamic CKD are stored in two files:
- UVN, use glob('*_ICM_CKDUVN_*')
- SWIR, use glob('*_ICM_CKDSIR_*')
Version 2+:
* All CKD in one file: glob('*_AUX_L1_CKD_*')
* Dynamic CKD are empty
Examples
-... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/broker/v3_8_0/fail_over_configuration_broker.py | Python | apache-2.0 | 12,204 | 0.002704 | from ..broker import Broker
class FailOverConfigurationBroker(Broker):
controller = "fail_over_configurations"
def get_config(self, **kwargs):
"""Get the failover configuration for the specified unit.
**Inputs**
| ``api version min:`` None
| ``api version max:`... | uired:`` False
| ``default:`` None
:param | unit_id: Unit ID. Should be specified in OC/Collector environment. Default value is 0.
:type unit_id: Integer
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param name: Failover action na... |
lociii/jukebox_live_indexer | setup.py | Python | mit | 1,135 | 0 | # -*- coding: UTF-8 -*-
from setuptools import setup, find_packages
setup(
name="jukebox-live-indexer",
packages=find_packages(),
version="0.1.1",
description="Background library indexing service for jukebox",
author="Jens Nistler",
author_email="opensource@jensnistler.de",
url="http://jens... | xer"],
license="MIT",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: End Users/Desktop",
"Intended Audienc | e :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Multimedia :: Sound/Audio :: Players",
],
install_requires=[
"jukebox>=0.3.7",
"python-daemon==1.6",
"watchdog>=0.6.0",
],
include_package_data=True... |
discentes-imd/IntegraTI-API | app/mod_auth/ns_models.py | Python | gpl-3.0 | 75 | 0.013333 | from flask_restplus import fields
from app.mod | _auth.con | trollers import ns
|
AGHPythonCourse2017/zad3-chudy1997 | song_singer/ConnectionException.py | Python | gpl-3.0 | 152 | 0 | class Conn | ectionException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.va | lue)
|
malon/presupuesto | budget_app/models/budget_item.py | Python | gpl-2.0 | 5,467 | 0.004024 | from django.db import models
from django.conf import settings
class BudgetItemManager(models.Manager):
def each_denormalized(self, additional_constraints=None, additional_arguments=None):
sql = \
"select " \
| "fc.area, fc.poli | cy, fc.function, fc.programme, " \
"ec.chapter, ec.article, ec.heading, ec.subheading, " \
"ic.institution, ic.section, ic.department, " \
"fdc.source, fdc.fund, "\
"i.id, i.item_number, i.description, i.expense, i.actual, i.amount, " \
"b.... |
TheTimmy/spack | lib/spack/spack/cmd/cd.py | Python | lgpl-2.1 | 1,684 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ogram 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 PA | RTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA... |
lipis/guestbook | main/appengine_config.py | Python | mit | 408 | 0.017157 | # coding: utf-8
import os
import sys
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
sys.path.i | nsert(0, 'lib.zip')
else:
import re
from google.appengine.tools.devappserver2.python import stubs
re_ = stubs.FakeFile._skip_ | files.pattern.replace('|^lib/.*', '')
re_ = re.compile(re_)
stubs.FakeFile._skip_files = re_
sys.path.insert(0, 'lib')
sys.path.insert(0, 'libx')
|
kaichogami/sympy | sympy/physics/quantum/cg.py | Python | bsd-3-clause | 22,514 | 0.002132 | #TODO:
# -Implement Clebsch-Gordan symmetries
# -Improve simplification method
# -Implement new simpifications
"""Clebsch-Gordon Coefficients."""
from __future__ import print_function, division
from sympy import (Add, expand, Eq, Expr, Mul, Piecewise, Pow, sqrt, Sum,
symbols, sympify, Wild)
from sy... | mentum coupling between
two systems. The coefficients give the expansion of a cou | pled total angular
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
coefficients are defined as [1]_:
.. math ::
C^{j_1,m_1}_{j_2,m_2,j_3,m_3} = \langle j_1,m_1;j_2,m_2 | j_3,m_3\\rangle
Parameters
==========
j1, m1, j2, m2, j3, m3 : Number, Symbol
Term... |
edx/edx-e2e-tests | regression/tests/lms/test_instructor_dashboard.py | Python | agpl-3.0 | 1,326 | 0.001508 | """
End to end tests for Instructor Dashboard.
" | ""
from bok_choy.web_app_test import WebAppTest
from regression.pages.lms.course_page_lms import CourseHomePageExtended
from regression.pages.lms.dashboard_lms import DashboardPageExtended
from regression.pages.lms.instructor_dashboard import InstructorDashboardPageExtended
from regression.pages.lms.utils import get_... | ey
from regression.tests.helpers.api_clients import LmsLoginApi
from regression.tests.helpers.utils import get_course_display_name, get_course_info
class AnalyticsTest(WebAppTest):
"""
Regression tests on Analytics on Instructor Dashboard
"""
def setUp(self):
super().setUp()
login_ap... |
tiancj/emesene | emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0060/pubsub.py | Python | gpl-3.0 | 25,426 | 0.00059 | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import logging
from sleekxmpp.xmlstream import JID
from sleekxmpp.xmlstream.handler import Callback
from sleekxmpp.xmlstream.matcher import Sta... | e node than the one provided,
| so be sure to check the result stanza for a server assigned name.
If no configuration form is provided, the node will be created using
the server's default configuration. To get the default configuration
use get_node_config().
Arguments:
jid -- The JID of the pubsub ... |
13steinj/praw | praw/models/reddit/comment.py | Python | bsd-2-clause | 11,117 | 0 | """Provide the Comment class."""
from ...exceptions import ClientException
from ..comment_forest import CommentForest
from .base import RedditBase
from .mixins import InboxableMixin, ThingModerationMixin, UserContentMixin
from .redditor import Redditor
class Comment(RedditBase, InboxableMixin, UserContentMixin):
... | """Provide an instance of :class:`.CommentForest`.
This property may return an empty list if the comment
has not been refreshed with :meth:`.refresh()`
Sort order and reply limit can b | e set with the ``reply_sort`` and
``reply_limit`` attributes before replies are fetched, including
any call to :meth:`.refresh`:
.. code:: python
comment.reply_sort = 'new'
comment.refresh()
replies = comment.replies
"""
if isinstance(self._rep... |
jmatthed/avatar-python | avatar/util/processes.py | Python | apache-2.0 | 796 | 0.007538 | '''
Created on Jun 26, 2013
@author: Jonas Zaddach <zaddach@eurecom.fr>
'''
import subprocess
def get_process_list():
processes = []
ps_output = subprocess.check_output(["ps", "-A", "-w", "-w", "-o", "pid", "-o", "command"])
ps_output = ps_output.decode('latin-1')
for line in ps_output.split("\n")[1:]... | s.append({"pid": int(pid), "cmd | ": cmd})
return processes
def find_processes(name):
process_list = get_process_list()
found_processes = []
for process in process_list:
if process["cmd"].startswith(name):
found_processes.append(process)
return found_processes |
hsgweon/sgtoolkit | sgtoolkit/sgtk_getsamplelistfromfasta.py | Python | gpl-2.0 | 1,239 | 0.021792 | #!/usr/bin/python
############################################################
# Argument Options
import argparse
parser = argparse.ArgumentParser("Creates a sample list f | ile from a fasta sequences.")
parser.add_argument("-i",
action = "st | ore",
dest = "infile",
metavar = "infile",
help = "[REQUIRED]",
required = True)
parser.add_argument("-o",
action = "store",
dest = "outfile",
metavar = "outfile",
... |
alikzao/tao1 | tao1/core/utils.py | Python | mit | 121 | 0.008264 | #!/u | sr/bin/env python
from tao1.core.utils_ import manage_console
if __name__ == "__main__":
| manage_console()
|
shafaypro/PYSHA | _StackoverFlow.py | Python | gpl-3.0 | 606 | 0.013201 | import webbrowser
# ToDO: You can improve the Search using the OAUTH and other apis of the stack over flow
class Stack | overFlow:
def __init__ (self):
pass
def search (self, search_text=''):
search_text = search_text.strip()
search_text = search_text.replace(' ', '+') # This replaces the spaces with the + sign
search_url = "http://stackoverflow.com/search?q=" + sea | rch_text
webbrowser.open(search_url)
return search_url # returns the search url for the reading purposes
#need to work with the api instead of the static referring |
166MMX/openjdk.java.net-openjfx-8u40-rt | modules/web/src/main/native/Tools/Scripts/webkitpy/common/checkout/scm/detection.py | Python | gpl-2.0 | 3,835 | 0.002868 | # Copyright (c) 2009, 2010, 2011 Google Inc. All rights reserved.
# Copyright (c) 2009 Apple Inc. All rights reserved.
#
# 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 reta... | filesyst | em, executive):
self._filesystem = filesystem
self._executive = executive
def default_scm(self, patch_directories=None):
"""Return the default SCM object as determined by the CWD and running code.
Returns the default SCM object for the current working directory; if the
CWD ... |
Hernanarce/pelisalacarta | python/main-classic/servers/youtube.py | Python | gpl-3.0 | 8,299 | 0.006145 | # s-*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para Youtube
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
import urlparse
from core import c... | 1:
url += "/"
url += urllib.unquote(url_desc_map["stream"])
elif url_desc_map.get("stream") and not url_desc_map.get("conn"):
url = urllib.unquote(url_desc_map["stream"])
if url_de | sc_map.get("sig"):
url += "&signature=" + url_desc_map["sig"]
elif url_desc_map.get("s"):
sig = url_desc_map["s"]
if not js_signature:
urljs = scrapertools.find_single_match(youtube_page_data, '"assets":.*?"js":\s*"([^"]... |
dunphyben/btce-api | test/test_public.py | Python | mit | 2,447 | 0.000409 | import decimal
import unittest
from btceapi.public import *
class TestPublic(unittest.TestCase):
def test_constructTrade(self):
d = {"pair": "btc_usd",
"trade_type": "bid",
"price": decimal.Decimal("1.234"),
"tid": 1,
"amount": decimal.Decimal("3.2"),
... | of decimal dates
d["date"] = decimal.Decimal("1368805684.878004")
t = Trade(**d)
assert type(t.date) is datetime.datetime
self.assertEqual(t.date, test_date)
# check conversion of integer dates
d["date"] = 1368805684
test_date = datetime.datetime.fromtimestamp(1... | test_date)
# check conversion of string dates with no fractional seconds
d["date"] = "2013-05-17 08:48:04"
t = Trade(**d)
assert type(t.date) is datetime.datetime
self.assertEqual(t.date, datetime.datetime(2013, 5, 17, 8, 48, 4, 0))
# check conversion of string dates wi... |
salv-orlando/MyRepo | nova/tests/scheduler/test_distributed_scheduler.py | Python | apache-2.0 | 10,588 | 0.000472 | # Copyright 2011 OpenStack LLC.
# 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... | dict(weight=6, blob='CCCCCCC'),
dict(weight=8, blob='DDDDDDD'),
]),
(2, [
dict(weight=10, blob='EEEEEEE'),
dict(weight=12, blob='FFFFFFF'),
dict(weight=14, blob='GGGGGGG'),
dict(weight=16, blob='HHHHHHH'),
]),
(3, [
... | 0, blob='JJJJJJJ'),
dict(weight=22, blob='KKKKKKK'),
dict(weight=24, blob='LLLLLLL'),
]),
]
def fake_zone_get_all(context):
return [
dict(id=1, api_url='zone1',
username='admin', password='password',
weight_offset=0.0, weight_scale=1.0),
... |
kiwifb/numpy | numpy/f2py/crackfortran.py | Python | bsd-3-clause | 126,846 | 0.001908 | #!/usr/bin/env python
"""
crackfortran --- read fortran (77,90) code and extract declaration information.
Copyright 1999-2004 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@ioc.ee>
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.
NO WARRANTY IS EXPRESSE... |
====================================================================
(Main source: IBM XL Fortran 5.1 Language Reference Manual)
type declaration = <typespec> [[<attrspec>]::] <entitydecl>
<typespec> = byte |
character[<charselector>] |
complex[<kindselector>] | |
double complex |
double precision |
integer[<kindselector>] |
logical[<kindselector>] |
real[<kindselector>] |
type(<typename>)
<charselector> = * <charlen> |
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.