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 |
|---|---|---|---|---|---|---|---|---|
Byron/bit | src/python/bit/tests/test_bundler.py | Python | lgpl-3.0 | 5,905 | 0.007282 | #-*-coding:utf-8-*-
"""
@package bit.tests.test_bundler
@brief tests for bit.bundler
@author Sebastian Thiel
@copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html)
"""
__all__ = []
from bit.tests import ITTestCaseBase
from bit.bundler import *
import sys
import os
from sqlalchemy imp... | ur test database"""
engine = create_engine(cls.db_url())
mcon = engine.connect()
md = MetaData(engine, reflect=True)
for name, table in md.tables.iteritems():
yield mcon, name, table
# end for each item
def _disabled_test_update_fixture_(self):
"... | 00000
for mcon, name, table in self._table_iterator():
fixture_path = self.fixture_path(name)
print >> sys.stderr, "Obtaining %i from %s" % (rcount, self.db_url() + '/' + name)
db = list()
for r in mcon.execute(select([table], (table.c.ctime != None) & (... |
mvendra/mvtools | deprecated/encrypt_oldver_l19.py | Python | mit | 1,387 | 0.008652 | #!/usr/bin/env python
import sys
import os
import getpass
from subprocess import call
def puaq():
print("Usage: %s infile [outfile] [passphrase]" % os.path.basename(__file__))
sys.exit(1)
def symmetric_encrypt(infile, outfile, passphrase):
"""
symmetric_encrypt
parameters are all mandatory here... | print("%s does not exist. Aborting.")
sys.exit(1)
if outfile == "" or outfile == None:
print("Invalid output filename. Aborting")
sys.exit(1)
if passphrase == "" or passphrase == None:
print("Invalid passphrase. Aborting.")
sys.exit(1)
| call(["openssl", "des3", "-e", "-salt", "-in", infile, "-out", outfile, "-k", passphrase])
if __name__ == "__main__":
infile = ""
outfile = ""
passphrase = ""
if len(sys.argv) < 2:
puaq()
infile = sys.argv[1] # mandatory
if len(sys.argv) > 2:
outfile = sys.argv[2] # option... |
logarithm/photon-python | photon/listener.py | Python | apache-2.0 | 977 | 0.001024 | """
Copyright 2015 Logvinenko Maksim
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
U | nless 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 o | r implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import abc
class PeerListener:
def __init__(self):
pass
@abc.abstractmethod
def debug_return(self, debug_level, message):
pass
@abc.abstractmethod
def on_status_chan... |
hanamvu/C4E11 | SS3/square_tur.py | Python | gpl-3.0 | 285 | 0.045614 | from tu | rtle import *
speed(0)
shape("turtle")
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
for i in range(6):
# for j in range(1,3)
color(colors[i])
begin_fill()
for j in range(4):
if (j%2)==1:
forward(100)
else:
forward(50)
left(360/4)
end | _fill()
forward(50)
|
cread/ecks | ecks/plugins/memory.py | Python | apache-2.0 | 1,335 | 0.012734 | """
Ecks plugin to collect system memory usage information
Copyright 2011 Chris Read (chris.read@gmail.com)
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.... | total_real, avail_real, mem_buffer, mem_cached). Values are in kiloBytes
"""
memory = (1,3,6,1,4,1,2021,4) # UCD-SNMP-MIB
data = parent.get_snmp_data(host, community, memory, 1)
if data:
return map(parent._build_answer,
parent._extract(data, int, 3),
parent._extract(da... | )[0]
|
BDague/generic-image-server | genericImageServer/userLoginPages/apps.py | Python | mit | 103 | 0 | from django.apps import AppConfig
class User | loginpagesConfig(AppConfig):
| name = 'userLoginPages'
|
Lisaveta-K/lisaveta-k.github.io | _site/tomat/apps/checkout/migrations/0009_courier_cities.py | Python | mit | 15,694 | 0.008029 | # -*- 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 'CourierCity'
db.create_table(u'checkout_couriercity', (
(u'id', self.gf('django.... | ds.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'products' | : ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['products.Product']", 'through': u"orm['checkout.OrderItem']", 'symmetrical': 'False'}),
'products_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '8', 'decimal_places': '2'}),
'shop': ('dj... |
openaid-IATI/OIPA | OIPA/iati_synchroniser/humanitrian_global_clusters_import.py | Python | agpl-3.0 | 1,087 | 0 | import os
import os.path
import ujson
from iati_codelists.models import Sector, SectorVocabulary
class GlobalClustersSectorImporter():
"""
Wrapper class for all import methods used on the Country model
"""
def __init__(self):
"""
"""
def get_json_data(self, location_from_here):
... | _vocabulary = SectorVocabulary.objects.get(pk=10)
for sector in data:
Sector.objects.get_or_create(
code=sector.get('id'),
vocabulary=clusters_vocabulary,
defaults={
'name': sector.get('label'),
| 'description': '',
'category': None,
})
|
gkunter/coquery | coquery/textgrids.py | Python | gpl-3.0 | 16,629 | 0 | # -*- coding: utf-8 -*-
"""
textgrids.py is part of Coquery.
Copyright (c) 2016-2021 Gero Kunter (gero.kunter@coquery.org)
Coquery is released under the terms of the GNU General Public License ( | v3).
For details, see the file LICENSE that you should have received along
with Coqu | ery. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import unicode_literals
import collections
import os
import logging
import tgt
from . import options
from .links import get_by_hash
from .unicode import utf8
class TextgridWriter(object):
def __init__(self, df, session):
self.df = df... |
bokeh/bokeh | tests/unit/bokeh/embed/ext_package_no_main/__init__.py | Python | bsd-3-clause | 78 | 0 | # | Bokeh imports
from bokeh.model import Model
class AModel(Model):
pass | |
tadek-project/tadek-common | tests/core/location.py | Python | gpl-3.0 | 9,487 | 0.007273 | ################################################################################
## ##
## This file is a part of TADEK. ##
## ... | elf.failIf(True)
def testGet(sel | f):
location.add(_LOCATION_DIR)
self.failUnless(_LOCATION_DIR in location.get())
def testGetEnabled(self):
location.add(_LOCATION_DIR)
self.failUnless(_LOCATION_DIR in location.get(True))
def testGetDisabled(self):
location.add(_LOCATION_DIR, False)
self.failUnl... |
apache/allura | Allura/allura/model/notification.py | Python | apache-2.0 | 30,127 | 0.001162 | # 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 (t... | ct or ''
if post.parent_id and not subject.lower().startswith('re:'):
subject = 'Re: ' + subject
author = post.author()
msg_id = kwargs.get('message_id') or artifact.url() + post._id
parent_msg_id = artifact.url() + \
post.parent_id if post... | author._id) if author != User.anonymous() else None,
reply_to_address='"{}" <{}>'.format(
subject_prefix, getattr(
artifact, 'email_address', g.noreply)),
subject=subject_prefix + subject,
text=text,
in_reply_to=... |
Kitware/cumulus | cumulus/ansible/tasks/providers/__init__.py | Python | apache-2.0 | 884 | 0 | ###############################################################################
# Copyright 2016 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 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 und... | overning permissions and
# limitations under the License.
###############################################################################
from .base import CloudProvider, InstanceState
from .ec2 import EC2Provider
__all__ = ('CloudProvider', 'InstanceState', 'EC2Provider')
|
pavelkuchin/tracktrains | profiles/migrations/0002_auto_20150509_1528.py | Python | mit | 982 | 0.003055 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_i | nitial'),
]
operations = [
migrations.AddField(
model_name='tracktrainsuser',
name='tasks_limit',
field=models.PositiveSmallIntegerField(default=4, verbose_name=b"The user's limit of tasks."),
),
migrations.AlterField(
model_name='tracktr | ainsuser',
name='inviter',
field=models.ForeignKey(verbose_name=b'The person who invited this user.', blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
migrations.AlterField(
model_name='tracktrainsuser',
name='invites_counter',
field=mod... |
jhertzog/pi | email/imap_delete.py | Python | mit | 1,097 | 0.000912 | import imaplib
import email
# you want to connect to a server; specify which server
server = imaplib.IMAP4('imap.*.com')
# after connecting, tell the server who you | are
server.login('*', '*')
# this will show you a list of available folders
# possibly your Inbox is called INBOX, but check the list of mailboxes
| code, mailboxen = server.list()
print mailboxen
#
server.select("INBOX")
email_list = [""]
for e in email_list:
print("Searching emails from %s" % e)
result_status, email_ids = server.search(None, '(FROM "%s")' % e)
email_ids = email_ids[0].split()
if len(email_ids) == 0:
print("No emails fo... |
gtaylor/btmux_battlesnake | battlesnake/plugins/contrib/arena_master/db_api.py | Python | bsd-3-clause | 11,199 | 0.000446 | """
The API for interacting with arena-related data in the DB.
"""
import datetime
from psycopg2.extras import Json
from twisted.internet.defer import inlineCallbacks, returnValue
from battlesnake.outbound_commands.think_fn_wrappers import btunitpartslist, \
btunitpartslist_ref
from battlesnake.plugins.contrib.ar... | print "Unable to find victim: wave %d, victim %s" % (wave_id, victim_dbref)
returnValue(None)
killer_id = yield get_participant_id_from_db(wave_id, killer_dbref)
if not killer_id:
print "Unable to find kill | er: w |
jabhij/MITx-6.00.1x-Python- | Week-3/L5/Prob3.py | Python | mit | 268 | 0.003731 | # | Declaring a Function
def recurPowerNew(base, exp):
# Base case is when exp = 0
if exp <= 0:
return 1
# Recursive Call
elif exp % 2 == 0:
return recurPowerNew(base*base, exp/2)
return base * recurPowerNew(base, exp - 1) | |
MozillaSecurity/FuzzManager | server/crashmanager/management/commands/cleanup_old_crashes.py | Python | mpl-2.0 | 3,783 | 0.006609 | from datetime import timedelta
from django.conf import settings
from django.core.management import BaseCommand, CommandError # noqa
from django.db.models.aggregates import Count
from django.utils import timezone
from crashmanager.models import CrashEntry, Bucket, Bug
class Command(BaseCommand):
help = "Cleanup... | ects.filter(pk__in=pks).delete()
bug.delete()
# Select all buckets that are empty and delete them
Bucket.objects.annotate(size=Count('crashentry')).filter(size=0, bug=None, permanent=False).delete()
# Select all entries that are older than x days and either not in any bucket
... | # or the bucket has no bug associated with it. If the bucket has a bug associated
# then we would want to keep entries around until the bug is fixed (they will be
# deleted when the bucket is deleted).
#
# Again, for the same reason as mentioned above, we have to delete entries in batch... |
cuhsat/tinythread | tinythread_test.py | Python | mit | 2,255 | 0 | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Christian Uhsat <christian@uhsat.de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limi... | gth):
"""
Returns a random printable string with the given | length.
"""
return "".join([random.choice(string.printable) for i in range(length)])
class TestTinyThread:
"""
TinyThread unit tests.
"""
def test_post(self):
"""
Simple fuzzy post test.
"""
thread = TinyThread(fuzzy_generator(16))
messages = [fuzzy_ge... |
theislab/scvelo | scvelo/tools/paga.py | Python | bsd-3-clause | 11,529 | 0.002255 | import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from scanpy.tools._paga import PAGA
# This is adapted from https://github.com/theislab/paga
from scvelo import logging as logg
from scvelo import settings
from .rank_velocity_genes import velocity_clusters
from .utils import strings_to_categor... | _spanning_tree=True,
copy=False,
):
"""PAGA graph with velocity-directed edges.
Mapping out the coarse-grained connectivity structures of complex manifolds
[Wolf19]_. By quantifying the connectivity | of partitions (groups, clusters) of the
single-cell graph, partition-based graph abstraction (PAGA) generates a much
simpler abstracted graph (*PAGA graph*) of partitions, in which edge weights
represent confidence in the presence of connections.
Parameters
----------
adata : :class:`~anndata.A... |
udragon/ldc | ldc/test/test_ldcdns.py | Python | gpl-2.0 | 502 | 0.013944 | #!/usr/bin/python
import unittest
import ldc
import uuid
class TestLDCDNSInterface(unittest.TestCase):
def test_ldcdns(self):
rand_str = str(uuid.uuid4())
ldc.dn | s.add(rand_str, '1.1.1.1')
assert ldc.dns.resolve(rand_str) == [ '1.1.1.1' ]
ldc.dns.replace_all(rand_str,'2.2.2.2')
assert ldc.dns.resolve(rand_str) == [ '2.2.2.2' ]
ldc.dns.delete(rand_str)
assert ldc.dns.resolve(rand_str) == []
if __n | ame__ == '__main__':
unittest.main()
|
Rusk85/pyload | module/plugins/accounts/UlozTo.py | Python | gpl-3.0 | 1,341 | 0.002983 | # -*- coding: utf-8 -*-
import re
from module.plugins.Account import Account
class UlozTo(Account):
__name__ = "UlozTo"
__version__ = "0.04"
__type__ = "account"
__description__ = """uloz.to account plugin"""
__author_name__ = ("zoidberg")
__author_mail__ = ("zoidberg@mujmail.cz")
TRAFF... |
def loadAccountInfo(self, user, req):
#this cookie gets lost somehow after each request
self.phpsessid = req.cj.getCookie("ULOSESSID")
html = req.load("http://www.ulozto.net/", decode=True)
req.cj.setCookie("www.ulozto.net", "ULOSESSID", self.phpsessid)
found = re.search(s... | trafficleft = int(float(found.group(1).replace(' ', '').replace(',', '.')) * 1000 / 1.024) if found else 0
self.premium = True if trafficleft else False
return {"validuntil": -1, "trafficleft": trafficleft}
def login(self, user, data, req):
html = req.load('http://www.ulozto.net/login?do=... |
romanz/electrum | lib/storage.py | Python | mit | 22,431 | 0.002229 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without... | ept:
return STO_EV_PLAINTEXT
def file_exists(self):
return self.path and os.path.exists(self.path)
def get_key(self, password):
secret = pbkdf2.PBKDF2(password, '', iterations = 1024, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
ec_key = bitcoin.EC_KEY(secret)
... | STO_EV_XPUB_PW:
return b'BIE2'
else:
raise Exception('no encryption magic for version: %s' % v)
def decrypt(self, password):
ec_key = self.get_key(password)
if self.raw:
enc_magic = self._get_encryption_magic()
s = zlib.decompress(ec_key.decr... |
ResearchSoftwareInstitute/MyHPOM | hs_core/migrations/0019_baseresource_locked_time.py | Python | bsd-3-clause | 410 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hs_core', '0018_ | merge'),
]
operations = | [
migrations.AddField(
model_name='baseresource',
name='locked_time',
field=models.DateTimeField(null=True, blank=True),
),
]
|
langdev/rosetta | app.py | Python | agpl-3.0 | 102 | 0 | #!/usr/bin/ | env python
from rosetta.web import app
if __name__ == "__main__":
app.run(debug | =True)
|
eren/sozlukcrawler | sozlukcrawl/spiders/itusozluk.py | Python | gpl-2.0 | 2,234 | 0.003133 | # -*- coding: utf-8 -*-
__author__ = 'Eren Turkay <turkay.eren@gmail.com>'
from scrapy import log
from scrapy.http import Request
from scrapy.exceptions import CloseSpider
from datetime import datetime
from . import GenericSozl | ukSpider
from ..items import Girdi
class ItusozlukBaslikSpider(GenericSozlukSpider):
name = 'itusozluk'
def __init__(self, **kwargs):
super(ItusozlukBaslikSpider, self).__init__(**kwargs)
self.allowed_domains = ['itusozluk.com']
def pars | e(self, response):
self.log("PARSING: %s" % response.request.url, level=log.INFO)
items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article')
if len(items_to_scrape) == 0:
self.log("!!! No item to parse found. It may indicate a problem with HTML !!!",
l... |
Wallace-dyfq/example-code | 21-class-metaprog/bulkfood/model_v8.py | Python | mit | 2,113 | 0.000473 | import abc
import collections
class AutoStorage:
__counter = 0
def __init__(self):
cls = self.__class__
prefix = cls.__name__
index = cls.__counter
self.storage_name | = '_{}#{}'.format(prefix, index)
cls.__counter += 1
def __get__(self, instance, owner):
if instance is None:
return self
else:
return getattr(instance, self.storage_name)
def __set__(self, instance, value):
setattr(instance, self.storage_name, value)
... | = self.validate(instance, value)
super().__set__(instance, value)
@abc.abstractmethod
def validate(self, instance, value):
"""return validated value or raise ValueError"""
class Quantity(Validated):
"""a number greater than zero"""
def validate(self, instance, value):
if val... |
darkforestzero/buck | programs/buck_repo.py | Python | apache-2.0 | 17,040 | 0.001761 | from __future__ import print_function
import glob
import os
import platform
import subprocess
import sys
import tempfile
import textwrap
from timing import monotonic_time_nanos
from tracing import Tracing
from buck_tool import BuckTool, check_output, JAVA_MAX_HEAP_SIZE_MB
from buck_tool import BuckToolException, Resta... | asses",
"build/aosp/classes",
"build/dx_classes",
"src",
"src-gen",
"third-party/java/android/sdklib-25.2.0.jar",
"th | ird-party/java/android/sdk-common-25.2.0.jar",
"third-party/java/android/common-25.2.0.jar",
"third-party/java/android/layoutlib-api-25.2.0.jar",
"third-party/java/aopalliance/aopalliance.jar",
"third-party/java/args4j/args4j-2.0.30.jar",
"third-party/java/asm/asm-debug-all-5.0.3.jar",
"third-pa... |
nyaruka/smartmin | smartmin/csv_imports/migrations/0005_alter_importtask_created_by_and_more.py | Python | bsd-3-clause | 1,026 | 0.001949 | # Generated by Django 4.0.1 on 2022-01-12 15:47
from dj | ango.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_ | USER_MODEL),
('csv_imports', '0004_auto_20170223_0917'),
]
operations = [
migrations.AlterField(
model_name='importtask',
name='created_by',
field=models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.P... |
fritzo/loom | examples/lending_club/test.py | Python | bsd-3-clause | 1,619 | 0 | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
# Copyright (c) 2015, Google, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modifi | cation, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the... | r the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT ... |
jonfoster/pyxb1 | examples/geocoder/client.py | Python | apache-2.0 | 2,378 | 0.003785 | import GeoCoder
from pyxb import BIND
import sys
import pyxb.utils.domutils as domutils
import pyxb.bundles.wssplat.soap11 as soapenv
import pyxb.bundles.wssplat.soapenc as soapenc
import urllib2
address = '1600 Pennsylvania Ave., Washington, DC'
if 1 < len(sys.argv):
address = sys.argv[1]
env = soapenv.Envelope(... | essage/5879. In
# short, the WSDL spec shows an example using soapenc:Array where a
# restriction was used to set the value of the wsdl:arrayType
# attribute. This restriction failed to d | uplicate the element content
# of the base type, resulting in a content type of empty in the
# restricted type. Consequently, PyXB can't get the information out
# of the DOM node, and we have to skip over the wildcard items to find
# something we can deal with.
# As further evidence the folks who designed SOAP 1.1 di... |
devDesu/scripts | markov/parse.py | Python | gpl-2.0 | 1,210 | 0.004139 | # -*- coding: utf-8 -*-
__author__ = 'Anton'
import re
from storage import Storage
class Parser:
def __init__(self, store, sentence_split=['.', '!', '?', '...', '\n'], word_split=[' ', ',', ': | ', '—']):
self.sentences = []
self.storage = store
self.word_split = word_split
temp = '['+''.join(['\{}'.format(i) for i | in sentence_split])+']'
print(temp)
self.sentence_split = re.compile(temp, flags=re.MULTILINE+re.UNICODE)
temp = '['+''.join(['\{}'.format(i) for i in word_split])+']'
print(temp)
self.word_split = re.compile(temp, flags=re.UNICODE)
def split_sentences(self, text):
... |
droark/Misc-Blockchain-Parse-Tools | Find-Unusual-Scripts.py | Python | mit | 33,452 | 0.004066 | # (c) 2016 Douglas Roark
# Licensed under the MIT License. See LICENSE for the details.
from __future__ import print_function, division # Valid as of 2.6
import sys
sys.path.insert(0, '/home/droark/Projects/etotheipi-BitcoinArmory')
import binascii, hashlib, string, os
from collections import namedtuple
from math impo... | tion output item and gets the
# pieces. The transaction output includes, in the following order:
# 1)The amount sent in the transaction. (8 bytes - LE)
# 2)Transaction output's script length. (VAR_INT - LE)
# 3)Transaction output's script. (VAR_LEN - BE)
# Input: A BinaryUnpacker object with the transaction input.
#... | utput's individual objects and the TxOut binary string.
def getTxOut(txUnpack):
'''Function that unpacks the items inside a transaction output.'''
txStartPos = txUnpack.getPosition()
# Get the individual Tx pieces.
txOutVal = txUnpack.get(UINT64)
txOutScrLen = txUnpack.get(VAR_INT)
txOutScr = t... |
magenta/magenta | magenta/models/drums_rnn/drums_rnn_create_dataset.py | Python | apache-2.0 | 2,181 | 0.004585 | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | rFlow's SequenceExample protos for input to the drums RNN models.
"""
import os
from magenta.models.drums_rnn import drums_rnn_config_flags
from magenta.models.drums_rnn import drums_rnn_pipeline
from magenta.pipelines import pipeline
import tensorflow.compat.v1 as tf
flags = tf.app.flags
FLAGS = tf.app.flags.FLAGS
... | to read NoteSequence protos from.')
flags.DEFINE_string(
'output_dir', None,
'Directory to write training and eval TFRecord files. The TFRecord files '
'are populated with SequenceExample protos.')
flags.DEFINE_float(
'eval_ratio', 0.1,
'Fraction of input to set aside for eval set. Partition is rand... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/classytags/compat.py | Python | agpl-3.0 | 248 | 0 | # - | *- coding: utf-8 -*-
try: # pragma: no cover
compat_basestring = basestring
except NameError:
compat_basestring = str
try:
compat_next | = next
except NameError: # pragma: no cover
def compat_next(it):
return it.next()
|
anotherjesse/nova | nova/auth/manager.py | Python | apache-2.0 | 28,865 | 0.000728 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | return AuthManager().add_role(self, role)
def remove_role(self, role):
return AuthManager().remove_role(self, role)
def is_project_member(self, project):
return AuthManager().is_project_member(self, project)
def is | _project_manager(self, project):
return AuthManager().is_project_manager(self, project)
def __repr__(self):
return "User('%s', '%s', '%s', '%s', %s)" % (self.id,
self.name,
self.access,
... |
p3trus/slave | slave/quantum_design/__init__.py | Python | gpl-3.0 | 43 | 0 | fro | m slave.quantum_design.ppms import PPMS | |
yyxt11/CaptchaProject | KNNDetector/console.py | Python | gpl-3.0 | 1,556 | 0.023779 | #coding:utf-8
from KNNDetector.KNN_Detect import *
import requests
from PIL import Image
import base64
import getpass
def login(username,passwd):
session=requests.session()
session.get('http://wsxk.hust.edu.cn/login.jsp').text
img=session.get('http://wsxk.hust.edu.cn/randomImage.action').conten... | pen('captcha.jpeg')
result=imageRecognize.recognise(image)
string=''
for item in result:
string+=item[1]
print(string)
| data={
'usertype':"xs",
'username':username,
'password':passwd,
'rand':string,
'sm1':"",
'ln':"app610.dc.hust.edu.cn"
}
headers = {
'Host':"wsxk.hust.edu.cn",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding"... |
JoyTeam/metagam | mg/constructor/stats.py | Python | gpl-3.0 | 13,373 | 0.002916 | #!/usr/bin/python2.6
# This file is a part of Metagam project.
#
# Metagam 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
# any later version.
#
# Metagam is distributed ... | # this character first appeared in the logs on the next day with "login" event.
# it means he was offline yesterday
character_players[char_uuid] = player_uuid
if act == "logout" or act == "disconnect":
# this chara... | # it means he was online yesterday all the day
character_players[char_uuid] = player_uuid
player_stat(player_uuid, since, till, "afterlog")
# getting characters online till the end of the day
for player_uuid, ent in |
pbelmann/command-line-interface | biobox_cli/command/login.py | Python | mit | 2,319 | 0.0069 | """
biobox login - Log in to a biobox container with mounted test data
Usage:
biobox login <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-r, --no-rm Don't remove the container after the process finishes
-t, --no-tty Don't start a terminal emulator, used for scripted intera... | util.parse_docopt(__doc__, argv, True)
image = opts["<image>"]
biobox_t | ype = opts["<biobox_type>"]
tty = not "--no-tty" in opts["<args>"]
remove = not "--no-rm" in opts["<args>"]
docker.exit_if_no_image_available(image)
params = get_login_parameters(biobox_type)
if params is None:
error.err_exit("unknown_command",
{"command_type"... |
Sispheor/piclodio3 | back/tests/test_views/test_web_radio_views/test_get_details.py | Python | mit | 785 | 0.003822 | from rest_fram | ework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from restapi.models.web_radio import WebRadio
class TestGetDetails(APITestCase):
def setUp(self):
super(TestGetDetails, self).setU | p()
self.webradio = WebRadio.objects.create(name="test", url="http://test.com")
self.url = reverse('api:webradios:retrieve_update_destroy', args=[self.webradio.id])
def test_get_details(self):
response = self.client.get(self.url, format='json')
expected_response = {'id': self.webrad... |
jaredjennings/shaney | shaney/generators/autoindex.py | Python | gpl-3.0 | 3,828 | 0.006531 | # shaney - prepare Puppet code with LaTeX comments for multiple audiences.
# Based on <https://github.com/afseo/cmits>.
# Copyright (C) 2015 Jared Jennings, jjennings@fastmail.fm.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published... | _match(r"define[\s]*([^\s(]+)")
def define_definition(m, value, target):
d = m[0]
ta | rget.send( ('index_entry', 'define', d, 'defined') )
target.send( ('label', 'define_' + d) )
target.send(value)
# A line with "something::anotherthing[::morethings] {" is a defined
# resource type use. This will not catch defines which don't have '::'
# in their names; but it will also not catch built-in reso... |
davidt/reviewboard | reviewboard/scmtools/tests/test_svn.py | Python | mit | 20,340 | 0 | # coding=utf-8
from __future__ import unicode_literals
import os
from hashlib import md5
import nose
from django.conf import settings
from kgb import SpyAgency
from reviewboard.diffviewer.diffutils import patch
from reviewboard.scmtools.core import (Branch, Commit, Revision, HEAD,
... | 'dependency may be missing.'
% self.backend)
assert self.tool.client.__class__.__module__ == self.backend
def tearDown(self):
super(CommonSVNTestCase, self).tearDown()
settings.SVNTOOL_BACKENDS = self._old_backend_setting
| recompute_svn_backend()
def shortDescription(self):
desc = super(CommonSVNTestCase, self).shortDescription()
desc = desc.replace('<backend>', self.backend_name)
return desc
def test_ssh(self):
"""Testing SVN (<backend>) with a SSH-backed Subversion repository"""
s... |
ActiveState/code | recipes/Python/440498_Win32com__Batch_repathing_Autocad/recipe-440498.py | Python | mit | 3,367 | 0.009504 | # Relative-refs.pyw
"""A short python script for repathing xrefs in Autocad."""
import win32com.client,os, os.path, tkFileDialog
from Tkinter import *
from tkMessageBox import askokcancel
from time import sleep
# Get a COM object for Autocad
acad = win32com.client.Dispatch("AutoCAD.Application")
def repath(filename)... | out and st | derr to normal."""
self.logfile.close()
sys.stderr = sys.__stderr__
sys.stdout = sys.__stdout__
class Tktextfile:
"""A file like interface to the Tk text widget."""
def __init__(self, root):
"""Create a scrollable text widget to be written to."""
self.root = root
... |
dleehr/cwltool | tests/test_dependencies.py | Python | apache-2.0 | 1,496 | 0.007353 | import pytest
import pytest
from cwltool.utils import onWindows
from .util import get_data, get_main_output, needs_docker
try:
from galaxy.tools import deps
except ImportError:
deps = None
@needs_docker
@pytest.mark.skipif(not deps | , reason="galaxy-lib is not installed")
def test_biocontainers():
wflow = get_data("tests/seqtk_seq.cwl")
job = get_data("tests/seqtk_seq_job.json")
error_code, _, _ = get_main_output(
["--beta-use-biocontainers", wflow, job])
assert error_code == 0
@pytest.mark.skipif(onWindows(), reason="bio... | )
def test_bioconda():
wflow = get_data("tests/seqtk_seq.cwl")
job = get_data("tests/seqtk_seq_job.json")
error_code, _, stderr = get_main_output(
["--beta-conda-dependencies", "--debug", wflow, job])
assert error_code == 0, stderr
import os
from distutils import spawn
@pytest.mark.skipif(not ... |
ameily/pubfs | pubfs/core/models.py | Python | bsd-2-clause | 225 | 0.013333 |
import mongoengine as db |
class BaseObject(db.Document):
meta = {'allow_inheritance': True}
name = db.StringField(required=True)
tags = db.ListField(db.StringField())
revision = db.IntFie | ld(default=1)
|
flavoi/diventi | diventi/accounts/migrations/0051_auto_20190423_0803.py | Python | apache-2.0 | 452 | 0 | # Generated by Django 2.1.7 on 2019-04-23 06:03
import diventi.accounts.models
from django.db import migra | tions
class Migration(migrations.Migration):
dependencies = [
('accounts', '0050_auto_20190421_2252'),
]
operations = [
migrations.AlterModelManagers(
name='diventiuser',
managers=[
('objects', diventi.accounts.models.DiventiUserManager()),
... |
]
|
metapolator/mutatormathtools | python_modules/lib/python/defcon/objects/contour.py | Python | apache-2.0 | 33,443 | 0.002213 | import weakref
from warnings import warn
from fontTools.misc import bezierTools
from defcon.objects.base import BaseObject
from defcon.tools import bezierMath
from defcon.tools.representations import contourBoundsRepresentationFactory,\
contourControlPointBoundsRepresentationFactory, contourClockwiseRepresentationF... | dentifiers within
the glyph.
This will post *Contour.PointsChanged* and *Contour.Changed* notifications.
"""
assert point not in self._points
if point.identifier is not None:
identifiers = self.identifiers
| assert point.identifier not in identifiers
if point.identifier is not None:
identifiers.add(point.identifier)
self._points.insert(index, point)
self.postNotification("Contour.PointsChanged")
self.dirty = True
def removePoint(self, point):
"""
... |
owlabs/incubator-airflow | tests/contrib/operators/test_redis_publish_operator.py | Python | apache-2.0 | 2,312 | 0.000865 | # -*- 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
#... | operator = RedisPublishOperator(
task_id='test_task',
dag=self.dag,
message='hello',
channel=self.channel,
redis_conn_id='redis_default'
)
hook = RedisHo | ok(redis_conn_id='redis_default')
pubsub = hook.get_conn().pubsub()
pubsub.subscribe(self.channel)
operator.execute(self.mock_context)
context_calls = []
self.assertTrue(self.mock_context['ti'].method_calls == context_calls, "context calls should be same")
message = pub... |
noahfx/lobster | lobster/__main__.py | Python | mit | 3,384 | 0.004137 | #!/usr/bin/env python
import sys
import argparse
from .audio import create_tracks
from .downloader import YouTube
from .parser import parse_tracks_file
from .prompt import wizard
from .exceptions import WizardError
def get_from_youtube(source):
yt = YouTube(source)
highest_bitrate = yt.audio_available.get('... | age = 'Launch Lobster in Wizard or Command mode,`wizard`'\
' will launch the Wizard mode, `cmd` will lauch' \
' Command mode, `cmd` is the current default '
parser.add_argument('--mode', '-m', type=str,
help=mode_help_mesage,
... | se_args())
mode = kwargs.get('mode').lower()
if mode == 'cmd':
required_fields = ["artist", "album", "tracks", "source", "input",
"output"]
should_generate = True
for req_field in required_fields:
if kwargs.get(req_field) is None:
sh... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scattercarpet/_uirevision.py | Python | mit | 408 | 0.002451 | import _plotly_utils. | basevalidators
class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="scattercarpet", **kwargs):
super(UirevisionValidator, self).__init__(
| plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
fomichev/pycryptobox | lib/preprocessor.py | Python | bsd-3-clause | 794 | 0.003778 | """ |
Custom c-style-like preprocessor
"""
import os
from cStringIO import StringIO
import re
from extern.Preprocessor import Preprocessor
def pp(filename, defines = {}, remove_lf=True, fatal=False):
"""
Preprocess given file using provided defines
"""
p = Preprocessor()
p.context.update(defines)
... | ubstitution')
if fatal:
p.do_filter('substitution')
else:
p.do_filter('attemptSubstitution')
if type(filename) == list:
for f in filename:
p.do_include(f)
else:
p.do_include(filename)
if remove_lf:
return os.linesep.join([s for s in p.out.getvalu... |
DiogoGoes/TCC | AssociationRule.py | Python | gpl-3.0 | 1,429 | 0.043387 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 6 22:58:00 2016
@author: Diogo
"""
# -*- coding: utf-8 -*-
"""
Cr | eated on Sun Jun 26 19:08:00 2016
@author: Diogo
"""
def ImportGames():
games = list()
user_games = dict()
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesCleansed.txt', 'r', encoding = 'utf-8') as lines:
next(lines) # Skiping headers
for ln in lines:
user, board_game, bo... | oard_game not in games:
games.append(board_game.replace('\t',' ').replace(' ', ' '))
if user not in user_games:
user_games[user] = dict()
if board_game not in user_games[user].keys():
user_games[user][board_game] = 1
return (games, user_games)
games, user_games = ImportGames()... |
lnielsen/invenio | invenio/ext/fixtures/registry.py | Python | gpl-2.0 | 1,433 | 0.00977 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | re datasets."""
from flask.ext.registry import RegistryProxy
from invenio.ext.registry import ModuleAutoDiscoveryRegistry
from invenio.utils.datastructures import LazyDict
fixtures_proxy = RegistryProxy(
'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures')
def fi | xtures_loader():
"""Load fixtures datasets."""
out = {}
for fixture in fixtures_proxy:
for data in getattr(fixture, '__all__', dir(fixture)):
if data[-4:] != 'Data' or data in out:
continue
out[data] = getattr(fixture, data)
return out
fixtures = LazyDict... |
ky822/scikit-learn | sklearn/linear_model/coordinate_descent.py | Python | bsd-3-clause | 75,144 | 0.000253 | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
# Gael Varoquaux <gael.varoquaux@inria.fr>
#
# License: BSD 3 clause
import sys
import warnings
from abc import ABCMeta, abstractmethod
import n... | ##
# Paths functions
def _al | pha_grid(X, y, Xy=None, l1_ratio=1.0, fit_intercept=True,
eps=1e-3, n_alphas=100, normalize=False, copy_X=True):
""" Compute the grid of alpha values for elastic net parameter search
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training da... |
DemocracyClub/EveryElection | every_election/apps/elections/migrations/0050_auto_20181005_1425.py | Python | bsd-3-clause | 512 | 0.001953 | # -*- coding: utf-8 -*-
# Gene | rated by Django 1.11.16 on 2018-10-05 14:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("elections", "0049_move_status")]
operations = [
migrations.RemoveField(model_name="election", name="rejection_reason"),
... | "),
]
|
TaliesinSkye/evennia | wintersoasis-master/web/character/urls.py | Python | bsd-3-clause | 308 | 0.006494 | from dj | ango.conf.urls import patterns, url
from character import views
urlpatterns = patterns('',
url(r'^profile/(?P<username>[^/]+)/$', views.profile, name="profile"),
url(r'^switch/', views.switch, name="switch"),
url(r'^autocomplete/user | ', views.character_lookup, name="character_lookup"),
)
|
znuxor/aoc2016 | 3b.py | Python | bsd-3-clause | 23,837 | 0.000042 | #!/usr/bin/env python3
theInput = """785 516 744
272 511 358
801 791 693
572 150 74
644 534 138
191 396 196
860 92 399
233 321 823
720 333 570
308 427 572
246 206 66
156 261 595
336 810 505
810 210 938
615 987 820
117 22 519
412 990 256
405 996 423
55 366 418
290 402 810
31... |
393 359 157
714 442 999
851 425 954
487 545 408
504 759 191
509 179 626
774 859 455
335 476 523
573 622 288
518 561 504
812 100 602
433 455 676
565 453 112
282 266 523
642 508 440
558 512 102
109 685 128
291 903 221
254 370 275
300 398 431
341 809 383
622 948 79
813 | 961 308
972 451 601
390 877 719
988 448 275
184 229 542
902 307 761
587 575 909
442 648 331
424 98 620
512 106 578
411 219 614
577 294 104
81 916 468
84 842 287
96 261 678
34 323 226
943 321 29
906 619 258
924 503 215
929 149 431
56 505 511
876 769 999
994 714 980
416... |
mountainpenguin/BySH | server/lib/tornado/netutil.py | Python | gpl-3.0 | 15,081 | 0.000663 | #!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# 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 a... | `). An alternative implementation can be
chosen with the `Resolver.configure <.Configurable.configure>`
class method::
Resolver.configure('tornado.netutil.ThreadedResolver')
The implementations of this interface includ | ed with Tornado are
* `tornado.netutil.BlockingResolver`
* `tornado.netutil.ThreadedResolver`
* `tornado.netutil.OverrideResolver`
* `tornado.platform.twisted.TwistedResolver`
* `tornado.platform.caresresolver.CaresResolver`
"""
@classmethod
def configurable_base(cls):
return Re... |
APMonitor/arduino | 0_Test_Device/Python/tclab/tclab.py | Python | apache-2.0 | 4,881 | 0.013112 | import sys
import time
import numpy as np
try:
import serial
except:
import pip
pip.main(['install','pyserial'])
import serial
from serial.tools import list_ports
class TCLab(object):
def __init__(self, port=None, baud=9600):
| port = self.findPort()
prin | t('Opening connection')
self.sp = serial.Serial(port=port, baudrate=baud, timeout=2)
self.sp.flushInput()
self.sp.flushOutput()
time.sleep(3)
print('TCLab connected via Arduino on port ' + port)
def findPort(self):
found = False
for port in l... |
twschiller/open-synthesis | openach/views/util.py | Python | gpl-3.0 | 1,719 | 0.000582 | from django.conf import settings
from django.contrib import messages
from django.core.exceptions import P | ermissionDenied
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext as _
def remove_and_redirect(request, removable, message_detail):
"""Mark a model as removed and | redirect the user to the associated board detail page."""
if getattr(settings, "EDIT_REMOVE_ENABLED", True):
removable.removed = True
removable.save()
class_name = (
removable._meta.verbose_name.title()
) # pylint: disable=protected-access
class_ = class_name[:1]... |
nrb/rpc-openstack | maas/testing/fake_hp_monitoring.py | Python | apache-2.0 | 940 | 0.001064 | #!/usr/bin/env python
# Copyright 2015, Rackspace US, 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... | 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
# l | imitations under the License.
import sys
args = sys.argv[1:]
if args == ['-s', 'show server']:
print 'Status Ok'
elif args == ['-s', 'show dimm']:
print 'Status Ok'
elif args == ['ctrl', 'all', 'show', 'config']:
print 'logicaldrive OK)'
else:
sys.exit('fake_hp_monitoring.py has received the followin... |
jmestrovic/finrep | web/gfi/migrations/0003_auto_20180226_1418.py | Python | gpl-2.0 | 2,921 | 0.002396 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-02-26 13:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gfi', '0002_auto_20180223_1523'),
]
... | eld(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Indicator | Types',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mark', models.CharField(max_length=10)),
('name', models.CharField(max_length=250)),
('description', models.TextField(bla... |
timlinux/geonode | tasks.py | Python | gpl-3.0 | 6,112 | 0.000164 | import json
import logging
import os
import re
import docker
from invoke import run, task
BOOTSTRAP_IMAGE_CHEIP = 'codenvy/che-ip:nightly'
@task
def waitfordbs(ctx):
print "**************************databases*******************************"
ctx.run("/usr/bin/wait-for-databases {0}".format('db'), pty=True)
... | _public_host_ip()
print "Public Hostname or IP is {0}".format(pub_ip)
pub_port = _geonode_public_port | ()
print "Public PORT is {0}".format(pub_port)
default_fixture = [
{
"model": "oauth2_provider.application",
"pk": 1001,
"fields": {
"skip_authorization": True,
"redirect_uris": "http://{0}:{1}/geoserver/index.html".format(
... |
JrGoodle/clowder | clowder/cli/diff.py | Python | mit | 1,529 | 0.003924 | """Clowder command line diff controller
.. codeauthor:: Joe DeCapo <joe@polka.cat>
"""
import argparse
import clowder.util.formatting as fmt
from clowder.clowder_controller import CLOWDER_CONTROLLER, print_clowder_name, valid_clowder_yaml_required
from clowder.config import Config
from clowder.git.clowder_repo impo... | bparsers: Subparsers action to add parser to
"""
parser = subparsers.add_parser('diff', help='Show git diff for projects')
parser.formatter_class = argparse.RawTextHelpFormatter
parser.set_defaults(func=diff)
add_parser_arguments(parser, [
(['projects'], dict( | metavar='<project|group>', default='default', nargs='*',
choices=CLOWDER_CONTROLLER.project_choices_with_default,
help=fmt.project_options_help_message('projects and groups to show diff for'))),
])
@valid_clowder_yaml_required
@print_clowder_name
@print_clow... |
intelligent-agent/redeem | redeem/Alarm.py | Python | gpl-3.0 | 6,796 | 0.015009 | #!/usr/bin/env python
"""
An alarm can be executed when an error condition occurs
Author: Elias Bakken
Redeem 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 opti... | self.inform_listeners()
Alarm.action_command("pause")
Alarm.action_command("alarm_heater_rising_fast", self.message)
elif self.type == Alarm.HEATER_FALLING_FAST:
self.disable_heaters()
self.inform_listeners()
Alarm.action_command("pause")
Alarm.action_command("alarm_heater_falli... | :
self.inform_listeners()
Alarm.action_command("pause")
Alarm.action_command("alarm_stepper_fault", self.message)
elif self.type == Alarm.FILAMENT_JAM:
Alarm.action_command("pause")
Alarm.action_command("alarm_filament_jam", self.message)
elif self.type == Alarm.PHYSICAL_ENDSTOP_HI... |
hzlf/openbroadcast | website/multilingual/languages.py | Python | gpl-3.0 | 2,661 | 0.006389 | """
Django-multilingual: language-related settings and functions.
"""
# Note: this file did become a mess and will have to be refactored
# after the configuration changes get in place.
#retrieve language settings from settings.py
from multilingual import settings
from django.utils.translation import ugettext_lazy as... | + '_'
+ _to_db_identifier(language_code))
def get_language_idx(language_code):
return get_language_code_list().index(language_code)
def get_translated_field_alias(field_name, language_code):
" | ""
Return an alias for field_name field for a given language_code.
Used in SQL queries.
"""
return ('_trans_'
+ field_name
+ '_' + _to_db_identifier(language_code))
def get_fallbacks(language_code):
fallbacks = settings.FALLBACK_LANGUAGES.get(language_code, [])
if le... |
guyfawcus/ArchMap | docs/conf.py | Python | unlicense | 9,093 | 0.006381 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ArchMap documentation build configuration file, created by
# sphinx-quickstart on Sat Apr 19 11:17:53 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | st'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'ArchMap'
copyright = '2017, James Fawcus-Robinson'
# The version info for the project you're documenting, acts as replacement for
# |version| and... | out the
# built documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
#release = '0.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: eithe... |
mattrobenolt/redis-py-contrib | setup.py | Python | bsd-2-clause | 768 | 0 | #!/usr/bin/env python
"""
redis-contrib
======
Missing contrib packages for redis-py.
"""
from setuptools import setup, find_packages
setup(
name='redis-contrib',
version='0.0.0',
author='Matt Robenolt',
author_email='matt@ydekproductions.com',
url='https://github.com/mattrobenolt/redis-py-contri... | edis-py',
long_description=__doc__,
packages=find_packages(),
zip_safe=False,
license='BSD',
install_requires=[
'redis',
],
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating... | tware Development'
],
)
|
biancini/TwitterAnalyzer | AnalysisTools/TwitterEngine/drawmap.py | Python | apache-2.0 | 2,613 | 0.011864 | __author__ = "Andrea Biancini"
__date__ = "October 2, 2013"
import os
from PIL import Image, ImageDraw, ImageFont
# from backend import TwitterApiCall,MySQLBackend
from backend import ElasticSearchBackend
class DrawMap():
color = (255, 0, 0)
lower_left = [41.0, -5.5]
top_right = [51.6, 10.0]
def __init__... | ticSearchBackend()
def GetXY(self, size, lat, lng):
x = size[0] * (lng - self.lower_left[1]) / (self.top_right[1] - self.lower_left[1])
y = size[1] * (lat - self.top_right[0]) / (self.lower_left[0] - self.top_right[0])
return [int(x), int(y)]
def DrawPoint(self, draw, x, y):
radius = 5
draw.e... | lor)
del draw
def ProduceImages(self):
root_path = os.path.abspath(os.path.join(__file__, '..'))
interval = 30
advancement = 0
imgnum = 1
persistence = 10
show = []
for i in range(0, persistence): show.append([])
tweets = self.backend.GetAllTweetCoordinates()
if tweets is ... |
celestian/sssd | src/tests/intg/sssd_ldb.py | Python | gpl-3.0 | 2,793 | 0 | #
# SSSD integration test - access the ldb cache
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This 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; version 2 only
#
# 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 PURPO... | p://www.gnu.org/licenses/>.
#
import os
import ldb
import config
class CacheType(object):
sysdb = 1
timestamps = 2
class TsCacheEntry(object):
user = 1
group = 2
class SssdLdb(object):
def __init__(self, domain_name):
self._domain_name = domain_name
self._sysdb = self._create_... |
tlapicka/2013-2014.3A | rovnice.py | Python | gpl-3.0 | 145 | 0.006897 | #!/usr/bin/python
def kvadrat | icka(a, b, c):
return 20
def kubicka(a, b, c, d):
return 77
x = 16
y = 'ahoj'
print | 'Inicializuji se'
|
NarrativeTeam/exifyay | bindings/__init__.py | Python | lgpl-3.0 | 23 | 0 | from .ex | ifyay impo | rt *
|
ligo-cbc/pycbc | docs/_include/transforms-table.py | Python | gpl-3.0 | 1,272 | 0 | #!/usr/bin/env python
# Copyright (C) 2018 Duncan Macleod, Collin Capano
#
# This program is free software; you can re | distribute 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 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... |
hasibi/TAGME-Reproducibility | scripts/evaluator_topics.py | Python | mit | 6,795 | 0.001766 | """
This script computes Topic metrics for the end-to-end performance.
Precision and recall are micro-averaged.
Matching condition: only entities should match.
@author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no)
"""
from __future__ import division
import sys
from collections import defaultdict
class EvaluatorTopic... | s_eval = {}
total_tp, total_fp, total_fn = 0, 0, 0
for qid in sorted(self. | qrels_dict):
queries_eval[qid] = eval_query_func(self.qrels_dict[qid], self.results_dict.get(qid, {}))
total_tp += queries_eval[qid]['tp']
total_fp += queries_eval[qid]['fp']
total_fn += queries_eval[qid]['fn']
total_prec = total_tp / (total_tp + total_fp)
... |
voicecom/pgtool | tests/__init__.py | Python | apache-2.0 | 45 | 0 | """This file is intentionally left bl | ank | ."""
|
MattClarke131/league | app/league/dashboard/views.py | Python | mit | 6,257 | 0.00032 | # -*- coding: utf-8 -*-
"""Dashboard."""
from flask import (Blueprint, current_app, flash, redirect, render_template,
request, url_for)
from flask_login import login_required, login_user
from league.dashboard.forms import (GameCreateForm, PlayerCreateForm,
PlayerD... | created!', 'success')
else:
flash_errors(form)
players = Player.query.all()
return render_template('dashboard/players.html', players=players,
| player_create_form=form)
@blueprint.route('/players/<int:player_id>', methods=['GET'])
def get_player(player_id):
"""Get game history and statistics for player."""
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
... |
WikiWatershed/gwlf-e | gwlfe/MultiUse_Fxns/Runoff/pRunoff.py | Python | apache-2.0 | 1,598 | 0.005632 | from numpy import zeros
from gwlfe.Memoization import memoize
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f
from gwlfe.Output.Loading.PConc import PConc
from gwlfe.Output.Loading.PConc import PConc_f
@memoize
def pRunoff(NYrs, DaysMonth, I... | reMonth2,
LastManureMonth2)
for Y in range(NYrs):
for i in range(12):
for l in range(NRur):
# += changed to =
result[Y][i][l] = 0.1 * p_conc[i][l] * rur_q_runoff[Y][l][i] * Area[l]
return result
@memoize
def pRunoff_f(NYrs, DaysMonth, Init... | FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2):
p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2,
LastManureMonth2)[:, :NRur]
rur_q_runoff = RurQRunoff_f(NYrs, DaysMonth, InitSn... |
yetship/blog_codes | multiprocess_demo/example02.py | Python | gpl-3.0 | 432 | 0.002315 | #!/usr/bin/env python
"""
A simple python example for multiprocess.
Created by | yetship at 2017/4/18 08:57
"""
f | rom random import randint
import multiprocessing
def worker(lower, upper):
"""thread worker function"""
print("get a random int: {}".format(randint(lower, upper)))
if __name__ == '__main__':
for i in range(3):
p = multiprocessing.Process(target=worker, args=(i, i ** 2))
p.start() |
deluxghost/DelogX | DelogX/utils/parser.py | Python | lgpl-3.0 | 1,000 | 0 | # -*- coding: utf-8 -*-
'''DelogX.utils.parser
Utils of markdown parser.
'''
import markdown
class Markdown(object):
'''Include the markdown parser method.'''
@classmethod
def markdown(cls, text, exts=None):
'''Parse markdown text to HTML5.
Args:
text (str): Raw markdown te... | 'markdown.extensions.tables',
'markdown.extensions.fenced_code'
]
if exts and isinstance(exts, (list, set, tuple)):
ext_list.extend(exts)
elif exts:
ext_list.append(exts)
output = markdown.markdown(
tex | t,
output_format='html5',
tab_length=4,
extensions=ext_list
)
if not output:
output = '<p></p>'
return output
|
ActionAdam/osmc | package/mediacenter-addon-osmc/src/script.module.osmcsetting.networking/resources/lib/osmc_bluetooth.py | Python | gpl-2.0 | 6,660 | 0.006006 | import connman
import bluetooth
import systemd
import sys
import pexpect
import json
RUNNING_IN_KODI = True
# XBMC Modules
try:
import xbmc
import xbmcgui
import xbmcaddon
except:
RUNNING_IN_KODI = False
DEVICE_PATH = 'org.bluez.Device1'
PAIRING_AGENT = 'osmc_bluetooth_agent.py'
BLUETOOTH_SERVICE ... | 'SOL@'
PEXPECT_EOL = '@EOL'
def log(message):
msg_str='OSMC_BLUETOOTH - ' + str(message)
if RUNNING_IN_KODI:
xbmc.log(msg_str, level=xbmc. | LOGDEBUG)
else:
print(msg_str)
def is_bluetooth_available():
return connman.is_technology_available('bluetooth')
def is_bluetooth_enabled():
connman_status = connman.is_technology_enabled('bluetooth')
service_status = systemd.is_service_running(BLUETOOTH_SERVICE)
return connman_status an... |
mozilla/medlem | medlem/wsgi.py | Python | mpl-2.0 | 1,039 | 0 | """
WSGI config for medlem project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'medlem.settings') # NOQA
# from django... | license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
# if newr | elic_ini and newrelic_license_key:
# newrelic.agent.initialize(newrelic_ini)
# application = newrelic.agent.wsgi_application()(application)
|
isc-projects/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_pgsql.py | Python | isc | 22,290 | 0.003006 | """Host Reservation DHCPv6"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_msg
import srv_control
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
@pytest.mark.pgsql
def test_v6_host_reservation_duplicate_reservation_duid():
misc.test_setup()
srv_cont... | stgreSQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'PostgreSQL', 1)
srv_control.new_db_backend_reservation('PostgreSQL', 'hw-address', 'f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 2, 'PostgreSQL', 2)
srv_control.ipv6_address_db_back... | start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', 666)
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send... |
spiceqa/tp-spice | spice/lib/utils_selenium.py | Python | gpl-2.0 | 2,480 | 0.00121 | # ONLY FOR DOCUMANTATION PURPOSE
#
#import os
#import re
#
#class CommandsLinuxSelenium(Commands):
#
# def run_selenium(self, ssn):
# """Some general info.
# There are ways to define Firefox options globaly:
#
# * /usr/lib64/firefox/defaults/preferences/<anyname>.js
# * /etc/firef... | p.updateUserPrefs(new File("D:\\t.js"));
#
# To create a new profile call:
#
# firefox -CreateProfile <profile name>
#
# """
# selenium = download_asset("selenium",
# section=self.cfg_vm.selenium_ver)
# fname = os.path.basename(selenium)... | d("-port %s" % cfg.selenium_port)
# opts.append("-trustAllSSLcertificates")
# if self.cfg.selenium_driver == 'Firefox':
# profile = self.cfg.firefox_profile
# if profile:
# cmd = "firefox -CreateProfile %s" % profile
# output = self.ssn.cmd(cmd)
# ... |
mithro/HDMI2USB-litex-firmware | targets/utils.py | Python | bsd-2-clause | 1,695 | 0.00354 | import pprint
def period_ns(freq):
return 1e9/freq
def csr_map_update(csr_map, csr_peripherals):
csr_map.update(dict((n, v)
for v, n in enumerate(csr_peripherals, start=(max(csr_map.values()) + 1) if csr_map else | 0)))
def csr_map_update_print(csr_map, csr_peripherals):
print()
print("-"*75)
print("Previous Max: {}".format(max(csr_map.values())))
csr_map.update(dict((n, v)
for v, n in enumerate(csr_peripheral | s, start=max(csr_map.values()) + 1)))
print(" New Max: {}".format(max(csr_map.values())))
csr_values = list((b,a) for a, b in csr_map.items())
csr_values.sort()
pprint.pprint(csr_values)
print("-"*75)
print()
def assert_pll_clock(requested_freq, input, feedback, divide, msg):
output_fr... |
brakhane/panda3d | samples/solar-system/step3_load_model.py | Python | bsd-3-clause | 4,775 | 0.005236 | #!/usr/bin/env python
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 2015-03-13
#
# This tutorial is intended as a initial panda scripting lesson going over
# display initialization, loading models, placing objects, and the scene graph.
#
# Step 3: In this step, we create a function called loadPlanets, which w... | the planets we will use the same
# sphere model and simply change textures. However, even though the sky is
# a sphere, it is different from the planet model because its polygons
#(which are always one-sided in Panda) face inside the sphere instead of
# outside (this is known as a model ... | # that it has to be a separate model.
self.sky = loader.loadModel("models/solar_sky_sphere")
# After the object is loaded, it must be placed in the scene. We do this by
# changing the parent of self.sky to render, which is a special NodePath.
# Each frame, Panda starts with rend... |
skeenp/Roam | libs/py2exe-0.6.9/py2exe/resources/VersionInfo.py | Python | gpl-2.0 | 9,595 | 0.008338 | # -*- coding: latin-1 -*-
##
## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller
##
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitatio... | E.
##
#
# $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $
#
# $Log$
# Revision 1.3 2004/01/16 10:45:31 theller
# Move py2exe from the sandbox directory up to the root dir.
#
# Revision 1.3 2003/12/29 13:44:57 theller
# Adapt for Python 2.3.
#
# Revision 1.2 2003/09/18 20:19:57 the | ller
# Remove a 2.3 warning, but mostly this checkin is to test the brand new
# py2exe-checkins mailing list.
#
# Revision 1.1 2003/08/29 12:30:52 mhammond
# New py2exe now uses the old resource functions :)
#
# Revision 1.1 2002/01/29 09:30:55 theller
# version 0.3.0
#
# Revision 1.2 2002/01/14 19:08:05 theller
... |
hjanime/VisTrails | vistrails/db/versions/v1_0_3/translate/v1_0_2.py | Python | bsd-3-clause | 14,959 | 0.004145 | ###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | module = sig[0]
else:
package = sig[0]
module = sig[1]
if len(sig) > 2:
namespace = sig[2]
item = DBPortSpecItem(id=id_scope.getNewId(DBPortSpecItem.vtType),
pos=i,
module=module,
... | namespace=namespace,
label=label,
default=default)
item.db_values = ''
item.db_entry_type = ''
new_obj.db_add_portSpecItem(item)
return new_obj
def update_portSpecs(old_obj, translate_dict):
new_port_specs = []
fo... |
napsternxg/GenderPrediction | data_download.py | Python | gpl-3.0 | 1,931 | 0.002071 | # [START all]
import argparse
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def main(project_id):
# [START build_service]
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get... | EN number
ELSE 0
END)/Total as Female,
SUM(CASE
WHEN gender = "M"
THEN number
ELSE 0
END)/Total as Male,
FROM [fh-bigquery:popular_names.usa_1910_2013] GROUP BY name) as a ORDER BY confidence DESC;
"""
}
query_response = query_request.query(
projectId=project_id... | %s' % file_name)
with open(file_name, "wb+") as fp:
for row in query_response['rows']:
print >> fp, '\t'.join(field['v'] for field in row['f'])
# [END print_results]
except HttpError as err:
print('Error: {}'.format(err.content))
raise err
if __name__ ... |
dongjoon-hyun/tensorflow | tensorflow/contrib/tensorrt/test/reshape_transpose_test.py | Python | apache-2.0 | 6,469 | 0.00371 | # 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... | ort
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.o... | import test
class ReshapeTest(trt_test.TfTrtIntegrationTestBase):
def GetParams(self):
dtype = dtypes.float32
input_name = "input"
input_dims = [100, 24, 24, 2]
output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
dtype=dtype, shape=[None]... |
domovilam/pimucha | piHAparsers/x10libs/c_cm1x.py | Python | gpl-3.0 | 1,136 | 0.021127 | # ----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Huynh Vi Lam <domovilam@gmail.com>
#
# This file is part of pimucha.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | ut WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the | GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
import logging,sys
logger = logging.getLogger()
X10Checkers = {
'RF' : 'x10chk(args)' ,
'PL' : 'x10chk(args)' ,
}
X10Encoders =... |
chippey/gaffer | apps/execute/execute-1.py | Python | bsd-3-clause | 5,996 | 0.043195 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | ) :
def __init__( | self ) :
Gaffer.Application.__init__(
self,
"""
Executes task nodes such as ImageWriters, SystemCommands and Render nodes
from within a .gfr file. This is used by Gaffer's dispatchers when executing
nodes in a background process or on a render farm, but can also be used to
perform a manual executi... |
benjyw/pants | src/python/pants/backend/python/lint/docformatter/rules.py | Python | apache-2.0 | 4,834 | 0.002482 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from typing import Tuple
from pants.backend.python.lint.docformatter.skip_field import SkipDocformatterField
from pants.backend.python.lint.docformatter.... | UnionRule
from pants.util.logging import LogLevel
from pants.util.strutil import pluralize
@dataclass(frozen=True)
class DocformatterFieldSet(FieldSet):
required_fields = (PythonSources,)
sources: PythonSources
@classmethod
def opt_out(cls, tgt: Target) -> bool:
return tgt.get(SkipDocformat... | class DocformatterRequest(PythonFmtRequest, LintRequest):
field_set_type = DocformatterFieldSet
@dataclass(frozen=True)
class SetupRequest:
request: DocformatterRequest
check_only: bool
@dataclass(frozen=True)
class Setup:
process: Process
original_digest: Digest
def generate_args(
*, sour... |
spikeekips/serf-python | src/serf/connection.py | Python | mpl-2.0 | 8,756 | 0.014048 | import socket
import urlparse
import urllib
import string
import time
import logging
from . import _exceptions
from . import constant
log = logging.getLogger('serf-rpc-client', )
AVAILABLE_HOST_URI_QUERY_KEYS = set([
'AuthKey',
], )
def parse_host (h, ) :
_hosts = list()
for i in filter(strin... | exceptions.ConnectionError(
'tried to all the known members, but failed, %s' % _members, )
if not self._once_connected :
| self._once_connected = True
self.disconnected = False
self._conn = _sock
return self._conn
def _connection (self, members, ) :
if not members :
raise _exceptions.ConnectionError('no members to connect', )
_sock = None
_members = members[:]
... |
dpaiton/OpenPV | pv-core/python/pvtools/readpvpfile.py | Python | epl-1.0 | 10,448 | 0.009858 | from .readpvpheader import readpvpheader,extendedHeaderPattern
import scipy.sparse as sp
import numpy as np
import os
import pdb
"""
readpvpfile reads pvp files from the output of OpenPV
filename: Filename of the pvp file.
progressPeriod: How often to print out progress. 0 means do not print progress (default).
lastFr... | 'ny', np.uint16),
('offset', np.uint32),
('values', dataT | ype, shape)])
stream.seek(0)
frameRange = range(startFrame, lastFrame, skipFrames)
data["values"] = np.zeros((len(frameRange), header['nbands'], header['numpatches'], header['nyp'], header['nxp'], header['nfp']))
data["time"] = np.zeros((len(frameRange)));
f... |
airbnb/airflow | tests/providers/google/cloud/operators/test_cloud_memorystore_system.py | Python | apache-2.0 | 2,251 | 0.001333 | #
# 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"); you may not... | ROJECT_ID", "example-project")
GCP_ARCHIVE_URL = os.environ.get("GCP_MEMORYSTORE_EXPORT_GCS_URL", "gs://test-memorystore/my-export.rdb")
GCP_ARCHIVE_URL_PARTS = urlparse(GCP_ARCHIVE_URL)
GCP_BUCKET_NAME = GCP_ARCHIVE_URL_PARTS.netloc
@pytest.mark.backend("mysql", "postgres")
@pytest.mark.credential_file(GCP_MEMORYSTO... | )
class CloudMemorystoreSystemTest(GoogleSystemTest):
"""
System tests for Google Cloud Memorystore operators
It use a real service.
"""
@provide_gcp_context(GCP_MEMORYSTORE)
def setUp(self):
super().setUp()
self.create_gcs_bucket(GCP_BUCKET_NAME, location="europe-north1")
... |
pik-copan/pyregimeshifts | scripts/raw_proxy_records_analysis/recurrence_analysis_speleo_raw.py | Python | mit | 13,113 | 0.004576 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2014 Jonathan F. Donges
# Author: Jonathan F. Donges <donges@pik-potsdam.de>
# URL: <http://www.pik-potsdam.de/members/donges/software>
"""
Performs recurrence analysis of paleoclimate proxy records.
This script provides analyses for this publication:
J.F. Donges, R.V. ... | []
# Get number of time series
n_time_series = len(FILENAMES)
# Load data
for i in xrange(n_time_series):
time, data = np.loadtxt(DATA_DIR + FILENAMES[i], comments=COMMENT_SYM | BOL,
unpack=True, usecols=(0,1,))
average_sampling_time = np.diff(time).mean()
time_list.append(time)
if DETREND:
# Detrend data!
detrended_data = detrend_time_series(data=data,
window_size=DETRENDING_WINDOW_SIZE / average_sampling_time)
... |
jhseu/tensorflow | tensorflow/python/distribute/saved_model_save_load_test.py | Python | apache-2.0 | 6,739 | 0.004452 | # Copyright 2019 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... | f _train_model(self, model, x_train, y_train, batch_size):
pass
def _predict_with_model(self, distribution, model, predic | t_dataset):
if distribution:
dist_predict_dataset = distribution.experimental_distribute_dataset(
predict_dataset)
per_replica_predict_data = next(iter(dist_predict_dataset))
result = distribution.experimental_run_v2(
model, args=(per_replica_predict_data,))
# Convert the... |
belokop/indico_bare | indico/web/http_api/metadata/xml.py | Python | gpl-3.0 | 4,167 | 0.00096 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | yDicts = all(type(subv) == dict for subv in v)
if onlyDicts:
for subv | in v:
elem.append(self._xmlForFossil(subv))
else:
for subv in v:
if type(subv) == dict:
elem.append(self._xmlForFossil(subv))
else:
... |
nmercier/linux-cross-gcc | win32/bin/Lib/hashlib.py | Python | bsd-3-clause | 8,063 | 0.000248 | # $Id$
#
# Copyright (C) 2005 Gregory P. Smith (greg@krypto.org)
# Licensed to PSF under a Contributor Agreement.
#
__doc__ = """hashlib module - A common interface to many hash function | s.
new(name, string='') - returns a new hash object implementing the
given hash function; initializing the hash
using the given string data.
Named constructor functions are also available, these are much faster
than using new():
md5(), sha1(), sha224(), sha256()... | he algorithms_guaranteed and algorithms_available attributes
to find out what algorithm names can be passed to new().
NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.