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 |
|---|---|---|---|---|---|---|---|---|
Lex0ne/trafaret_validator | tests/test_metaclass.py | Python | mit | 1,906 | 0 | from unittest import TestCase
import trafaret as t
from trafaret_validator import TrafaretValidator
class ValidatorForTest(TrafaretValidator):
t_value = t.Int()
value = 5 |
class ValidatorForTest2(ValidatorForTest):
test = t.String()
class TestMetaclass(TestCase):
def test_metaclass(self):
self.assertIsInstance(ValidatorForTest._validators, dict,
'Value should be instance of dict')
self.assertIn('t_value', ValidatorForTest._valid... | 'Value should be in _validators')
self.assertNotIn('value', ValidatorForTest._validators,
'Value should not be in _validators')
self.assertIsInstance(ValidatorForTest._trafaret, t.Trafaret,
'Value should be instance of Trafaret')... |
adalmieres/scriptsIBMConnections | IBMConnectionsSocialGraph.py | Python | gpl-3.0 | 8,111 | 0.041435 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# dépendances
import requests
import xml.dom.minidom
import sys
import signal
import os
import getopt
from queue import Queue
from threading import Thread
import time
class SetQueue(Queue):
def _init(self, maxsize):
Queue._init(self, maxsize)
self.a... | gin, pwd)
totalResult = dom.getElementsByT | agName('opensearch:totalResults')[0]
totalResult = int(totalResult.firstChild.data)
if totalResult > 250:
nbPage = int(float(totalResult) / 250) + 1
for n in range(1,nbPage,1):
item = url + "&page=" + str(n)
q.put(item)
else:
nbPage = 1
q.put(url)
def getUserIdsWorker(login, pwd, qin, qout):... |
sparkslabs/kamaelia_ | Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Support/Data/tests/test_Escape.py | Python | apache-2.0 | 7,515 | 0.006121 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ver... | t use this file except in compliance with the License.
# You may obtain a copy of the License a | t
#
# 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 governin... |
alephdata/ingestors | ingestors/support/package.py | Python | mit | 1,257 | 0 | import shutil
import logging
from followthemoney import model
from ingestors.support.temp import TempFileSupport
from ingestors.support.encoding import EncodingSupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
class PackageSupport(TempFileSupport, EncodingSupport):
def ... | None or fh is None:
return
file_name = out_path.name
try:
log.debug("Unpack: %s", file_name)
with open(out_path, "wb") as out_fh:
shutil.copyfileobj(fh, out_fh)
finally:
fh.close()
def ingest(self, file_path, entity):
... | (file_path, entity, temp_dir)
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
def unpack(self, file_path, entity, temp_dir):
pass
|
hellais/luigi | test/central_planner_test.py | Python | apache-2.0 | 28,970 | 0.001277 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | R, 'A')
| self.assertEqual(self.sch.get_work(WORKER)['task_id'], 'A')
self.sch.add_task(WORKER, 'A', FAILED)
for t in range(100):
self.setTime(t)
self.assertEqual(self.sch.get_work(WORKER)['task_id'], None)
self.sch.ping(WORKER)
if t % 10 == 0:
self... |
timwee/emacs-starter-kit-mr-flip-forked | vendor/rope/ropetest/builtinstest.py | Python | gpl-3.0 | 20,183 | 0.00104 | import unittest
from rope.base import pyobjects, builtins
from ropetest import testutils
class BuiltinTypesTest(unittest.TestCase):
def setUp(self):
super(BuiltinTypesTest, self).setUp()
self.project = testutils.sample_project()
self.pycore = self.project.pycore
self.mod = testut... | ject):\n pass\n'
'd = {C1(): C2()}\nfor c in d.keys():\n a_var = c\n')
pymod = self.pycore.resource_to_pyobject(self.mod)
c_class = pymod['C1'].get_object()
a_var = pymod['a_var'].get_object()
self.assertEquals(c_class, a_var.get_type())
def test_getting... | :\n pass\nclass C2(object):\n pass\n'
'd = {C1(): C2()}\nfor c in d.values():\n a_var = c\n')
pymod = self.pycore.resource_to_pyobject(self.mod)
c_class = pymod['C2'].get_object()
a_var = pymod['a_var'].get_object()
self.assertEquals(c_class, a_var.get_typ... |
improlabs/Banglish-Sentiment-Analysis | python3/senalysis-1.py | Python | gpl-3.0 | 530 | 0 | #!/usr/local/bin/python
from pyavrophonetic import avro
from textblob import TextBlob
from vade | rSentiment.vaderSentiment import SentimentIntensityAnalyzer
import sys
b = input("Enter Banglish :")
textBlobTrans = TextBlob(avro.parse(b))
c = str(textBlobTrans.translate(to='en'))
print(c)
analyze = TextBlob(c)
print('By TextBlob Sentiment analysis')
print(analyze.sentiment)
print('By vaderSenti... | imentIntensityAnalyzer()
vs = analyzer.polarity_scores(c)
print(str(vs))
|
theithec/bookhelper | bookhelper/tests/test_init.py | Python | mit | 741 | 0.006748 | from unittest import TestCase
# from unittest import mock
from mwclient import | Site
from bookhelper import ExistingBook
from . import PageMock, SiteMock, TESTBOOK1_TXT
#Site.login=mock.MagicMock(return_value=True)
class TestInit(TestCase):
def setUp(self):
self.site = SiteMock()
def test_book(self):
book = ExistingBook(self.site, "Testbook1", "live")
self.ass... | .friendly_title, "Testbook1")
self.assertEqual(book.book_page.text.strip(), TESTBOOK1_TXT)
self.assertEqual(book.toc[0].target,'Testbook1/Page1')
self.assertEqual(book.toc[1].target,'Testbook1/Page2')
self.assertEqual(book.toc[1].text,'Page2')
|
cgwire/zou | zou/app/blueprints/crud/search_filter.py | Python | agpl-3.0 | 370 | 0 | from zou.app.models.search_filter import Search | Filter
from .base import BaseModelResource, BaseModelsResource
class SearchFiltersResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, SearchFilter)
class SearchFilterResource(BaseModelResource):
def _ | _init__(self):
BaseModelResource.__init__(self, SearchFilter)
|
jdthorpe/archiver | __main__.py | Python | mit | 13,106 | 0.011064 | # this is the interface for `python archiver`
import archiver
import appdirs
import os
import sys
import pickle
import json
from archiver.archiver import Archiver
from archiver.parser import parseArgs
args = parseArgs()
from edit import edit
# ==============================================
print args
# TODO: s... | --------------------------------
# load the user data
# ------------------------------------------------------------
# get the user data directory
user_data_dir = appdirs.user_data_dir('FileArchiver', 'jdthorpe')
| if not os.path.exists(user_data_dir) :
os.makedirs(user_data_dir)
# LOAD THE INDEX NAMES AND ACTIVE INDEX
indexes_path = os.path.join(user_data_dir,'INDEXES.json')
if os.path.exists(indexes_path):
with open(indexes_path,'rb') as fh:
indexes = json.load(fh)
else:
indexes= {'active':None,'names':[]}
... |
elastic/elasticsearch-py | elasticsearch/_sync/client/xpack.py | Python | apache-2.0 | 4,223 | 0.00071 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | ves usage information about the installed X-Pack features.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/usage-api.html>`_
| :param master_timeout: Period to wait for a connection to the master node. If
no response is received before the timeout expires, the request fails and
returns an error.
"""
__path = "/_xpack/usage"
__query: t.Dict[str, t.Any] = {}
if error_trace is not None:
... |
loic/django | django/core/validators.py | Python | bsd-3-clause | 17,864 | 0.002183 | from __future__ import unicode_literals
import os
import re
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.functional import SimpleLazyObject
from django.utils.ipv6 impo... | 0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, | validated later)
# Host patterns
hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
# Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
tld_re = (
'\.' ... |
pshchelo/ironic | ironic/tests/unit/api/test_root.py | Python | apache-2.0 | 3,515 | 0 | # Copyright 2013 Red Hat, 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... | onic-API-Version': '1.32'},
additional_expected_resources=['heartbeat',
'lookup',
'portgroups',
| 'volume'])
|
thomasbarillot/DAQ | eTOF/WetLab_NewportDelayStage.py | Python | mit | 1,437 | 0.020181 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 04 11:17:15 2016
@author: atto
Piezostage remote control (ie writingdelay into file read by humongium)
"""
import sys
# The CLR module provide functions for interacting with the underlying
# .NET runtime
import visa
import time
# Add reference to assembly and import n... | d_termination='\r')
self.controller.timeout = 1000
| self.stagenum=1
def __del__(self):
self.controller.clear()
self.controller.close()
self.rm.close()
def MoveAbs(self,target):
#
cmd = str(self.stagenum)+'PA'+str(target)+';'+str(self.stagenum)+'WS\r'
status=self.controller.write(unicode(cmd,"utf-8"))
... |
SuLab/PyBioC | src/bioc/bioc_collection.py | Python | bsd-2-clause | 1,302 | 0 | __all__ = ['BioCCollection']
from meta import _MetaInfons, _MetaIter
from compat import _Py2Next
class BioCCollection( | _Py2Next, _MetaInfons, _MetaIter):
def __init__(self, collection=None):
self.infons = dict()
self.source = ''
self.date = ''
self.key = ''
self.documents = list()
if collection is not None:
self.infons = collection.infons
self.source = colle... | self.documents = collection.documents
def __str__(self):
s = 'source: ' + self.source + '\n'
s += 'date: ' + self.date + '\n'
s += 'key: ' + self.key + '\n'
s += str(self.infons) + '\n'
s += str(self.documents) + '\n'
return s
def _iterdata(self):
... |
PMEAL/OpenPNM | openpnm/utils/__init__.py | Python | mit | 983 | 0.001017 | r"""
Utilities and helper classes/functions
==== | ==================================
This module contains two very important classes (Project and Workspace)
as well as a number of helper classes.
"""
import logging as logging
from .misc import *
from ._settings import *
from ._workspace import *
from ._project import *
# You can add info to the logger message by ... | of available items see:
# https://docs.python.org/3/library/logging.html#logrecord-attributes
# NOTE: If the calling locations appears as 'root' it's because the logger
# was not given a name in a file somewhere. A good option is __name__.
log_format = \
'-' * 60 + '\n\
%(levelname)-11s: %(message)s \n\
SOURCE : ... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_hyperlink28.py | Python | bsd-2-clause | 1,640 | 0 | ############################# | ##################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTes... | """
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('hyperlink28.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Workbook(self.got_filename)
... |
ddietze/FSRStools | rraman/__init__.py | Python | gpl-3.0 | 36,173 | 0.003594 | """
.. module: FSRStools.rraman
:platform: Windows
.. moduleauthor:: Daniel Dietze <daniel.dietze@berkeley.edu>
Resonance Raman excitation profile calculation based on the time-domain picture of resonance Raman. See Myers and Mathies in *Biological Applications of Raman Spectroscopy*, Vol. 2, pp. 1-58 (John Wi... | p.arange(numPoints) / (c0 * dt * numPoints)
return t, wn
|
def molarExtinction2AbsCS(eSpctr, IOR):
"""Convert molar extinction (cm-1 / M) to molecular absorption cross section (A**2 / molec).
See McHale, Resonance Raman Spectroscopy, Wiley, (2002), p. 545 or Myers & Mathies for details. The absorption cross section in solution has to be scaled by index of refracti... |
ttm/indicadores-participativos | puxaTweets.py | Python | lgpl-3.0 | 5,174 | 0.024966 | #-*- coding: utf8 -*-
import pymongo, time as T, threading as t, sys
from twython import TwythonStreamer
from twython import Twython
from maccess import TW, mdc
HTAG=["#aao0","#arenaNETmundial","#Participabr"]
HTAG_=[i.replace("#","H") for i in HTAG]
class MyStreamer(TwythonStreamer):
def on_success(self, data):
... | ollection.insert(tweets_depois)
elif 'ttweets' in dir(self):
self.mongo_collection.insert(self.ttweets)
print "sync"
def todosDeDepois(self,si | nce_id):
tweets=[]
tweets_=self.buscaProgressiva(since_id=since_id)[::-1]
while len(tweets_):
tweets+=tweets_[::-1]
T.sleep(20)
tweets_=self.buscaProgressiva(since_id=tweets[-1]["id"])
print "puxados todos os tweets mais recentes ",self.hashtag
... |
NSLS-II-XPD/ipython_ophyd | archived/profile_collection-dev/startup/99-subtracted-tiff-exporter.py | Python | bsd-2-clause | 1,827 | 0.002189 | from time import sleep
from bluesky.callbacks.broker import LiveTiffExporter
from databroker import process
from bluesky import Msg
from bluesky.plans import DeltaScanPlan, DeltaListScanPlan
RE = gs.RE # an alias
def take_dark():
print('closing shutter...')
shctl1.put(0) # close shutter
sleep(2)
pr... | s = loops * list(np.linspace(start, stop, num=num_steps, endpoint=True))
plan = DeltaListScanPlan([pe1c], motor, steps)
uid = RE(plan, subs, dark_frame=dark_uid, **metadata)
sleep(3)
process(db[uid], exporter)
class SubtractedTiffExporter(LiveTiffExporter):
"Intercept image | s before saving and subtract dark image"
def start(self, doc):
# The metadata refers to the scan uid of the dark scan.
if 'dark_frame' not in doc:
raise ValueError("No dark_frame was recorded.")
uid = doc['dark_frame']
dark_header = db[uid]
self.dark_img, = get_i... |
rodo/tsung-gis | build_scenario.py | Python | gpl-3.0 | 3,719 | 0.003227 | #!/usr/bin/env python3
"""
Generate all the xml files for each actions, the module are
defined in the src directory
Example :
build_directory.py -m map
"""
import os
import sys
from optparse import OptionParser
__version__ = "0.0.2"
def arg_parse():
""" Parse command line arguments """
arg_list = "-m mod... | &load;
<sessions>
<session name="init">
</session>
</sessions>
</tsung>"""
def render(options, module, action, subaction, skeleton):
"""Write an entity file
"""
name = '{}_{}_{}.xml'.format(module, action, subaction)
fpath = os.path.join(options.outputdir, name)
print ("write {}".f... | t ('{} directory does not exists'.format(opts.outputdir))
sys.exit(1)
if opts.module is not None:
main(opts)
else:
print("please add at least one module with -m")
sys.exit(1)
|
shub0/algorithm-data-structure | python/PopSugar.py | Python | bsd-3-clause | 1,436 | 0.002786 | #! /usr/bin/python
class Seat:
# @param index, an integer
def __init__(self, index):
self.index = index
self.next = None
class Room:
# @param num_seat, an integer
def __init__(self, num_seat):
if num_seat < 1:
raise VauleError('invalid room config') |
seat = Seat(1)
constructor = seat
for index in range(2, num_seat + 1):
constructor.next = Seat(index)
constructor = constructor.next
constructor.next = | seat
self.token = seat
self.num_seat = num_seat
# @param start_index, an integer
def initial_token(self, start_index=1):
while self.token.next.index != start_index:
self.token = self.token.next
# @return a boolean
def remove_seat(self):
if self.num_seat == ... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/IPython/testing/tools.py | Python | bsd-2-clause | 13,960 | 0.003438 | """Generic testing tools.
Authors
-------
- Fernando Perez <Fernando.Perez@berkeley.edu>
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import re
import sys
import tempfile
from contextlib import contextmanager
from io import StringIO
from subproc... | a.txt', '/f | oo/b.txt']
>>> full_path('/foo',['a.txt','b.txt'])
['/a.txt', '/b.txt']
If a single file is given, the output is still a list::
>>> full_path('/foo','a.txt')
['/a.txt']
"""
files = list_strings(files)
base = os.path.split(startPath)[0]
return [ os.path.join(base,f) for f ... |
listyque/TACTIC-Handler | thlib/ui_classes/ui_drop_plate_classes.py | Python | epl-1.0 | 18,599 | 0.001505 | # file ui_drop_plate_classes.py
import os
from thlib.side.Qt import QtWidgets as QtGui
from thlib.side.Qt import QtGui as Qt4Gui |
from thlib.side.Qt import QtC | ore
from thlib.environment import env_mode, env_inst, env_write_config, env_read_config
import thlib.global_functions as gf
import thlib.ui.checkin_out.ui_drop_plate as ui_drop_plate
import thlib.ui.checkin_out.ui_drop_plate_config as ui_drop_plate_config
from thlib.ui_classes.ui_custom_qwidgets import Ui_horizontalCo... |
pipex/gitbot | config.py | Python | apache-2.0 | 1,016 | 0.002953 | from __future__ import absolute_import
from __future__ import unicode_literals
class Config(object):
DEBUG = False
TESTING = False
# Host for the redis server
REDIS = 'redis'
# Do not push this to a public repo
SLACK_DEFAULT_CHANNEL = '#general'
SLACK_DEVELOPERS_CHANNEL = '#developers'
... | tion directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Log file (the directory must exist)
APPLICATION_LOG = os.path.j | oin(BASE_DIR, 'log', 'application.log')
# Secret key for flask sessions and CSRF protection
SECRET_KEY = "secret key that you need to change, seriously!"
class ProductionConfig(Config):
SLACK_TOKEN = 'here you put the slack token'
# Gitlab hook url
GITLAB_HOOK = '/hooks/bWxNGVQij55cCZigeKDlXf9P6L... |
Aerojspark/PyFR | pyfr/readers/gmsh.py | Python | bsd-3-clause | 6,856 | 0.000729 | # -*- coding: utf-8 -*-
from collections import defaultdict
import re
import numpy as np
from pyfr.readers import BaseReader, NodalMeshAssembler
from pyfr.readers.nodemaps import GmshNodeMaps
def msh_section(mshit, section):
endln = '$End{}\n'.format(section)
endix = int(next(mshit)) - 1
for i, l in e... | isinstance(msh, str):
msh = open(msh)
# Get an iterator over the lines of the mesh
mshit = iter(msh)
# Requir | ed section readers
sect_map = {'MeshFormat': self._read_mesh_format,
'Nodes': self._read_nodes,
'Elements': self._read_eles,
'PhysicalNames': self._read_phys_names}
req_sect = frozenset(sect_map)
# Seen sections
seen_sect = set... |
tensorflow/lingvo | docs/apidoc/conf.py | Python | apache-2.0 | 6,969 | 0.001004 | # Lint as: python3
# 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 ... | 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'lingvo', u'Lingvo Documentation', [author], 1)]
# -- Options for Texinfo output -------... | ----------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'lingvo', u'Lingvo Documentation', author, 'Lingvo',
'One line description of project.', 'Miscel... |
chnops/code | fastq_to_fasta.py | Python | mit | 177 | 0.00565 | import os
import sys
from Bio import SeqIO
f = open(sys.argv[1], 'rU')
out = open(sys.argv[2], 'w')
for | records in SeqIO.pars | e(f, 'fastq'):
SeqIO.write(records, out, 'fasta')
|
sboily/xivo-admin-ivr-plugins | xivo_ivr/plugins/home/load.py | Python | gpl-3.0 | 148 | 0.006757 | from xivo_admin import BasePlugi | n
from views import home
class XiVOHome(BasePlugin):
def load(self, app):
app.register_b | lueprint(home)
|
dgu-dna/DNA-Bot | apps/delete_memo.py | Python | mit | 1,080 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from apps.decorators import on_command
from apps.slackutils import isNumber
from time import localtime, strftime
import json
CACHE_DEFAULT_URL = './apps/memo_cache/memo_cache.json'
@on_command(['!메모삭제', '!ㅁㅁㅅㅈ', '!aatw'])
def run(robot, channel, tokens, ... | ine in del_line:
del jdat[user][l | ine - 1]
with open(CACHE_DEFAULT_URL, 'w') as fp:
json.dump(jdat, fp, indent=4)
del_line = map(lambda s: str(s), del_line)
msg = '<' + ', '.join(sorted(del_line)) + '> 메모를 삭제 했음.'
return channel, msg
|
ingadhoc/demo | demo_simple/__manifest__.py | Python | agpl-3.0 | 3,001 | 0 | ##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | rsion 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for mor... | es/>.
#
##############################################################################
{
'name': 'Demo Simple',
'version': '13.0.1.0.0',
'category': 'Tools',
'sequence': 14,
'summary': '',
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3',
'images': [
],
... |
tdda/tdda | tdda/constraints/pdverify.py | Python | mit | 126 | 0.007937 | # -*- coding: utf-8 -*-
"""
Compatibility module for TDDA Pandas constraints.
"""
from | tdda.constraints.pd.verify import | *
|
gdanezis/rousseau-chain | hippiehug-package/tests/test_tree.py | Python | bsd-2-clause | 5,884 | 0.03416 | from hippiehug import RedisStore, Tree, Leaf, Branch
import pytest
## ============== TESTS ===================
def test_evidence():
t = Tree()
# Test positive case
t.add(b"Hello", b"Hello")
t.add(b"World", b"World")
root, E = t.evidence(b"World")
assert len(E) == 2
store = dict... | est_multi_test | ():
t = Tree()
t.multi_add([b"Hello", b"World"])
assert t.multi_is_in([b"Hello", b"World"]) == [True, True]
answer, head, evidence = t.multi_is_in([b"Hello", b"World"], evidence=True)
assert answer == [True, True]
e = dict((k.identity(), k) for k in evidence)
t2 = Tree(e, head)
... |
razisayyed/django-ads | ads/templatetags/ads_tags.py | Python | apache-2.0 | 956 | 0 | from __future__ import unicode_literals
from django import template
from django.conf import settings
from django.utils import timezone
from ads.models import Ad
register = template.Library()
@register.inclusion_tag('ads/tags/render_ads_zone.html', takes_context=True)
def render_ads_zone(context, zone):
"""
... | urns an advertise for a ``zone``.
Tag usage:
{% load ads_tags %}
{% render_zone 'zone' %}
"""
context.update({
'google_adsense_client': settings.ADS_GOOGLE_ADSENSE_CLIENT,
'zone': zone,
'zone_info': settings.ADS_ZONES.get(zone, None)
})
return context
@register.simp... | count %}
{% get_ads_count 'zone1,zone2,zone3' as ads_count %}
"""
zone = zone.split(',')
return Ad.objects.public().filter(zone__in=zone).count()
|
xtao/flask-weixin | setup.py | Python | bsd-3-clause | 1,257 | 0 | #!/usr/bin/env python
# coding: utf-8
|
try:
# python setup.py test
import multiprocessing
except ImportError:
pass
import os
import re
from setuptools import setup
def fread(fname):
filepath = os.path.join(os.path.dirname(__file__), fname)
with open(filepath) as f:
return f.read()
content = fread('flask_weixin.py')
m = re... | all(r'__version__\s*=\s*\'(.*)\'', content)
version = m[0]
setup(
name='Flask-Weixin',
version=version,
url='https://github.com/lepture/flask-weixin',
author='Hsiaoming Yang',
author_email='me@lepture.com',
description='Weixin for Flask.',
long_description=fread('README.rst'),
license=... |
westurner/pwd | setup.py | Python | bsd-3-clause | 1,441 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
| from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
| readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='pwd',
version='0.3.5',
... |
lehmannro/translate | storage/wordfast.py | Python | gpl-2.0 | 16,175 | 0.006636 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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... | he hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with translate; if not, write to t... | ion, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Manage the Wordfast Translation Memory format
Wordfast TM format is the Translation Memory format used by the
U{Wordfast<http://www.wordfast.net/>} computer aided translation tool.
It is a bilingual base class derived format with L{Wordf... |
cangencer/hazelcast-python-client | hazelcast/protocol/codec/list_is_empty_codec.py | Python | apache-2.0 | 1,038 | 0.000963 | from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.list_message_type import *
REQUEST_TYPE = LIST | _ISEMPTY
RESPONSE_TYPE = 101
RETRYABLE = True
d | ef calculate_size(name):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
return data_size
def encode_request(name):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name))
client_message.set_... |
shanestockall/EECS-Grading-Rig | src/packages/EECS-211-Grader/acceptancetest_osx.py | Python | mit | 2,279 | 0.035542 | import hashlib
import shutil
import os
from datetime import datetime
list_of_paths_and_strings = [
["assignment1.cpp", "main()"]
]
def main():
abspath = os.path.abspath(__file__)
dname = os.path.dirname(sys.argv[0])
os.chdir(dname)
if acceptance_test():
make_txt_file()
zip_dir()
def get_md... | file with each of the hashes for each of the files using MD5
write_file = open("hash.txt", "w+")
write_file.write("Write time: " + str(get_current_time()) + '\n')
for file in os.listdir(os.getcwd()):
if "." in file:
f_name, file_hash = get_md5_hash(file)
write_file.write(f_name + '\n')
write_file... | r("./tmp")
for file in os.listdir(os.getcwd()):
try:
if ".pdf" in file:
continue
elif "acceptancetest" in file:
continue
else:
shutil.copy(file, './tmp/')
except:
continue
shutil.make_archive(zip_name, 'zip', directory_name)
shutil.rmtree('./tmp')
if __name__ == ... |
jorisvandenbossche/DS-python-data-analysis | notebooks/_solutions/case2_biodiversity_analysis6.py | Python | bsd-3-clause | 123 | 0.01626 | survey_data_processed[survey_data_processed.duplicated(keep=False)].sort_valu | es(["eventDate", "verbatimLocality"]) | .head(10) |
jchristman/adventofcode | 13/win.py | Python | mit | 2,809 | 0.00712 | # ----------------------------------------------------------------------------------------------------------------------
# Advent of Code - Day 13
#
# The Python One-Liner challenge:
#
# Rules:
#
# - Reading input into a variable from another file or with an assignment is acceptable and does not count against
# ... | == 0 else -int(re.findall(r'[0-9]+', line)[0]) for line in open('input2', 'r').read().splitlines() if re.findall(r'[A-Z][a-z]+', line)[0] == n | ame } for name in set(re.findall(r'[A-Z][a-z]+', open('input2', 'r').read())) }
print max((reduce(lambda first_total, second: (first_total[0] + [second], first_total[1] + _input[first_total[0][-1]][second] + _input[second][first_total[0][-1]]), [([arrangement[-1]], 0)] + list(arrangement)) for arrangement in itertools... |
ajpocus/pizzeria | order/forms.py | Python | bsd-3-clause | 1,411 | 0.019135 | from django import forms
from or | der.models import Pizza, Bread, Customer
class PizzaForm(forms.ModelForm):
class Meta:
model = Pizza
fields = ('size', 'toppings', 'crust')
widgets = {
'size': forms.RadioSelect(),
'crust': forms.RadioSelect(),
'toppings': forms.CheckboxSelectMultiple(),
... | izza = Pizza.objects.create()
pizza.size = size
pizza.crust = crust
for topping in toppings:
pizza.toppings.add(topping)
pizza.save()
order.pizzas.add(pizza)
order.save()
class BreadForm(forms.ModelForm):
class Meta:
model = Bread
fields = ('flavor',)
widget... |
iticus/spotlipy | settings_default.py | Python | mit | 1,141 | 0.008764 | '''
Created on Jun 20, 2016
@author: ionut
'''
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("u | rllib3").setLevel(logging.WARNING)
logging.getLogger("spotify.search").setLevel(logging.WARNING)
logging.getLogger("spotify.session").setLevel(logging.WARNING)
#Database connection - Postgres / Amazon RDS
DSN = "dbname='spotlipy' user='postgres' | host='127.0.0.1' password='password'"
#dogstarradio search URL
SEARCH_URL = 'http://www.dogstarradio.com/search_playlist.php'
JUNK_INDICATORS = ['@', '#', '.com', 'Hip Hop Nation', 'SiriusXM']
#for stations numbers and names see stations.txt
STATIONS = [
34, 44
]
#if MONTH or DATE are None we will use yesterday ... |
dcramer/django-db-log | djangodblog/migrations/0004_fill_error_checksums.py | Python | bsd-3-clause | 3,710 | 0.007817 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
from djangodblog.helpers import construct_checksum
for e in orm.Error.obj... | me': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
' | id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index'... |
tswast/google-cloud-python | asset/google/cloud/asset_v1/gapic/transports/asset_service_grpc_transport.py | Python | apache-2.0 | 7,999 | 0.001375 | # -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | dress (str): The address where the service is hosted.
"""
# If both `channel` and `credentials` are specified, raise an
# exception (channels come with credentials baked in already).
if channel is not None and credentials is not None:
raise ValueError(
"The `c... | s None:
channel = self.create_channel(
address=address,
credentials=credentials,
options={
"grpc.max_send_message_length": -1,
"grpc.max_receive_message_length": -1,
}.items(),
)
self... |
axant/tgapp-mailtemplates | mailtemplates/model/ming/models.py | Python | mit | 997 | 0 | from ming.odm import FieldProperty
from ming.odm import ForeignIdProperty
from ming.odm import MappedClass
from ming.odm import RelationProperty
from mailtemplates.model import DBSession
from ming import schema as s
class MailModel(MappedClass):
class __mongometa__:
name = 'mailtemplates_mail_models'
... | usage = FieldProperty(s.String, required=True)
template_translations = RelationProperty('TemplateTranslation')
class TemplateTranslation(MappedClass):
class __mongometa__:
nam | e = 'mailtemplates_template_translations'
session = DBSession
_id = FieldProperty(s.ObjectId)
mail_model_id = ForeignIdProperty('MailModel')
mail_model = RelationProperty('MailModel')
language = FieldProperty(s.String, required=True)
subject = FieldProperty(s.String)
body = FieldPropert... |
petterreinholdtsen/cinelerra-hv | thirdparty/OpenCV-2.3.1/samples/python2/facedetect.py | Python | gpl-2.0 | 1,942 | 0.010299 | import numpy as np
import cv2
import cv2.cv as cv
from video import create_capture
from common import clock, draw_str
help_message = '''
USAGE: facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
def detect(img, cascade):
rects = cascade.detectMultiScale(img, sca... | s_roi = vis[y1:y2, x1:x2]
subrects = detect(roi.copy(), nested)
draw_rects(vis_roi, subrects, (255, 0, 0))
dt = clock() - t
draw | _str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
cv2.imshow('facedetect', vis)
if cv2.waitKey(5) == 27:
break
|
tencentyun/cos-python-sdk | setup.py | Python | mit | 523 | 0.026769 | #!/usr/bin/env python
# coding=utf-8
import sys
if sys.version_info[0] != 2 or sys.version_info[1] < 6:
sys.exit('Sorry, only python 2.6 or 2.7 is | supported')
from setuptools import setup, find_packages
setup(
name = 'qcloud_cos',
version = '3.3',
description = 'python sdk for tencent qcloud cos',
| license = 'MIT License',
install_requires=['requests'],
author = 'chengwu',
author_email = 'chengwu@tencent.com',
packages = find_packages(),
)
|
rafalcieslinski/pgspecial | scripts/docparser.py | Python | bsd-3-clause | 1,456 | 0.001374 | from bs4 import BeautifulSoup
import sys
import os
import json
def get_secti | on(doc, section):
element = doc.find(section)
if element:
return element.get_text | ()
def get_description(doc):
text = get_section(doc, "refsect1")
if text:
lines = filter(lambda x: x.strip(), text.split("\n"))
if len(lines) > 1 and lines[0] == "Description":
return lines[0] + "\n" + lines[1]
def parse(file_name):
with open(file_name, "r") as file:
... |
jonathanmorgan/django_reference_data | migrations/0001_initial.py | Python | gpl-3.0 | 4,641 | 0.008403 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Reference_Domain'
db.create_table(u'django_reference_data_reference_domain', (
(... | object_name': 'Reference_Domain'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'county': ('django.db.models.fie... | nk': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'domain_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'domain_path': ('django.db.models.fields.CharField', [], {'max_length': '2... |
RaveYoda/Shellmen | src/core/mixins/StylesMixin.py | Python | gpl-2.0 | 2,111 | 0.001895 | # Python imports
# Lib imports
from PyInqui | rer import style_from_dict, Token
# Application imports
class StylesMixin:
"""
The StylesMixin has style methods that get called and
return their respective objects.
"""
def default(self):
retur | n style_from_dict({
Token.Separator: '#6C6C6C',
Token.QuestionMark: '#FF9D00 bold',
# Token.Selected: '', # default
Token.Selected: '#5F819D',
Token.Pointer: '#FF9D00 bold',
Token.Instruction: '', # default
Token.Answer: '#5F819D bold... |
garoa/concorrente.py | tkinter/tkapp2.py | Python | cc0-1.0 | 7,362 | 0.003667 | import tkinter as tk
import asyncio
import threading
from tkevents import TkEventLoop
from HardWork import *
import concurrent.futures
@asyncio.coroutine
def async(it, *args):
return (yield from asyncio.get_event_loop().run_in_executor(None, it, *args))
class Application(tk.Frame):
def __init_... | s after counting".format(len(count))
def words_sorted(future_most_common):
def words_sorted_update_ui():
self.status[3]["text"] = "Sorting..."
most_common = future_mo... | text"] = "The ten most common words: {0}".format(', '.join(most_common))
print('Sorting on thread ', threading.get_ident())
self.after(0, words_sorted_update_ui)
future_most_common = executor.submit(get_most... |
hkv-consultants/bowa | bowa/tools.py | Python | gpl-3.0 | 382 | 0 | # (c) Nelen & Schuurma | ns. GPL lice | nsed, see LICENSE.rst.
from __future__ import unicode_literals
def version():
"""
return version string
"""
from pkginfo.installed import Installed
import bowa
installed = Installed(bowa)
if installed.version:
return 'Versie april 2014 (%s)' % (installed.version)
else:
... |
robotframework/mabot | src/mabot/settings/defaultsettings.py | Python | apache-2.0 | 846 | 0 | # Copyright 2008 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file e | xcept in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
default_message = "Not Executed!"
ask_tags_a... |
Pierre-Sassoulas/django-survey | survey/migrations/0008_translated_name_for_models.py | Python | agpl-3.0 | 6,920 | 0.002601 | # Generated by Django 1.11.13 on 2018-06-26 16:51
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("survey", "0007_auto_20180217_1515")]
operations = [
migrations.AlterModelOptions(
... | field=models.DateTimeField(auto_now_add=True, verbose_name="Creation date"),
),
migrations.AlterField(
model_name="answer",
name="question",
field=mo | dels.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="answers",
to="survey.Question",
verbose_name="Question",
),
),
migrations.AlterField(
model_name="answer",
name="response",
... |
thica/ORCA-Remote | src/ORCA/utils/Platform/generic/generic_GetIPAddressV6.py | Python | gpl-3.0 | 2,158 | 0.008341 | # -*- coding: utf-8 -*-
"""
ORCA Open Remote Control Application
Copyright (C) 2013-2020 Carsten Thielepape
Please contact me by : http://www.orca-remote.org/
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publi... | the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This | program is distributed in the hope that it will be useful,
but WITHOUT 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
... |
nagyistoce/edx-platform | lms/djangoapps/courseware/masquerade.py | Python | agpl-3.0 | 9,747 | 0.004001 | '''
---------------------------------------- Masquerade ----------------------------------------
Allow course staff to see a student or staff view of courseware.
Which kind of view has been selected is stored in the session state.
'''
import logging
from django.conf import settings
from django.contrib.auth.decorators... | masquerading as, or None | if no masquerade is in effect.
"""
course_masquerade = get_course_masquerade(user, course_key)
return course_masquerade.role if course_masquerade else None
def is_masquerading_as_student(user, course_key):
"""
Returns true if the user is a staff member masquerading as a student.
"""
retur... |
endlessm/chromium-browser | chrome/android/monochrome/scripts/monochrome_apk_checker.py | Python | bsd-3-clause | 9,387 | 0.008735 | #!/usr/bin/env python2.7
#
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import re
import os
import posixpath
import StringIO
import sys
import subprocess
from contextlib import closing
... | se in monochrome.
Verify files not being compressed in apk are also uncompressed in
Monochrome APK.
"""
uncompressed = [i.filename for i in apk if i.uncompressed ]
monochrome_uncompressed = [i.filename for i in monochrome if i.uncompressed | ]
compressed = [u for u in uncompressed if u not in monochrome_uncompressed]
if len(compressed):
raise Exception("The following files are compressed in Monochrome:\n %s" %
'\n'.join(compressed))
def SuperSetOf(monochrome, apk):
"""Verify Monochrome is super set of apk."""
def exists_in... |
krig/booth | test/runtests.py | Python | gpl-2.0 | 1,540 | 0.004545 | #!/usr/bin/python
import os
import re
import shutil
import sys
import tempfile
import time
import unittest
from clienttests import ClientConfigTests
from sitetests import SiteConfigTests
from arbtests import ArbitratorConfigTests
if __name__ == '__main__':
if os.geteuid() == 0:
sys.stderr.write("Mus... | ,
}
major, minor, micro, releaselevel, serial = sys.version_info
if major > 2 or (major == 2 and minor >= 7):
# New in 2.7
runner_args['buffer'] = True
runner_args['failfast'] = True
pass
# not root anymore, so safe
# needed because old instances might still use the ... | util.rmtree(test_run_path)
sys.exit(0)
else:
print "Left %s for debugging" % test_run_path
sys.exit(1)
|
atvcaptain/enigma2 | lib/python/Tools/CopyFiles.py | Python | gpl-2.0 | 2,263 | 0.02563 | from __future__ import print_function
from Components.Task import PythonTask, Task, Job, job_manager as JobManager
from Tools.Directories import fileExists
from enigma import eTimer
from os import path
from shutil import rmtree, copy2, move
class DeleteFolderTask(PythonTask):
def openFiles(self, fileList):
self.fil... | ng files"))
cmdline = 'cp -Rf "%s" "%s"' % (srcfile, destfile)
AddFileProcessTask(self, cmdline, srcfile, destfile, name)
class MoveFileJob(Job):
def __init__(self, srcfile, destfile, name):
Job.__init__(self, _("Moving files"))
cmdlin | e = 'mv -f "%s" "%s"' % (srcfile, destfile)
AddFileProcessTask(self, cmdline, srcfile, destfile, name)
class AddFileProcessTask(Task):
def __init__(self, job, cmdline, srcfile, destfile, name):
Task.__init__(self, job, name)
self.setCmdline(cmdline)
self.srcfile = srcfile
self.destfile = destfile
self.Pr... |
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/test/process_echoer.py | Python | bsd-3-clause | 225 | 0 | """Write back all data it receives."""
import sys
data = sys.stdin.read(1)
while data:
sys.stdout.write(data)
sys.stdout.flush()
data = sys.stdi | n.read(1)
sys.stderr.write("byebye")
sys.stderr | .flush()
|
raphonic/pomodorotimer | pomodoro.py | Python | mit | 3,109 | 0.00579 | import wx
import datetime
from time import strptime
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Engine = create_engine('sqlite:///pomodoros.db', echo=False)
Base = declarative_base()
... | name__ = "pomodorologs"
id = Column(Integer, primary_key= | True)
completed_at = Column(Date, default=datetime.date.today())
def __init__(self, completed_at=None):
if completed_at is not None: self.completed_at = completed_at
@staticmethod
def get_logs():
today = Session.query(PomodoroLog).filter(PomodoroLog.completed_at == datetime.dat... |
GeorgiaTechDHLab/TOME | topics/migrations/0017_auto_20170630_1627.py | Python | bsd-3-clause | 916 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-30 16:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('topics', '0016_auto_20170627_1602'),
]
operations = [
migrations.AddField(
... | s.AddField(
model_name='topic',
name='rank',
field=models.IntegerField(default=-1),
),
migrations.AddField(
model_name='wordtopicrank',
name='rank',
field=models.IntegerField(default=-1),
),
migrations.AddField(
... | dels.IntegerField(default=-1),
),
]
|
jgraef/pyAGE | age/descriptor.py | Python | lgpl-3.0 | 4,547 | 0.007259 | # age/descriptor.py
# pyAGE - A Python implementation of the Analog Genetic Encoding
# Copyright (C) 2010 Janosch Gräf
#
# 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 the Free
# Software Foundation, either version ... | check_possibilities(self):
keys = ["char_delete", "char_insert", "char_replace", "frag_delete", "frag_move", "frag_copy", "device_insert", "chromosome_delete", "chromosome_copy", "chromosome_crossover"]
if (s | elf.possibilities==None):
self.possibilities = {}
elif (type(self.possibilities)!=dict):
return False
for p in keys:
if (p not in self.possibilities):
self.possibilities[p] = 0.0
else:
try:
self.possibili... |
GerritCodeReview/gerrit | tools/maven/mvn.py | Python | apache-2.0 | 2,729 | 0.000366 | #!/usr/bin/env python3
# Copyright (C) 2013 The Android Open Source Project
#
# 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 ... | gs.a:
cmd = [
'mvn',
'gpg:sign-and-deploy-file',
'-Dversion=%s' % args.v,
'-DrepositoryId=%s' % args.repository,
'-Durl=%s' % args.url,
]
else:
print("unknown action -a %s" % args.a, file=stderr)
exit(1)
for spec in args.s:
artifact, packaging_type, src | = spec.split(':')
exe = cmd + [
'-DpomFile=%s' % path.join(root, 'tools', 'maven',
'%s_pom.xml' % artifact),
'-Dpackaging=%s' % packaging_type,
'-Dfile=%s' % src,
]
try:
if environ.get('VERBOSE'):
print(' '.join(exe), file=stder... |
grepory/tomboy | test/DBusSearchTest.py | Python | lgpl-2.1 | 859 | 0.023283 | #!/usr/bin/python
"""Usage : ./tomboy.py <True|False> <search-term> <search-term> ...
For Example:
./tomboy.py | True Hello Res
./tomboy.py True Hello
./tomboy.py True hlo
"""
import sys
import dbus
import gobject
import dbus.glib
# Get the D-Bus session bus
bus = | dbus.SessionBus()
# Access the Tomboy D-Bus object
obj = bus.get_object("org.gnome.Tomboy", "/org/gnome/Tomboy/RemoteControl")
# Access the Tomboy remote control interface
tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
def func(a):
if (len(a)<2):
print __doc__
elif (a[1][0].lower() =="t" or a[1][0... |
frougon/CondConfigParser | condconfigparser/__init__.py | Python | bsd-2-clause | 2,270 | 0 | # -*- coding: utf-8 -*-
# __init__.py --- Initialization of the condconfigparser package.
#
# Copyright (c) 2014, Florent Roug | on
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Red... | e the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,... |
alejob/mdanalysis | package/MDAnalysis/topology/tpr/setting.py | Python | gpl-2.0 | 8,002 | 0 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- http://www.mdanalysis.org
# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | onPotentials, F_RESTRDIHS),
(tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_CBTDIHS),
(26, F_FOURDIHS), (26, F_PIDIHS), (43, F_TABDIHS), (65, F_CMAP),
(60, F_GB12), (61, F_GB13), (61, F_GB14), (72, F_GBPOL),
(72, F_NPSOLVATION), (41, F_LJC14_Q), (41, F_LJC_PAIRS_NB),
(32, F_ | BHAM_LR), (32, F_RF_EXCL), (32, F_COUL_RECIP), (93, F_LJ_RECIP),
(46, F_DPD), (30, F_POLARIZATION), (36, F_THOLE_POL), (90, F_FBPOSRES),
(22, F_DISRESVIOL), (22, F_ORIRES), (22, F_ORIRESDEV),
(26, F_DIHRES), (26, F_DIHRESVIOL), (49, F_VSITE4FDN),
(50, F_VSITEN), (46, F_COM_PULL), (20, F_EQM),
(46, F... |
gnuworldman/site-analytics | src/site_analytics/wsgi.py | Python | gpl-3.0 | 223 | 0 | """WSGI config for | site_analytics project."""
import os
from django.core.wsgi import g | et_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site_analytics.settings")
application = get_wsgi_application()
|
toranb/django-bower-registry | api/migrations/0001_initial.py | Python | mit | 1,703 | 0.007046 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Package'
db.create_table(u'api_package', (
(u'id', self.gf('django.db.models.fie... | e=True, max_length=500)),
('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),
))
db.send_create_signal(u'api', ['Package'])
# Adding unique constraint on 'Package', fields ['name', 'url']
db.create_unique(u'api_package' | , ['name', 'url'])
def backwards(self, orm):
# Removing unique constraint on 'Package', fields ['name', 'url']
db.delete_unique(u'api_package', ['name', 'url'])
# Deleting model 'Package'
db.delete_table(u'api_package')
models = {
u'api.package': {
'Meta'... |
mick-d/nipype | nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py | Python | bsd-3-clause | 1,610 | 0.023602 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..brainsuite import Hemisplit
def test_Hemisplit_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefau... | nputs = Hemisplit.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_Hemisplit_outputs():
output_map = dict(outputLeftHemisphere=dict(),
outputLeftPialHemisphere=dict(... | t.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
|
apmoore1/semeval | lstms/EarlyStoppingLSTM.py | Python | gpl-3.0 | 2,914 | 0.002059 | from semeval import helper as helper
from semeval.lstms.LSTMModel import LSTMModel
import numpy
from keras.models import Sequential
from keras.layers import Dense, Activation, Bidirectional, LSTM, Dropout
from keras.callbacks import EarlyStopping
class EarlyStoppingLSTM(LSTMModel):
'''Model that can train an LST... | has the following dimensions:
length of the longest train text broken down into tokens
by
the vector size of the word2vec mo | del given in the constructor
e.g. 21, 300 if the word2vec model vector size if 300 and the length of
the longest train text in tokens is 21.
For more details on the layers use read the source or after training
visualise using visualise_model function.
'''
super().fit()... |
leifos/tango_with_django_19 | code/tango_with_django_project/rango/forms.py | Python | apache-2.0 | 2,036 | 0.005894 | from django import forms
from rango.models import Page, Category, UserProfile
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.Hi... | class Meta:
# Provide an association between the ModelForm and a model
model = Page
# What fields do we want to include in our form?
# This way we don't need every field in the model present.
# Some fields may allow NULL values, so we may not want to include them...
... | #or specify the fields to include (i.e. not include the category field)
#fields = ('title', 'url', 'views')
class UserProfileForm(forms.ModelForm):
website = forms.URLField(required=False)
picture = forms.ImageField(required=False)
class Meta:
model = UserProfile
exclude = ('us... |
Mashdon/RaspAquaLight | WebServ/WebController.py | Python | mit | 484 | 0.002066 | from threading import RLock
from Model import C_Model
class C_WebCont | roller:
instance_WebController = None
locker = RLock()
@staticmethod
def getInstance():
with C_WebController.locker:
if C_WebController.instance_WebController is None:
C_WebController.instance_WebController = C_WebController()
return C_WebController.inst... | getInstance()
|
jammie080/Twitter-Bot | twitter/user.py | Python | bsd-2-clause | 5,841 | 0.012498 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from settings import config
import scrape, logger
from datetime import datetime
class user(object):
def __init__(self,driver):
self.scrape = scrape.scrape(driver)
self.logger = logger.logger()
self.url = "https://www.twitter.com/"
def is_p... | p(float(mytime))
if(datetime.today() - date).days > days:
return True
else:
return False
def days_since_last_tweet(self,user_id):
mytime | = self.last_tweet_date(user_id)
date = datetime.fromtimestamp(float(mytime))
today = datetime.today()
diff = today - date
days_ago = diff.days
return days_ago
def days_ago(self,user_id):
mytime = self.last_tweet_date(user_id)
date = datetime.fromtimestamp(fl... |
esosn/euler | 55.py | Python | mit | 273 | 0.007326 | import time
from fu | nctions import islychrel
times = []
times.append(time.clock())
limit = 10000
count = 0
for i in range(10, limit):
if islychrel(i, 0, 50):
co | unt += 1
print(count)
times.append(time.clock())
print(times[-1] - times[-2]) |
vzhong/pystacks | pystacks/optimizer.py | Python | mit | 2,213 | 0.002711 | from theano import tensor as T, function, shared, config
import numpy as np
class Optimizer(object):
def update(self, param, grad, lr, transformer=None, grad_transformer=None):
if grad_transformer is not None:
grad = grad_transformer.transform(grad)
param_update, helper_update = self.... | )
new_he | lper = helper + grad**2
return (param, param - lr * grad / T.sqrt(1e-8 + new_helper)), (helper, new_helper)
class RMSProp(Optimizer):
def __init__(self, alpha=0.9, beta=0.1):
super(RMSProp, self).__init__()
self.alpha, self.beta = alpha, beta
def update_(self, param, grad, lr):
... |
figueira/Orinoco-Urgencias | app_enfermedad/admin.py | Python | gpl-3.0 | 294 | 0.003401 | from django. | contrib import admin
from app_enfermedad.models import *
admin.site.register(ParteCuerpo)
admin.site.register(ZonaCuerpo)
admin.site.register(Aspecto)
admin.site.register(AspectoAtencion)
admin.site.register(Anomalia)
admin.site.register(Zo | naParte)
admin.site.register(ParteAspecto) |
google/makani | gs/monitor2/apps/plugins/layouts/debug_hover_layout.py | Python | apache-2.0 | 909 | 0.0033 | # Copyright 2020 Makani Technologies 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 agreed to... | e 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.
"""Layout to monitor hover status through full telemetry."""
from makani.gs.monitor2.apps.plug... | outs import hover_template
class DebugHoverLayout(hover_template.HoverLayout):
"""The hover layout."""
_NAME = 'Debug (Hover)'
_MODE = common.FULL_COMMS_MODE
|
diogocs1/comps | web/addons/hr_payroll/wizard/__init__.py | Python | apache-2.0 | 1,159 | 0.001726 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# This program is free software: you can redistribute it and/or modify
# it ... | OR 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/>.
#
########################################################################... | s
import hr_payroll_contribution_register_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
open-mmlab/mmdetection | configs/res2net/mask_rcnn_r2_101_fpn_2x_coco.py | Python | apache-2.0 | 287 | 0 | _base_ = '../mask_rcnn/mask_rcnn_r50_fpn_2x_coco.py'
model = dict(
backbone=dict(
type='Res2Net',
depth=101,
scales=4,
base_width=26,
init_cfg=dict(
type='Pretrained',
c | heckpoint='open-mmlab://res2net10 | 1_v1d_26w_4s')))
|
cawka/ns-3-dev-ndnSIM | src/lr-wpan/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 385,494 | 0.014791 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | ort_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class | ]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
#... |
medialab/reanalyse | reanalyseapp/update.py | Python | lgpl-3.0 | 11,321 | 0.02297 | # -*- coding: utf-8 -*-
#
# Import script for .csv files.
# Note: manifest a strong printaholism.
#
import sys, os, csv, re
from optparse import OptionParser
# get path of the django project
path = ("/").join( sys.path[0].split("/")[:-1] )
ppath = ("/").join( sys.path[0].split("/")[:-2] )
if path not in sys.pat... | Tag.DoesNotExist, e:
print " %s \"%s\": creating tag [%s:%s]" % ( texte.id, texte_name, article, Tag.ARTICLE )
| t = Tag( type=Tag.ARTICLE, slug=article, name=article)
t.save()
# save location geo
texte.locationgeo = locationgeo
texte.tags.add( t )
texte.date = date
texte.save()
#try
def install( upload_path, enquete_path ) :
from imexport import importEnqu... |
openstack/neutron-lib | neutron_lib/tests/unit/db/test_sqlalchemytypes.py | Python | apache-2.0 | 9,414 | 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... | ence[name] = ip
self._validate_ip_address(data_field_name='ip', expected=reference)
self._delete_rows()
self._validate_ip_address(data_field_name='ip', expected=None)
def test_multiple_create(self):
ip_addresses = [
{'name': 'fake_id1', 'ip': "10.0.0.5"},
{'... | 'ip': "2120::ffff:ffff:ffff:ffff"}]
self._test_multiple_create(ip_addresses)
class CIDRTestCase(SqlAlchemyTypesBaseTestCase):
def _get_test_table(self, meta):
return sa.Table(
'fakecidrmodels',
meta,
sa.Column('id', sa.String(36), primary_key=True, nullab... |
googleapis/python-recommender | google/cloud/recommender_v1/services/recommender/async_client.py | Python | apache-2.0 | 50,233 | 0.001553 | # -*- 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... | rgs, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments t | o pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
RecommenderAsyncClient: The constructed client.
"""
return RecommenderClient.from_service_account_file.__func__(RecommenderAsyncClient, filename, *args, **kwargs) # type: ignore... |
zhsso/ubunto-one | src/backends/db/__init__.py | Python | agpl-3.0 | 833 | 0 | # Copyright 2008-2015 Canonical
#
# 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 version.
#
# This program is distributed... | a copy of the GNU Affero General P | ublic License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check http://launchpad.net/filesync-server
"""Database schemas and tools for accessing and testing with the database."""
|
opesci/devito | devito/passes/iet/instrument.py | Python | mit | 2,261 | 0.000885 | from devito.ir.iet import MapNodes, Section, TimedList, Transformer
from devito.mpi.routines import (HaloUpdateCall, HaloWaitCall, MPICall, MPIList,
HaloUpdateList, HaloWaitList, RemainderCall)
from devito.passes.iet.engine import iet_pass
from devito.passes.iet.orchestration import Bus... | def track_subsections(iet, **kwargs):
"""
Add custom Sections to the `profiler`. Custom Sections include:
* MPI Calls (e.g., HaloUpdateCall and HaloUpda | teWait)
* Busy-waiting on While(lock) (e.g., from host-device orchestration)
"""
profiler = kwargs['profiler']
sregistry = kwargs['sregistry']
name_mapper = {
HaloUpdateCall: 'haloupdate',
HaloWaitCall: 'halowait',
RemainderCall: 'remainder',
HaloUpdateList: 'hal... |
ideascube/ideascube | ideascube/serveradmin/urls.py | Python | agpl-3.0 | 562 | 0 | from django.conf.urls import url
from . import views
app_name = 'server'
urlpatterns = [
url(r'^settings/$', views.server_info, name='settings'),
url(r'^power/$', views.power, name='power'),
url(r'^backup/$', views.backup, name='backup'),
url(r'^battery/$', views.battery, name='battery'),
url(r'^... | 'wifi'),
url(r'^wifi_history/$', views.wifi_history, nam | e='wifi_history'),
url(r'^home_page/$', views.home_page, name='home_page'),
url(r'^languages/$', views.languages, name='languages'),
]
|
ermanno-pirotta/playground | google-python-exercises/copyspecial/copyspecial.py | Python | lgpl-3.0 | 2,723 | 0.012119 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google | -python-class/
import sys
import re
import os
import shutil
import zipfile
"""Copy Special exercise
"""
""" The goal of this program is to copy all files that are contained in
the provided list of directories to anoth | er directory or zip them to a zip file"""
# +++your code here+++
# Write functions and modify main() to call them
# a special file is one with __w+__ pattern
def find_special_files(from_dirs):
special_files = []
for directory in from_dirs:
# skip non existing directories
if os.path.exists(dire... |
subodhchhabra/airflow | airflow/hooks/samba_hook.py | Python | apache-2.0 | 1,807 | 0 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS I | S" 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.
from smbclient import SambaClient
import os
from airflow.hooks.base_hook import BaseHook
class SambaHook(BaseHook):
"""
... |
opadron/girder | plugins/provenance/plugin_tests/provenance_test.py | Python | apache-2.0 | 17,716 | 0.000056 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013, 2014 Kitware 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... | _getProvenance(self, item, user, version=None, resource='item',
checkOk=True):
params = {}
if version is not None:
params = {'version': version}
resp = self.request(
path='/%s/%s/provenance' % (resource, item['_id']),
method='GET', user=... | etadata(self, item, meta, user):
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=user, body=json.dumps(meta),
type='application/json')
self.assertStatusOk(resp)
return self._getProvenance(item, user)
def ... |
jkossen/imposter | examples/frontend_fcgi.py | Python | bsd-2-clause | 149 | 0 | #!/usr/bin/env python
from flup.server.fcgi import WSGISe | rver
from frontend impo | rt app
WSGIServer(app, bindAddress=app.config['FCGI_SOCKET']).run()
|
Tanych/CodeTracking | 39-Combination-Sum/solution.py | Python | mit | 677 | 0.029542 | class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def recurhelper( | nums,res,path,target,start):
if target==0:
res.append(path)
return
if target<0:
return
if target>0:
for i in xrange(start,len(nums)):
if nums[i]<=target:
recurhelper(nums,res,p... |
return res |
mahmoud/womp | womp/stats.py | Python | gpl-3.0 | 2,081 | 0.001442 | def mean(vals):
if vals:
return sum(vals, 0.0) / len(vals)
else:
return 0.0
def trim(vals, trim=0.25):
if trim > 0.0:
trim = float(trim)
size = len(vals)
size_diff = int(size * trim)
vals = vals[size_diff:-size_diff]
return vals
def median(vals):
if ... | (copy[size / 2 - 1] + copy[size / 2]) / 2.0
def pow_diff(vals, power):
m = mean(vals)
return [(v - m) ** power f | or v in vals]
def variance(vals):
return mean(pow_diff(vals, 2))
def std_dev(vals):
return variance(vals) ** 0.5
def absolute_dev(vals, x):
return [abs(x - v) for v in vals]
def median_abs_dev(vals):
x = median(vals)
return median(absolute_dev(vals, x))
def rel_std_dev(vals):
val_mean ... |
wheeler-microfluidics/serial_device | serial_device/threaded.py | Python | gpl-3.0 | 9,719 | 0 | import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platfor... | .index)))
except NameError as exception:
self.error.exception = exception
self.error.set()
self.closed.set()
return
| while True:
# Wait for requested serial port to become available.
while self.comport not in (serial_device
.comports(only_available=True).index):
# Assume serial port was disconnected temporarily. Wait and
# periodical... |
alirizakeles/tendenci | tendenci/apps/invoices/reports.py | Python | gpl-3.0 | 2,731 | 0.002563 | from django.utils.translation import ugettext_lazy as _
from django.utils.html import mark_safe
from django.core.urlresolvers import reverse
from tendenci.libs.model_report.report import reports, ReportAdmin
from tendenci.libs.model_report.utils import (sum_column, us_date_format, date_label,
... | value)
class InvoiceReport(ReportAdmin):
# choose a title for your report for h1, title tag and report list
title = _('Invoice Report')
# specify your model
model = Invoice
# fields in the specified model to display in the report table
fields = [
'id',
'bill_ | to',
'create_dt',
'status_detail',
'object_type',
'entity',
'payments_credits',
'balance',
'total'
]
# fields in the model to show filters for
list_filter = ('status_detail', 'create_dt', 'object_type')
# fields in the model to order results by
... |
USGSDenverPychron/pychron | pychron/entry/mass_spec_reverter.py | Python | apache-2.0 | 8,096 | 0.001729 | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | ".format(
isol, i + 1, pt.Count | er
)
)
dest.delete(pt)
# delete isotope results
for i, ir in enumerate(iso.results[1:]):
self.debug(
"{} B {:02d} deleting results {}".format(
isol, i ... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/aaa/aaatacacsparams.py | Python | apache-2.0 | 8,097 | 0.037545 | #
# Copyright (c) 2008-2015 Citrix 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
try :
return self._auditfailedcmds
except | Exception as e:
raise e
@auditfailedcmds.setter
def auditfailedcmds(self, auditfailedcmds) :
ur"""The option for sending accounting messages to the TACACS+ server.<br/>Possible values = ON, OFF
"""
try :
self._auditfailedcmds = auditfailedcmds
except Exception as e:
raise e
@property
def defaulta... |
partofthething/home-assistant | homeassistant/components/aemet/abstract_aemet_sensor.py | Python | apache-2.0 | 1,752 | 0 | """Abstraction form AEMET OpenData sensors."""
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import ATTRIBUTION, SENSOR_DEVICE_CLASS, SENSOR_NAME, SENSOR_UNIT
from .weather_update_coordinator import WeatherUpdateCoordinator
class A... | S)
@propert | y
def name(self):
"""Return the name of the sensor."""
return f"{self._name} {self._sensor_name}"
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return self._unique_id
@property
def attribution(self):
"""Return the attribution."""
... |
tvieira/did | examples/mr.bob/hooks.py | Python | gpl-2.0 | 706 | 0 | #!/usr/bin/env python
# coding: utf-8
# Author: "Chris Ward" <cward@redhat.com>
'''
Mr.Bob Hooks
src: http://mrbob.readthedocs.org/en/latest/api.html#module-mrbob.hooks
'''
def pre_re | nder(configurator):
pass
def | post_render(configurator):
# remove unnecessary __init__.py, hooks.py
pass
def pre_ask_question(configurator, question):
pass
def post_ask_question(configurator, question, answer):
pass
def set_name_email(configurator, question, answer):
'''
prepare "Full Name" <email@eg.com>" string
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.