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 |
|---|---|---|---|---|---|---|---|---|
zheller/flake8-quotes | test/test_checks.py | Python | mit | 10,373 | 0.00617 | from flake8_quotes import QuoteChecker
import os
import subprocess
from unittest import TestCase
class TestChecks(TestCase):
def test_get_noqa_lines(self):
checker = QuoteChecker(None, filename=get_absolute_path('data/no_qa.py'))
self.assertEqual(checker.get_noqa_lines(checker.get_file_contents())... | l(list(doubles_checker.get_quotes_errors(doubles_checker.get_file_contents())), [
{'col': 4, 'line': 1, 'message': 'Q001 Double quote multiline found but single quotes preferred'},
])
def test_wrapped(self):
doubles_checker = QuoteChecker(None, filename=get_absolute_path('data/doubles_w... | :
doubles_checker = QuoteChecker(None, filename=get_absolute_path('data/doubles.py'))
self.assertEqual(list(doubles_checker.get_quotes_errors(doubles_checker.get_file_contents())), [
{'col': 24, 'line': 1, 'message': 'Q000 Double quotes found but single quotes preferred'},
{'col'... |
nbargnesi/proxme | setup.py | Python | mit | 1,716 | 0.001166 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
# TODO: put package requirements... | s='proxme',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Progra... | 'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements,
setup_requires=setup_requirements,
entry_points = {
'console_scripts': [
'proxme = proxme.__main__:main'
],
}
)
|
DayGitH/Python-Challenges | DailyProgrammer/DP20161109B.py | Python | mit | 1,742 | 0.004018 | """
[2016-11-09] Challenge #291 [Intermediate] Reverse Polish Notation Calculator
https://www.reddit.com/r/dailyprogrammer/comments/5c5jx9/20161109_challenge_291_intermediate_reverse/
A little while back we had a programming
[challenge](https://www.reddit.com/r/dailyprogrammer/comments/2yquvm/20150311_challenge_205_i... | Drop by /r/dailyprogrammer_ideas and
share it with everyone!
"""
def mai | n():
pass
if __name__ == "__main__":
main()
|
aronsky/home-assistant | homeassistant/components/vicare/sensor.py | Python | apache-2.0 | 16,333 | 0.000735 | """Viessmann ViCare sensor device."""
from __future__ import annotations
from contextlib import suppress
from dataclasses import dataclass
import logging
from PyViCare.PyViCareUtils import (
PyViCareInvalidDataError,
PyViCareNotSupportedFeatureError,
PyViCareRateLimitError,
)
import requests
from homeass... | OR_BURNER_STARTS = "burner_starts"
SENSOR_BURNER_HOURS = "burner_hours"
SENSOR_BURNER_POWER = "burner_power"
SENSOR_DHW_GAS_CONSUMPTION_TODAY = "hotwater_gas_consumption_today"
SENSOR_DHW_GAS_CONSUMPTION_THIS_WEEK = "hotwater_gas_consumption_heating_this_week"
SE | NSOR_DHW_GAS_CONSUMPTION_THIS_MONTH = "hotwater_gas_consumption_heating_this_month"
SENSOR_DHW_GAS_CONSUMPTION_THIS_YEAR = "hotwater_gas_consumption_heating_this_year"
SENSOR_GAS_CONSUMPTION_TODAY = "gas_consumption_heating_today"
SENSOR_GAS_CONSUMPTION_THIS_WEEK = "gas_consumption_heating_this_week"
SENSOR_GAS_CONSUMP... |
psikon/pitft-scripts | src/mainscreen.py | Python | mit | 2,347 | 0.007669 | #!/usr/bin/env python
'''
Generate the main window for the pi-gui program. The interface show the last played
item with cover, title and supllemental informations that is interactive
and two buttons for show up the library screen and exit the porgram itself.
'''
#@author: Philipp Sehnert
#@contact: philipp.sehnert[a... | for the menu items
self.funcs = funcs
# cached book for last played window
self.book = book
#define function that checks for mouse location
def on_click(self):
click_pos = (pygame.mouse.get_pos() [0], pygame.mouse.get_pos() [1])
# select last played item
if 10 <=... | # go to library screen
if 10 <= click_pos[0] <= 205 and 190 <= click_pos[1] <= 230:
self.funcs['Select Book']()
# exit gui
if 265 <= click_pos[0] <= 315 and 190 <= click_pos[1] <= 230:
self.interface.exit_interface(self.screen)
def run(self):
'''run metho... |
vlegoff/tsunami | src/abstraits/obase/__init__.py | Python | bsd-3-clause | 9,968 | 0.002834 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | un attribut change de nom ou de type), à la récupération l'objet sera
mis à jour grâce à une fonction définie dans le convertisseur
(voir BaseObj.update).
La fonction se trouvera dans un fichier identifiant le nom de la
classe. On s'assure grâce à cette métaclasse que deux classes
... | ces
classes hérités.
"""
def __init__(cls, nom, bases, contenu):
"""Constructeur de la métaclasse"""
type.__init__(cls, nom, bases, contenu)
classes_base[cls.__module__ + "." + cls.__name__] = cls
# Si on trouve les attributs _nom et _version,
# c'est que la cla... |
krfkeith/enough | lib/dot.py | Python | gpl-3.0 | 6,472 | 0.004944 | # Copyright (c) 2007 Enough Project.
# See LICENSE for details.
## /* Copyright 2007, Eyal Lotem, Noam Lewis, enoughmail@googlegroups.com */
## /*
## This file is part of Enough.
## Enough is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as pu... | h()
def processEnded(self, reason):
self.proto.connectionLost(reason)
class _DotProtocol(LineReceiver):
delimiter = ' | \n'
def __init__(self):
self._waiting = None
self._current_graph_parser = None
self._process = None
def set_process(self, process):
self._process = process
def lineReceived(self, line):
if self._current_graph_parser is None:
raise Error("Dot outputs stuf... |
yochow/autotest | server/hosts/monitors/monitors_util.py | Python | gpl-2.0 | 10,543 | 0.000474 | # Shared utility functions across monitors scripts.
import fcntl, os, re, select, signal, subprocess, sys, time
TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.'
class Error(Exception):
pass
class InvalidTimestampFormat(Error):
pass
def prepend_timestamp(msg, format):
"""Prepen... | ing mode.
This allows us to take advantage of pipe.read()
where we don't have to specify a buflen.
Cuts down on a few lines we'd have to maintain.
Args:
pipe: file; File object to modify
Returns: pipe
"""
flags = fcntl.fcntl(pipe, fcntl.F_GETFL)
fcntl.fcntl(pipe, fcntl.F_SETFL, ... | _paths: list;
lastlines_dirpath: str;
Returns:
tuple; (procs, pipes) or
({path: subprocess.Popen, ...}, {file: path, ...})
"""
if lastlines_dirpath and not os.path.exists(lastlines_dirpath):
os.makedirs(lastlines_dirpath)
tail_cmd = ('/usr/bin/tail', '--retry', '--follow=... |
themadhatterz/cpapi | app/checkpoint.py | Python | mit | 6,936 | 0.001874 | import ast
import base64
import itertools
from functools import lru_cache
import cpapilib
from flask import session
from app import app
OBJECTS_DICTIONARY = None
@lru_cache(maxsize=5000)
def uid_name(uid_obj):
for obj in OBJECTS_DICTIONARY:
if uid_obj == obj['uid']:
return obj['name']
... | else:
section = ''
all_rules['rulebase'].append({'type': 'accesssection', 'name': section})
if 'rulebase' in rule:
for subrule in rule['rulebase']:
final = self._filter_rule(subrule, response['objects-diction | ary'])
all_rules['rulebase'].append(final)
return all_rules
@staticmethod
def _filter_rule(rule, object_dictionary):
"""Recieves rule and replaces UID with Name."""
global OBJECTS_DICTIONARY
OBJECTS_DICTIONARY = object_dictionary
src = rule['source']
... |
smallyear/linuxLearn | salt/salt/modules/freebsdports.py | Python | apache-2.0 | 13,305 | 0 | # -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it it also possible... | Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join | (_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.make... |
fokusov/moneyguru | core/plugin/stale_currency_provider.py | Python | gpl-3.0 | 3,715 | 0.004307 | # Copyright 2016 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
# This plugin subclasses CurrencyProviderPlugin to provide additional curre... | f.register_currency(
'TRL', 'Turkish lira',
exponent=0, start_date=date(1998, 1, 2), start_rate=7.0e-06,
stop_date=date(2004, 12, 31), latest | _rate=8.925e-07)
self.register_currency(
'VEB', 'Venezuelan bolivar',
exponent=0, start_date=date(1998, 1, 2), start_rate=0.002827,
stop_date=date(2007, 12, 31), latest_rate=0.00046)
self.register_currency(
'SKK', 'Slovak koruna',
start_date=da... |
jpvantuyl/python_koans | python2/koans/about_method_bindings.py | Python | mit | 2,996 | 0.000668 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... | function2.get_fruit | = function
self.assertEqual('pineapple', function2.get_fruit())
def test_inner_functions_are_unbound(self):
function2.get_fruit = function
try:
cls = function2.get_fruit.im_self
except AttributeError as ex:
self.assertMatch('object has no attribute', ex[0])
... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/SGIX/shadow.py | Python | lgpl-3.0 | 750 | 0.024 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | ,0x819B)
GL_TEXTURE_COMPARE_SGIX=_C(' | GL_TEXTURE_COMPARE_SGIX',0x819A)
GL_TEXTURE_GEQUAL_R_SGIX=_C('GL_TEXTURE_GEQUAL_R_SGIX',0x819D)
GL_TEXTURE_LEQUAL_R_SGIX=_C('GL_TEXTURE_LEQUAL_R_SGIX',0x819C)
|
EdinburghGenomics/clarity_scripts | scripts/generate_hamilton_input_UPL.py | Python | mit | 4,957 | 0.00585 | #!/usr/bin/env python
import csv
import sys
from EPPs.common import StepEPP
class GenerateHamiltonInputUPL(StepEPP):
"""Generate a CSV containing the necessary information to batch up to 9 User Prepared Library receipt plates into
one DCT plate. The Hamilton requires input and output plate containers and well... | the step.' % len(unique_output_containers))
sys.exit(1)
# define the rows and columns in the input plate (standard 96 well plate pattern)
| rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
columns = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
# add the lines to the csv_array that will be used to write the Hamilton input file
for unique_input_container in sorted(unique_input_containers):
for col... |
knuu/competitive-programming | atcoder/corp/codefes2014qb_c_2.py | Python | mit | 203 | 0.137931 | from collections import Counter as C
i,s=lambda:C(input()),lambda t:sum(t.v | alues());a,b,c=i(),i(),i();a,b,N=a&c,b&c,s(c);print('NO'if any((a+b)[k]<v for k,v in c.items())|(s(a)*2<N)|(s(b)*2<N)el | se'YES')
|
EthanBlackburn/sync-engine | migrations/versions/006_add_search_tokens.py | Python | agpl-3.0 | 797 | 0.002509 | """Add search tokens.
Revision ID: 482338e7a7d6
Revises: 41a7e825d108
Create Date: 2014-03-18 00:16:49.525732
"""
# revision identifiers, used by Alembic.
revision = '482338e7a7d6'
down_revision = 'adc646e1f11'
from alembic import op
import sql | alchemy as sa
def upgrade():
op.create_table(
'searchtoken',
sa.Column('id', sa.Integer(), nullable=False | ),
sa.Column('token', sa.String(length=255), nullable=True),
sa.Column('source', sa.Enum('name', 'email_address'), nullable=True),
sa.Column('contact_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['contact_id'], ['contact.id'],
ondelete='CASCA... |
randomshinichi/QRL | src/qrl/core/txs/TokenTransaction.py | Python | mit | 9,390 | 0.002556 | from pyqrllib.pyqrllib import bin2hstr, QRLHelper
from qrl.core import config
from qrl.core.AddressState import AddressState
from qrl.core.misc import logger
from qrl.core.txs.Transaction import Transaction
class TokenTransaction(Transaction):
"""
TokenTransaction to create new Token.
"""
def __init... | alance in self.initial_balances:
if initial_balance.address == self.owner:
owner_processed = True
if initial_balance.address == self.addr_from:
addr_from_processed = True
if initial_balance.address == add | r_from_pk:
addr_from_pk_processed = True
if initial_balance.address in addresses_state:
addresses_state[initial_balance.address].update_token_balance(self.txhash,
|
ForensicTools/GRREAT-475_2141-Chaigon-Failey-Siebert | client/client_actions/file_fingerprint.py | Python | apache-2.0 | 2,271 | 0.010128 | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Action to fingerprint files on the client."""
import hashlib
from grr.parsers import fingerprint
from grr.client import vfs
from grr.client.client_actions import standard
from grr.lib import rdfvalue
class FingerprintFile(standard.ReadBuffe... | rdfvalue.FingerprintTuple.Type.FPT_GENERIC: (
fingerprint.Fingerprinter.EvalGeneric),
rdfvalu | e.FingerprintTuple.Type.FPT_PE_COFF: (
fingerprint.Fingerprinter.EvalPecoff),
}
def Run(self, args):
"""Fingerprint a file."""
with vfs.VFSOpen(args.pathspec,
progress_callback=self.Progress) as file_obj:
fingerprinter = fingerprint.Fingerprinter(file_obj)
respons... |
jaak-s/chemblnet | models/vaffl.py | Python | mit | 7,837 | 0.016843 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mat", type=str, help="mat file with observations X and side info", required=True)
parser.add_argument("--epochs", type=int, help="number of epochs", default = 2000)
parser.add_argument("--hsize", type=int, help="size of the hidden layer", ... | al: Xv,
# x_idx_comp: Xindices,
# y_idx_comp: Ytr_idx_comp,
# y_idx_prot: Ytr_idx_prot,
# y_val: Ytr_val,
# | tb_ratio: 1.0,
# bsize: Ytrain.shape[0]
# })
# beta_l2 = np.sqrt(sess.run(tf.nn.l2_loss(beta.mean)))
# beta_std_min = np.sqrt(sess.run(tf.reduce_min(beta.var)))
# beta_prec = sess.run(beta.prec)
# ... |
btenaglia/hpc-historias-clinicas | hpc-historias-clinicas/historias/migrations/0007_auto_20150425_1459.py | Python | bsd-3-clause | 1,309 | 0.002292 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('historias', '0006_auto_20150413_0001'),
]
operations = [
migrations.AlterField(
model_name='hist... | field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'),
preserve_default=True,
| ),
migrations.AlterField(
model_name='historias',
name='hora_ingreso',
field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'),
preserve_default=True,
),
... |
oskyar/test-TFG | TFG/apps/subject/models.py | Python | gpl-2.0 | 2,996 | 0.000334 | __author__ = 'oskyar'
from django.db import models
from django.utils.translation import ugettext as _
from s3direct.fields import S3DirectField
from smart_selects.db_fields import ChainedManyToManyField
# Manager de Asignatura
class SubjectManager(models.Manager):
def owner(self, pk_subject):
return self... | missions = (
('view_subject', 'View detail Subject'),
('register_subject', 'Student registers of subject'),
('unregister_subject', 'Student unregisters of subject')
)
def __str__(self):
return self.name + " | (" + self.category + ")"
|
LowerSilesians/geo-squizzy | tests/gs_socket/__init__.py | Python | mit | 19 | 0 | __ | author__ = 'ing' | |
arnaudfr/echec | tests/test_players.py | Python | gpl-3.0 | 1,120 | 0.001786 | # -*- coding: utf-8 -*-
from src.constant import *
import unittest
from src.game import Game |
class TestPlayers(unittest.TestCase):
# Init a player
def test_initPlayer(self):
game = Game()
player = game.createPlayer()
self.assertEqual(player._id, 0)
# Get a valid player
def test_getPlayer(self):
game = Game()
player0 = game.createPlayer()
playe... | id, 1)
playerN = game.getPlayer(0)
self.assertEqual(playerN._id, 0)
playerN = game.getPlayer(1)
self.assertEqual(playerN._id, 1)
# Get an invalid player
def test_getUnvalidPlayer(self):
game = Game()
player = game.getPlayer(0)
self.assertIsNone(player)
... |
mlperf/training_results_v0.7 | Google/benchmarks/resnet/implementations/resnet-cloud-TF2.0-tpu-v3-32/tf2_common/modeling/activations/swish.py | Python | apache-2.0 | 2,452 | 0.00367 | # 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... | _ import absolute_import |
from __future__ import division
from __future__ import print_function
import tensorflow as tf
@tf.keras.utils.register_keras_serializable(package='Text')
def simple_swish(features):
"""Computes the Swish activation function.
The tf.nn.swish operation uses a custom gradient to reduce memory usage.
Since savi... |
igordejanovic/textx-tools | txtools/templates/lang/copy/pack_name/__init__.py | Python | mit | 25 | 0 | __ve | rsion__ = "0.1.dev0" | |
praus/shapy | tests/netlink/test_htb_class.py | Python | mit | 1,941 | 0.014426 | import unittest
import socket
import os
from shapy.framework.netlink.constants import *
from shapy.framework.netlink.message import *
from shapy.framework.netlink.tc import *
from shapy.framework.netlink.htb import *
from shapy.framework.netlink.connection import Connection
from tests import TCTestCase
class TestClas... | init = Attr(TCA_HTB_INIT,
HTBParms(rate, rate).pack() +
RTab(rate, mtu).pack() + CTab(rate, mtu).pack())
tcm = tcmsg(socket.AF_UNSPEC, self.interface.if_index, handle, self.qhandle, 0,
[Attr(TCA_KIND, 'htb\0'), init])
msg = ... | service_template=tcm)
self.conn.send(msg)
self.check_ack(self.conn.recv())
self.delete_root_qdisc()
def add_htb_qdisc(self):
tcm = tcmsg(socket.AF_UNSPEC, self.interface.if_index, self.qhandle, TC_H_ROOT, 0,
[Attr(TCA_KIND, 'htb\0'), HTBQdiscAtt... |
FreeCodeCampRoma/precision_school-management | precision/pages/apps.py | Python | mit | 122 | 0 | from django.apps import AppConfig
class PagesConfig(AppConfig):
| name = 'precision.pages'
verbose_name = "P | ages"
|
openego/ego.io | egoio/db_tables/demand.py | Python | agpl-3.0 | 6,745 | 0 | # coding: utf-8
from sqlalchemy import Column, Float, Integer, Numeric, String, Table, Text
from geoalchemy2.types import Geometry
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class EgoDemandFederalstate(Base):
__tablename__ = 'ego_demand_federalstate... | olumn(Float(53))
sector_count_residential = Column(Integer)
sector_count_retail = Column(Integer)
sector_count_industrial = Column(Integer)
sector_count_agricultural = Column(Integer)
sector_count_sum = Column(Integer)
sector_consumption_residential = Column(Float(53))
sector_consumption_ret... | _peakload_retail = Column(Float(53))
sector_peakload_residential = Column(Float(53))
sector_peakload_industrial = Column(Float(53))
sector_peakload_agricultural = Column(Float(53))
geom_centroid = Column(Geometry('POINT', 3035))
geom_surfacepoint = Column(Geometry('POINT', 3035))
geom_centre = C... |
0xalen/opencaster_isdb-tb | libs/dvbobjects/dvbobjects/utils/MJD.py | Python | gpl-2.0 | 1,057 | 0.011353 | #! /usr/bin/env python
# This file is part of the dvbobjects library.
#
# Copyright © 2005-2013 Lorenzo Pallara l.pallara@avalpa.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software F | oundation; either version 2 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
# MERCHANTABIL | ITY 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from math i... |
hipnusleo/laserjet | resource/pypi/cryptography-1.7.1/tests/hazmat/primitives/test_idea.py | Python | apache-2.0 | 2,825 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import os
import pytest
from cryptography.ha... | modes
from .utils import generate_encrypt_test
from ...utils import load_nist_vectors
@pytest.mark.supported(
only_if=lambda ba | ckend: backend.cipher_supported(
algorithms.IDEA(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support IDEA ECB",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeECB(object):
test_ECB = generate_encrypt_test(
load_nist_vectors,
os.... |
agiliq/fundraiser | authentication/forms.py | Python | bsd-3-clause | 626 | 0 | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models | import User
from django.utils.tra | nslation import ugettext_lazy as _
class RegistrationForm(UserCreationForm):
email = forms.EmailField(help_text='Enter a valid email address')
address = forms.CharField()
website = forms.URLField()
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects... |
bahattincinic/arguman.org | web/nouns/utils.py | Python | mit | 1,877 | 0 | # -*- coding:utf-8 -*-
import operator
import string
import operator
import itertools
import snowballstemmer
from textblob import TextBlob, Word
LOWER_MAP = {
'tr': {
ord('I'): u'ı'
}
}
STEMMERS = {
'en': snowballstemmer.stemmer('english'),
'tr': snowballstemmer.stemmer('turkish'),
}
def no... | .tokenize()
def get_synsets(text):
return Word(to_lemma(text)).synsets
def get_lemmas(text):
word = Word(to_lemma(text))
sets = map(set, [synset.lemma_names()
for synset in word.synsets])
return map(from_lemma, reduce(operator.or_, sets))
def to_lemma(text):
return text.r... | ord
return (stemmer
.stemWord(word)
.strip(string.punctuation))
def tokenize(wordlist, language, stem=True):
return ' '.join((stem_word(word, language) if stem else word)
for word in wordlist)
def lower(text, language):
if language in LOWER_MAP:
text ... |
rarmknecht/SimpleQuine | mkarray.py | Python | mit | 111 | 0.027027 | #!/usr/bin/python
file = open('prog.txt','r')
s = ""
| for b in file.read( | ):
s+="%d," % ord(b)
print(s[:-1])
|
avelino/Flask-Quik | tests/example.py | Python | mit | 315 | 0.003175 | from flask import Flask
from flask.ext.quik import FlaskQuik
from flask.ext.quik import render_template
app = Flask(__name__)
quik = FlaskQuik(app)
@app.route('/', methods=['GET', 'POST'] )
def hello_quik():
return render_template('hello.html', name='quik')
app.run(host='0.0.0.0', debug=True, po | rt=5000)
| |
qwergram/data-structures | src/test_linked_list.py | Python | mit | 5,503 | 0 | # -*- coding=utf-8 -*-
"""Test LinkedList for random inputs."""
import pyte | st
def test_linkedlist_tail_default():
"""Test LinkedList contstructor for functionality."""
from linked_list import LinkedList
assert LinkedList.tail is None
def test_linkedlist_construct_empty_list():
"""Test LinkedList insert command works with empty list."""
from linked_l | ist import LinkedList
input_ = []
linked_list_instance = LinkedList(input_)
assert linked_list_instance.tail is None
def test_linkedlist_construct_integer():
"""Test LinkedList insert command works with empty list."""
from linked_list import LinkedList
input_ = 5
linked_list_instance = Lin... |
marteinn/Skeppa | skeppa/ext/__init__.py | Python | mit | 400 | 0 | active_extensions = []
class Extension(object):
def register(self):
pass
def dispatch(event, *args, **kwargs):
for extension in active_extensions:
if not hasattr(extension, e | vent):
continue
getattr(extension, event)(*args, **kwargs)
def register(extension):
instance = extension()
active_extensions.append(instance)
| instance.register()
|
siyanew/Siarobo | plugins/soundcloud.py | Python | mit | 3,323 | 0.003912 | import asyncio
import demjson
from bot import user_steps, sender, get, downloader
from message import Message
client_id = ''#YOUR CLIENT ID
async def search(query):
global guest_client_id
search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c... | ard = {'hide_keyboard': True, 'selective': T | rue}
del user_steps[from_id]
return [Message(chat_id).set_text("*Not Found*",
reply_to_message_id=message['message_id'], reply_markup=hide_keyboard,
parse_mode="markdown")]
return [Message(chat_id... |
kcarnold/autograd | tests/test_complex.py | Python | mit | 1,428 | 0.016106 | from __future__ import absolute_import
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.util import *
from autograd import grad
npr.seed(1)
def test_real_type():
fun = lambda x: np.sum(np.real(x))
df = grad(fun)
assert type(df(1.0)) == float
assert type(df(1.0j)) == complex... | d_fun = lambda x: to_scalar(grad(fun)(x))
check_grads(fun, 1.1)
check_grads(d_fun, 2.1)
def test_abs_complex():
fun = lambda x : to_scalar(np.abs(x))
d_fun = lambda x: to_scalar(grad(fun)(x))
check_gra | ds(fun, 1.1 + 1.2j)
check_grads(d_fun, 1.1 + 1.3j)
|
amir343/ansible-modules-extras | network/f5/bigip_monitor_tcp.py | Python | gpl-3.0 | 16,428 | 0.006148 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, serge van Ginderachter <serge@vanginderachter.be>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either vers... | ip:
description:
- IP address part of the ipport defini | tion. The default API setting
is "0.0.0.0".
required: false
default: none
port:
description:
- port address part op the ipport definition. The default API
setting is 0.
required: false
default: none
interval:
description:
... |
unchartedsoftware/PLUTO | src/rules/validateFilename.py | Python | apache-2.0 | 1,114 | 0.027828 | from __future__ import print_function
import os.path
import re
import imp
import sys
from shutil import copyfile
import PythonAPI as api
class ValidateFilename(api.PythonAPI | Rule):
def __init__(self, config):
super(ValidateFilename, self).__init__(config)
def run(self, inputFile, outputFile, encoding):
# NOTE: dot syntax doesn't work for dereferencing fields on self.config because the properties are defined using UTF-8 strings.
if not "regex" in self.config:
self.error("No re... | ")
elif not "file" in self.config["importConfig"]:
self.error("No file specified in the rule config.importConfig.")
else:
filename = os.path.basename(self.config["importConfig"]["file"])
prog = re.compile(self.config["regex"], re.UNICODE)
if prog.match(filename) is None:
self.error(filename + " does... |
smellman/sotmjp-website | docs/conf.py | Python | bsd-3-clause | 8,580 | 0.007459 | # -*- coding: utf-8 -*-
#
# Pinax Symposion documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 5 17:31:13 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | x', u'Pinax Symposion Documentation',
u'Eldarion Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true,... | show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for ma... |
ooovector/qtlab_replacement | tunable_coupling_transmons/Misis_two_qubit_July_2019_setup.py | Python | gpl-3.0 | 12,967 | 0.003915 | from qsweepy.instruments import *
from qsweepy import *
from qsweepy import awg_iq_multi
import numpy as np
device_settings = {'vna_address': 'TCPIP0::10.20.61.48::inst0::INSTR',
'lo1_address': 'TCPIP0::10.20.61.59::inst0::INSTR',
'lo1_timeout': 5000, 'rf_switch_address': '10.20... | litude': 0.8,
'hdawg_ch4_amplitude': 0.8,
'hdawg_ch5_amplitude': 0.8,
'hdawg_ch6_amplitude': 0.8,
'hdawg_ch7_amplitude': 0.8,
'awg_tek_ch1_amplitude': 1.0,
'awg_tek_ch2_amplitude': 1.0,
'... | 'awg_tek_ch4_amplitude': 1.0,
'awg_tek_ch1_offset': 0.0,
'awg_tek_ch2_offset': 0.0,
'awg_tek_ch3_offset': 0.0,
'awg_tek_ch4_offset': 0.0,
'lo1_freq': 3.41e9,
'pna_freq': 6.07e9,
... |
hinnerk/py-djbdnslog | src/djbdnslog/scripts/__init__.py | Python | bsd-3-clause | 197 | 0.015228 | import sys
def check_args(argv | ):
if len(argv) != 2:
print ("Help:\n"
"%s filename.log\n"
"filename.log = name of logfile") % argv[0]
sys.e | xit(1)
|
pythonitalia/pycon_site | p3/management/commands/partner_events.py | Python | bsd-2-clause | 1,898 | 0.002634 | # -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils im... | f, time))
for sch in models.Schedule.objects.filter(conference=conference):
events = | list(models.Event.objects.filter(schedule=sch))
for fare, time in partner_events[sch.date]:
track_id = 'f%s' % fare.id
for e in events:
if track_id in e.get_all_tracks_names():
event = e
break
... |
rorito/django-squeezemail | squeezemail/management/commands/run_steps_task.py | Python | mit | 197 | 0 | f | rom django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
f | rom squeezemail.tasks import run_steps
run_steps.delay()
|
procool/mygw | globals/utils/server/http_client.py | Python | bsd-2-clause | 1,122 | 0.017825 | import json
from urllib2 import urlopen, HTTPError
from urllib import urlencode
import logging
class HTTPClient(object):
def __init__(self, host='localhost', port=90):
self.host = host
self.port = port
def get_serv_addr (self):
return 'http://%s:%s/' % ( self.host, self.port, )
... | dler)
try: postdata = kwargs.pop('postdata')
except: postdata=None
for arg in args:
url += '%s/' % arg
params = urlencode(kwargs)
url = '%s?%s'% (url, params)
| logging.debug("Request url: %s" % url)
try: response = urlopen(url, postdata)
except HTTPError as err:
raise(err)
except:
return None
## Reading data:
try:
response = response.read()
except:
return None
... |
airbnb/airflow | airflow/contrib/hooks/gcp_container_hook.py | Python | apache-2.0 | 1,567 | 0.002553 | #
# 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... | `."""
def __init__(self, *args, **kwargs):
warnings.warn(
"This class is deprecated. Please use `airflow.providers.google.cloud.hooks.container.GKEHook`.",
DeprecationWarning,
stacklevel=2,
)
super() | .__init__(*args, **kwargs)
|
Smashman/mods.tf | app/utils/utils.py | Python | gpl-3.0 | 11,564 | 0.002248 | import ntpath
import os
import s | team
import zipfile
import shutil
from subprocess import check_call, CalledProcessError
from flask import flash, current_app, abort
from PIL import Image
from io import BytesIO
from werkzeug.u | tils import secure_filename
from ..tf2.models import all_classes, TF2BodyGroup, TF2EquipRegion
from ..mods.models import ModClassModel, ModImage
from ..models import get_or_create
from app import db, sentry
def list_from_vdf_dict(dictionary):
return_list = []
for dict_item, number in dictionary.items():
... |
tempbottle/elliptics | tests/pytests/test_session_parameters.py | Python | lgpl-3.0 | 7,542 | 0.000928 | # =============================================================================
# 2013+ Copyright (c) Kirill Smorodinnikov <shaitkir@gmail.com>
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | r(session, prop) == value
@pytest.mark.parametrize('prop, setter, getter, values', [
('groups', 'set_groups', 'get_groups', (
[],
range(1, 100),
range(1, 100000),
range(10, 10000))),
('cflags', 'set_cflags', 'get_cflags', command_flags),
('iof... | licy', 'set_exceptions_policy',
'get_exceptions_policy', tuple(exceptions_policy) + (
elliptics.exceptions_policy.throw_at_start |
elliptics.exceptions_policy.throw_at_wait,
elliptics.exceptions_policy.throw_at_start |
elliptics.exceptions_policy.throw_at_wa... |
wogsland/QSTK | build/lib.linux-x86_64-2.7/QSTK/qstkutil/qsdateutil.py | Python | bsd-3-clause | 9,008 | 0.01099 | '''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
Created on Jan 1, 2011
@author:Drew Bratcher
@contact: dbratcher@gatech.edu
@summary: Contains tutorial for backteste... | ear in years)):
years.append(date.year)
return(years)
def getMonths(funds,year):
months=[]
for date in funds.index:
if((date.year==year) and not(date.month in months)):
months.append(date.month)
return(months)
def getDays(funds,year,month):
days=[]
for date in f... | r i in range(0,(ts_end-ts_start).days):
days.append(ts_start+timedelta(days=1)*i)
return(days)
def getFirstDay(funds,year,month):
for date in funds.index:
if((date.year==year) and (date.month==month)):
return(date)
return('ERROR')
def getLastDay(funds,year,month):
return_da... |
gabrielhurley/django-block-comment | block_comment/models.py | Python | bsd-3-clause | 2,966 | 0.001011 | '''Custom models for the block_comment app.'''
import difflib
from django.contrib.comments.models import Comment
from django.db import models
from django.utils.translation import ugettext as _
from block_comment.diff_match_patch import diff_match_patch
class BlockComment(Comment):
'''
``BlockComment`` exten... | smarter matching algorithm.
matcher = diff_match_patch()
for i in tuple(matches):
if matcher.match_main(blocks[i], needle, self.index) < 0:
# No match, discard this option
matches.remove(i)
# Unless we've... | ck_index = matches[0]
if block_index:
return get_block_index(block_index)
# If we can't find anything, return -1
return -1
def relink_comment(self, haystack, save=True):
index = self.get_match_index(haystack)
if index == self.index:
... |
charlesll/RamPy | legacy_code/IR_dec_comb.py | Python | gpl-2.0 | 6,585 | 0.027183 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 07:54:05 2014
@author: charleslelosq
Carnegie Institution for Science
"""
import sys
sys.path.append("/Users/charleslelosq/Documents/RamPy/lib-charles/")
import csv
import numpy as np
import scipy
import matplotlib
import matplotlib.gridspec as gridspec
from pylab ... | software of Matt Newville, CARS, university of Chicago, available on the web
from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit, fit_report
from spectratools import * #Charles' libraries and functions
from Tkinter import *
import tkMessageBox
from tkFileDialog import askopenfilename
#### We d... | of functions that will be used for fitting data
#### unfortunatly, as we use lmfit (which is convenient because it can fix or release
#### easily the parameters) we are not able to use arrays for parameters...
#### so it is a little bit long to write all the things, but in a way quite robust also...
#### gaussian and... |
rwightman/pytorch-image-models | timm/models/sknet.py | Python | apache-2.0 | 8,742 | 0.004004 | """ Selective Kernel Networks (ResNet base)
Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586)
This was inspired by reading 'Compounding the Performance Improvements...' (https://arxiv.org/abs/2001.06268)
and a streamlined impl at https://github.com/clovaai/assembled-cnn but I ended up building somet... | =norm_layer, aa_layer=aa_layer)
width = int(math.floor(planes * (base_width / 64)) * cardinality)
first_planes = width // reduce_first
outplanes = planes * self.expansion
first_dilation = first_dilation or dilation
self.conv1 = ConvBnAct(inplanes, first_planes, kernel_size=1, **... | _planes, width, stride=stride, dilation=first_dilation, groups=cardinality,
**conv_kwargs, **sk_kwargs)
conv_kwargs['act_layer'] = None
self.conv3 = ConvBnAct(width, outplanes, kernel_size=1, **conv_kwargs)
self.se = create_attn(attn_layer, outplanes)
self.act = act_layer(inp... |
a1fred/git-barry | gitbarry/reasons/__init__.py | Python | mit | 177 | 0 | from gitbarry.rea | sons import start, f | inish, switch # , switch, publish
REASONS = {
'start': start,
'finish': finish,
'switch': switch,
# 'publish': publish,
}
|
theguardian/LazyLibrarian_Old | lazylibrarian/notifiers/tweet.py | Python | gpl-3.0 | 5,477 | 0.012416 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/lazylibrarian/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 ... | token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(key)
logger.info('Generating and signing request for an access token using | key '+key)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable
oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
logger.info('oauth_consumer: '+str(oauth_consumer))
oauth_client = oauth.Client(oauth_consumer,... |
arbakker/yt-daemon | search_yt.py | Python | mit | 380 | 0.005263 | import urllib
import urllib2
from bs4 import BeautifulSoup
textToSearch = | 'gorillaz'
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
print 'https://www.youtube.com' + vid['href' | ]
|
trungdtbk/faucet | tests/generative/integration/mininet_tests.py | Python | apache-2.0 | 17,678 | 0.001923 | #!/usr/bin/env python3
import random
import unittest
import networkx
from mininet.topo import Topo
from clib.mininet_test_watcher import TopologyWatcher
from clib.mininet_test_base_topo import FaucetTopoTestBase
class FaucetFaultToleranceBaseTest(FaucetTopoTestBase):
"""
Generate a topology of the given pa... | self.debug_log_path else None,
'hardware': 'Open vSwitch'
})
if i in stack_roots:
dp_options[i]['stack'] = {'priority': stack_roots[i]}
vlan_options = {}
routers = {}
if self.NUM_VLANS >= 2:
# Setup options for routing
| routers = {0: list(range(self.NUM_VLANS))}
for i in range(self.NUM_VLANS):
vlan_options[i] = {
'faucet_mac': self.faucet_mac(i),
'faucet_vips': [self.faucet_vip(i)],
'targeted_gw_resolution': False
}
... |
denis-vilyuzhanin/selenium-fastview | py/test/selenium/webdriver/common/element_attribute_tests.py | Python | apache-2.0 | 12,180 | 0.00312 | #!/usr/bin/python
#
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "Li... | .get_attribute("selected") is None, "false")
self.assertTrue(initiallyNotSelected.get_at | tribute("selected") is None, "false")
self.assertEqual("true", initiallySelected.get_attribute("selected"), "true")
initiallyNotSelected.click()
self.assertTrue(neverSelected.get_attribute("selected") is None)
self.assertEqual("true", initiallyNotSelected.get_attribute("selected"))
... |
MissionCriticalCloud/marvin | marvin/cloudstackAPI/listVPCOfferings.py | Python | apache-2.0 | 5,265 | 0.002279 | """Lists VPC offerings"""
from baseCmd import *
from baseResponse import *
class listVPCOfferingsCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "false"
"""list VPC offerings by display text"""
self.displaytext = None
self.typeInfo['displaytext'] = 'string'
... |
self.physicalnetworkid = None
""""services for this provider"""
self.servicelist = None
""""state of the network provider"""
self.state = None
class service:
def __init__(self):
""""the service name"" | "
self.name = None
""""the list of capabilities"""
self.capability = []
""""can this service capability value can be choosable while creatine network offerings"""
self.canchooseservicecapability = None
""""the capability name"""
self.name = None
""""the ca... |
pscedu/slash2-stable | slash2/utils/tsuite2/managers/ion.py | Python | isc | 1,513 | 0.017184 | from managers import sl2gen
from utils.ssh import SSH
from paramiko import SSHException
import sys
import logging
log = logging.getLogger("sl2.ion")
def launch_ion(tsuite):
"""Launch ION daemons.
Args:
tsuite: tsuite runtime."""
gdbcmd_path = tsuite.conf["slash2"]["ion_gdb"]
sl2gen.launch_gdb_sl(tsuite,... | = dict(tsuite.src_dirs, **tsuite.build_dirs)
repl_dict = dict(repl_dict, **ion)
#Create remote connection to server
try:
user, host = tsuite.user, ion["host"]
log.debug("Connecting to {0}@{1}".format(user, host))
ssh = SSH(user, host, '')
cmd = """
mkdir -p {datadir}
mk... | {fsroot}
{slmkfs} -Wi -u {fsuuid} -I {site_id} {fsroot}"""\
.format(**repl_dict)
sock_name = "ts.ion."+ion["id"]
sl2gen.sl_screen_and_wait(tsuite, ssh, cmd, sock_name)
log.info("Finished creating {0}!".format(ion["name"]))
ssh.close()
except SSHException, e:
log.fatal(... |
remond-andre/discord-wow-armory-bot-modified | tests.py | Python | mit | 12,125 | 0.00833 | import unittest
from constants import *
from wow import *
from util import *
class BaseTest(unittest.TestCase):
def test_for_normal_query_split(self):
# Tests to ensure that the query gets split properly when the bot gets a message.
# Example query: '!armory pve/pvp <name> <realm> <region>'
... | roperly when the bot gets a url based message.
# Example query: '!armory pve/pvp <armory-link> <region>' (Accepts either a world of warcraft or battle net link)
sample_wow_url = '!armory pve https://worldofwarcraft.com/en-us/character/burning-legion/jimo us'
sam | ple_battlenet_url = '!armory pve http://us.battle.net/wow/en/character/burning-legion/jimo/advanced us'
self.assertEqual(split_query(sample_wow_url, 'pve'), ['jimo', 'burning-legion', 'pve', 'us'])
self.assertEqual(split_query(sample_battlenet_url, 'pvp'), ['jimo', 'burning-legion', 'pvp', 'us'])
... |
superstack/nova | nova/db/sqlalchemy/migration.py | Python | apache-2.0 | 3,168 | 0 | # 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... | eptions as versioning_exceptions
except ImportError:
sys.exit(_("python-migrate is not installed. Exiting."))
FLAGS = flags.FLAGS
def db_sync(version=None):
db_version()
repo_path = _find_migrate_repo()
return versioning_api.upgrade(FLA | GS.sql_connection, repo_path, version)
def db_version():
repo_path = _find_migrate_repo()
try:
return versioning_api.db_version(FLAGS.sql_connection, repo_path)
except versioning_exceptions.DatabaseNotControlledError:
# If we aren't version controlled we may already have the database
... |
robmcmullen/peppy | peppy/third_party/aui/framemanager.py | Python | gpl-2.0 | 360,518 | 0.00593 | # --------------------------------------------------------------------------- #
# AUI Library wxPython IMPLEMENTATION
#
# Original C++ Code From Kirix (wxAUI). You Can Find It At:
#
# License: wxWidgets license
#
# http:#www.kirix.com/en/community/opensource/wxaui/about_wxaui.html
#
# Current wxAUI Version Tracked: ... | specified
by this variable.
**Position** - More than one pane can be placed inside of a "dock". Imagine two panes
being docked on the left side of a window. One pane can be placed over another.
In proportionally managed docks, the pane position indicates it's sequential position,
starting with zero. So, in our scenar... | left side, the
top pane in the dock would have position 0, and the second one would occupy position 1.
**Row** - A row can allow for two docks to be placed next to each other. One of the most
common places for this to happen is in the toolbar. Multiple toolbar rows are allowed,
the first row being in row 0, and the s... |
raffo85h/projecteuler | 87. Prime power triples.py | Python | gpl-2.0 | 692 | 0.027457 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 15:52:33 2014
@auth | or: raffaelerainone
"""
from time import clock
from math import sqrt
def is_prime(n):
check=True
i=2
while check and i<=sqrt(n):
if n%i==0:
check=False
i+=1
return check
start = clock()
lim=50*(10**6)
A=[]
prime_2 = [i for i in range(2,int(lim**(0.5))) if is_prime(i)]
... |
for i in prime_2:
for j in prime_3:
for k in prime_4:
x=(i**2)+(j**3)+(k**4)
if x<lim:
A.append(x)
print len(set(A))
print clock() - start |
StellarCN/py-stellar-base | stellar_sdk/xdr/transaction_result.py | Python | apache-2.0 | 2,928 | 0 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .int64 import Int64
from .transaction_result_ext import TransactionResultExt
from .transaction_result_result import TransactionResul... | void;
}
result;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
"""
def __init__(
self,
fee_charged: Int64,
result: TransactionResultRes... | ult
self.ext = ext
def pack(self, packer: Packer) -> None:
self.fee_charged.pack(packer)
self.result.pack(packer)
self.ext.pack(packer)
@classmethod
def unpack(cls, unpacker: Unpacker) -> "TransactionResult":
fee_charged = Int64.unpack(unpacker)
result = Tra... |
buhe/judge | executors/RUBY19.py | Python | agpl-3.0 | 407 | 0.002457 | import os
from .ruby import RubyExecutor
class Exe | cutor(RubyExecutor):
name = 'RUBY19'
def get_nproc(self):
return [-1, 1][os.name == 'nt']
def get_security(self):
from cptbox.syscalls import sys_write
sec = super(Executor, self).get_security()
sec[sys_write] = lambda debugger: debugger.arg0 in (1, 2, 4)
r | eturn sec
initialize = Executor.initialize
|
gonicus/gosa | plugins/goto/conftest.py | Python | lgpl-2.1 | 496 | 0.002016 | import pytest
from | gosa.common import Environment
from gosa.common.components import PluginRegistry, ObjectRegistry
import os
def pytest_unconfigure(config):
PluginRegistry.getInstance('HTTPService').srv.stop()
PluginRegistry.shutdown()
@pytest.fixture(scope="session", autouse=True)
def use_test_config():
oreg = ObjectReg... | stance("CommandRegistry") # @UnusedVariable
|
conejoninja/pelisalacarta | python/version-xbmc-09-plugin/core/config.py | Python | gpl-3.0 | 5,454 | 0.018532 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# Gestión de parámetros de configuración - xbmc
#------------------------------------------------------------
# tvalacarta
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#--------------------------------------------------------... | ty( "system.platform.windows" ):
platform = "windows"
elif xbmc.getCondVisibility( "system.platform.osx" ):
platform = "osx"
return platform
def open_settings():
xbmcplugin.openSettings( sys.argv[ 0 ] )
def get_setting(name):
return xbmcplugin.getSetting(name)
def set_setting(name... | ept:
pass
def get_localized_string(code):
dev = xbmc.getLocalizedString( code )
try:
dev = dev.encode ("utf-8") #This only aplies to unicode strings. The rest stay as they are.
except:
pass
return dev
def get_library_path():
#return os.path.join( get_data_path(), ... |
KonradMagnusson/PyPLOG | __init__.py | Python | mit | 285 | 0.010526 | import plog.plog as plg
PLOG = plg.PLOG
plog_col | or = plg.plog_color
plog = plg | .plog
def perr(*msg, delim=" "):
plog(*msg, type=PLOG.err, delim=delim)
def pwrn(*msg, delim=" "):
plog(*msg, type=PLOG.warn, delim=delim)
__all__ = ["PLOG", "plog_color", "plog", "perr", "pwrn"]
|
j5shi/Thruster | pylibs/sqlite3/test/regression.py | Python | gpl-2.0 | 12,067 | 0.001243 | #-*- coding: iso-8859-1 -*-
# pysqlite2/test/regression.py: pysqlite regression tests
#
# Copyright (C) 2006-2007 Gerhard Häring <gh@ghaering.de>
#
# This file is part of pysqlite.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for ... | memory:",detect_types=sqlite.PARSE_DECLTYPES)
con.execute("create table foo(bar timestamp)")
con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),))
con.execute(SELECT)
con.execute("drop table foo")
con.execute("create table foo(bar integer)")
con... | def CheckRegisterAdapter(self):
"""
See issue 3312.
"""
self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
def CheckSetIsolationLevel(self):
"""
See issue 3312.
"""
con = sqlite.connect(":memory:")
self.assertRaises(... |
UnknownStudio/Codeic | ScratchPlus/kurt/doc/conf.py | Python | mpl-2.0 | 10,130 | 0.00849 | # -*- coding: utf-8 -*-
#
# Kurt documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 29 16:09:55 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | he document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Kurt', u'Kurt Documentation',
u'Tim Radvan', 'K | urt', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# --... |
anmekin/django-httplog | test_app/urls.py | Python | bsd-3-clause | 405 | 0.004938 | # coding: utf-8
try | :
from django.conf.urls import patterns, url, include
except ImportError:
from django.conf.urls.defaults import patterns, url, include
from django.http import HttpResponse
def dummy(request):
return HttpResponse()
urlpatterns = patterns('',
url('^api/.+/$', dummy, name='dummy'),
url('', include(... | pp_name='auth', namespace='auth'))
)
|
WatsonDNA/nlp100 | chap05/k44.py | Python | unlicense | 343 | 0 | #
# usage: pyth | on k44.py {file name} {number}
#
import sys
import pydot
from k41 import *
from k42 import get_relation_pairs
if __name__ == '__main__':
fn, nos = sys.argv[1], int(sys.argv[2])
sl = load_cabocha(fn)
pl = get_relation_pairs([sl[nos-1]])
g = | pydot.graph_from_edges(pl)
g.write_png('result.png', prog='dot')
|
pantsbuild/pants | src/python/pants/backend/scala/subsystems/scala.py | Python | apache-2.0 | 1,433 | 0.004187 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache L | icense, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from pants.option.option_types import DictOption
from pants.opt | ion.subsystem import Subsystem
DEFAULT_SCALA_VERSION = "2.13.6"
_logger = logging.getLogger(__name__)
class ScalaSubsystem(Subsystem):
options_scope = "scala"
help = "Scala programming language"
_version_for_resolve = DictOption[str](
"--version-for-resolve",
help=(
"A dicti... |
larsks/pydonet | lib/pydonet/construct/formats/filesystem/fat12.py | Python | gpl-2.0 | 86 | 0 | """
File Allocation Table (FAT | ) / 12 bit version |
Used primarily for diskettes
"""
|
DreamSourceLab/DSView | libsigrokdecode4DSL/decoders/a7105/pd.py | Python | gpl-3.0 | 12,297 | 0.002114 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2020 Richard Li <richard.li@ces.hk>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the Lice... | 'Cmd {}'.format(self.cmd)
def parse_command(self, b):
'''Parses the command byte.
Returns a tuple consisting of:
- the name of the command
- additional data needed to dissect the following bytes
- minimum number of following bytes
- maximum number of following byte... |
if b == 0x06:
return ('W_ID', None, 1, 4)
elif b == 0x46:
return ('R_ID', None, 1, 4)
elif (b & 0b10000000) == 0:
if (b & 0b01000000) == 0:
c = 'W_REGISTER'
else:
c = 'R_REGISTER'
d = b & 0b00111111
... |
gizas/CSS_Extractor | replace.py | Python | mit | 580 | 0.017241 | #This script is for produsing a new list of sites e | xtracted from alexa top site list
import re
prefix = 'http://'
#suffix = '</td><td></td></tr><tr><td>waitForPageToLoad</td><td></td><td>3000</td></tr>'
with open('top100_alexa.txt','r') as f:
newlines = []
for line in f.readlines():
found=re.sub(r'\d+', '', line)
line=found
newlines.ap... | ') as f:
for line in newlines:
#f.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))
f.write('%s%s\n' % (prefix, line.rstrip('\n'))) |
nvoron23/tarantool | test/lib/admin_connection.py | Python | bsd-2-clause | 2,482 | 0.000403 | __author__ = "Konstantin Osipov <kostja.osipov@gmail.com>"
# 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. Redistributions in binary form must reproduce 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# AN... |
tbenthompson/LMS_public | lms_code/analysis/just_detach_bem.py | Python | mit | 846 | 0.002364 | import lms_code.lib.rep2 as rep2
from lms_code.analysis.run_bem import bemify, boundary_conditions,\
assemble, constrain, solve, evaluate_surface_disp
from lms_code.analysis.simplified_bem import create_surface | _mesh, \
set_params
from codim1.core import simple_line_mesh, combine_meshes, ray_mesh
def create_fault_mesh(d):
top_fault_vert = [0, -1e9]
top = d['intersection_pt']
joint = [4.20012e5 + 1.6, -2.006e4 - 5]
bottom = [3.09134e5 + 1.1, -2.3376e4 - 3]
detach = simple_line_mesh(d['fault_elements'],... | create_surface_mesh(d)
bemify(d)
boundary_conditions(d)
assemble(d)
# constrain(d)
solve(d)
evaluate_surface_disp(d)
rep2.save("bem_just_detach", d)
|
pandeydivesh15/AVSR-Deep-Speech | DeepSpeech_RHL.py | Python | gpl-2.0 | 72,056 | 0.005551 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
import sys
log_level_index = sys.argv.index('--log_level') + 1 if '--log_level' in sys.argv else 0
os.environ['TF_CPP_MIN_LOG_LEVEL'] = sys.argv[log_level_index] if log_level_index > 0 and log_leve... | False, 'wether to log device placement of the operators to the console')
tf.app.flags.DEFINE_integer ('report_count', 10, 'number of phrases with lowest WER (best matching) to print out during a WER report')
tf.app.flags.DEFINE_string ('summary_dir', '', 'target directory for TensorB... | mmaries" within user\'s data home specified by the XDG Base Directory Specification')
tf.app.flags.DEFINE_integer ('summary_secs', 0, 'interval in seconds for saving TensorBoard summaries - if 0, no summaries will be written')
# Geometry
tf.app.flags.DEFINE_integer ('n_hidden', 2048, 'lay... |
sam-m888/gramps | gramps/gen/filters/rules/place/_hasnolatorlon.py | Python | gpl-2.0 | 1,902 | 0.005783 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | treet, Fifth Floor, Boston, MA 02110-1301 USA.
#
# gen.filters.rules/Place/_HasNoLatOrLon.py
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocal... | ----------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-------------------------------------------------------------------------
#
# HasNoLatOrLon
#
#------------------------------------------------------------------------... |
nighres/nighres | nighres/surface/levelset_curvature.py | Python | apache-2.0 | 4,723 | 0.002117 | import os
import numpy as np
import nibabel as nb
import nighresjava
from ..io import load_volume, save_volume
from ..utils import _output_dir_4saving, _fname_4saving
def levelset_curvature(levelset_image, distance=1.0,
save_data=False, overwrite=False, output_dir=None,
... | return output
# load the data
lvl_img = load_volume(levelset_image)
lvl_data = lvl_img.get_data()
hdr = lvl_img.header
aff = lvl_img.affine
resolution = [x.item() for x in hdr.get_zooms()]
dimensions = lvl_data.shape
# algorithm
# start virtual machine, if not already r... | pass
# create algorithm instance
algorithm = nighresjava.LevelsetCurvature()
# set parameters
algorithm.setMaxDistance(distance)
# load images and set dimensions and resolution
input_image = load_volume(levelset_image)
data = input_image.get_data()
affine = input_image.get_affine(... |
zmcartor/Algorithms | Python/better_inversion_count.py | Python | mit | 485 | 0.012371 | # based on killer algo found here:
# http://codereview.stackexchange.com/questions/12922/inversion-count-using-merge-sort
import sys, bisec | t
input_list = map(int,open(sys.argv[1]))
sorted_list = sorted(input_list)
inversions = 0
# we compare the unsorted list to the sorted list
# to compute inversion count, neat!
for d in input_list:
#locate insertion point in sorted_list for d
p = bisect.bisect_left(sorted_list,d)
inversions += p
input_lis... | pop(p)
print inversions
|
butterscotchstallion/SpiffyRPG | SpiffyRPG/SpiffyWorld/models/unit_dialogue.py | Python | mit | 1,421 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class UnitDialogue:
"""
Unit dialogue model
"""
def __init__(self, **kwargs):
self.db = kwargs["db"]
self.dialogue = {}
def _get_unit | _dialogue_map(self, dialogue):
unit_dialogue_map = {}
for unit_dialogue in dialogue:
unit_id = unit_dialogue["unit_id"]
if unit_id not in unit_dialogue_map:
unit_dialogue_map[unit_id] = []
unit_dialogue_map[unit_id].append(un | it_dialogue["dialogue_id"])
return unit_dialogue_map
def get_unit_dialogue(self):
"""
Get unit dialogue IDs. Those will be queried
against the dialogue collection to get the rest
of the dialogue information
"""
cursor = self.db.cursor()
cursor.execu... |
marceloomens/appointments | appointments/apps/common/views.py | Python | mit | 7,355 | 0.007886 | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... | form.is_valid():
email = form.cleaned_data['email']
try:
user = User.objects.get(email=email)
date = timezon | e.now().date()
appointments = user.appointments.filter(date__gte=date)
send_reminder(user, appointments)
except User.DoesNotExist:
pass
messages.success(request, _("We'll send you an e-mail with all your appointments."))
... |
habanero-rice/hclib | test/performance-regression/full-apps/qmcpack/nexus/library/superstring.py | Python | bsd-3-clause | 11,640 | 0.029639 |
'''
superstring
a collection of functions to manipulate strings
general purpose
next_visible_character
remove_whitespace
shrink_whitespace
var2string
string2array
is_string
stringmap
stringbreak
find_matching_brace
remove_comment_lines
contains_any
contains_all
... | if
return (vis_char,vis_loc)
#end def next_visible_characte | r
def remove_whitespace(s):
sr = s.replace('\n','').replace('\t','').replace(' ','')
return
#end def remove_whitespace
def shrink_whitespace(si):
sw = si.strip().replace('\n','')
lst = sw.split(' ')
s = ''
for t in lst:
if(t!=''):
s += t+' '
#end if
#end for
... |
Solid-Mechanics/matplotlib-4-abaqus | matplotlib/sphinxext/plot_directive.py | Python | mit | 27,667 | 0.002205 | """
A directive for including a matplotlib plot in a Sphinx document.
By default, in HTML output, `plot` will include a .png file with a
link to a high-res .png and .pdf. In LaTeX output, it will include a
.pdf.
The source code for the plot may be included in one of three ways:
1. **A path to a source file** as t... | yplot as plt
from matplotlib import _pylab_helpers
__version__ = 2
#------------------------------------------------------------------------------
# Relative pathnames
#------------------------------------------------------------------------------
# os.path.relpath is new in Python 2.6
try:
from os.path import r... | r:
# Copied from Python 2.7
if 'posix' in sys.builtin_module_names:
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
pardir
if not path:
... |
jonparrott/botocore | botocore/hooks.py | Python | mit | 10,052 | 0 | # Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 limitation the rights to u... | (func3, 'bar')]))
# This will print 'foo'
:type responses: list of tuples
:param responses: The responses from the ``EventHooks.emit`` method.
This is a list of tuples, and each tuple is
(handler, handler_response).
:param default: If no non-None responses are found, then this ... | nse[1] is not None:
return response[1]
return default
class BaseEventHooks(object):
def emit(self, event_name, **kwargs):
return []
def register(self, event_name, handler):
self._verify_is_callable(handler)
self._verify_accept_kwargs(handler)
self._register(eve... |
kbuschme/irony-detection | setup.py | Python | gpl-3.0 | 301 | 0.009967 | # -*- coding: utf-8 -*-
from __future__ import print_function
from nltk import do | wnload
TOKENIZER_MODEL = "punkt"
POS_TAGGER = "maxent_treebank_pos_tagger"
def downloadDependencies():
download(TOKENIZER_MODEL)
download(POS_TAGGER)
if __name__ == '__main__ | ':
downloadDependencies()
|
coreycb/charms.openstack | charms_openstack/plugins/__init__.py | Python | apache-2.0 | 1,179 | 0 | # Copyright 2019 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Pull in helpers that 'charms_openstack.plugins'... | import (
BaseOpenStackCephCharm,
CephCharm,
PolicydOverridePlugin,
)
from charms_openstack.plugins.trilio import (
TrilioVaultCharm,
TrilioVaultSubordinateCharm,
TrilioVaultCharmGhostAction,
)
__all__ = (
"BaseOpenStackCephCharm",
"CephCharm",
"CephRelationAdapter",
"PolicydOve... |
aeklant/scipy | scipy/stats/_rvs_sampling.py | Python | bsd-3-clause | 7,080 | 0.000141 | import numpy as np
import warnings
from scipy._lib._util import check_random_state
def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None):
"""
Generate random samples from a probability density function using the
ratio-of-uniforms method.
Parameters
----------
pdf : cal... | rt(f(0)), -v_bound, v_bound
>>> np.random.seed(12345)
>>> rvs = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=2500)
The K-S test confirms that the random variates are indeed normally
distributed (normality is not rejected at 5% significance level):
>>> stats.kstest(rvs, 'norm')[1]
0.34201... | np.random.seed(12345)
>>> rvs = stats.rvs_ratio_uniforms(lambda x: np.exp(-x), umax=1,
... vmin=0, vmax=2*np.exp(-1), size=1000)
>>> stats.kstest(rvs, 'expon')[1]
0.928454552559516
Sometimes it can be helpful to use a non-zero shift parameter `c`, see e.g.
[2]_ ab... |
karan259/GrovePi | Software/Python/grove_thumb_joystick.py | Python | mit | 3,278 | 0.003661 | #!/usr/bin/env python
#
# GrovePi Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask... | all be included in
all cop | ies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLA... |
google/upvote_py2 | common/ng_template.py | Python | apache-2.0 | 1,657 | 0.01026 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/ | LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri | ting, 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.
"""Invokes html2js and appends goog.provide.
https://www.... |
FrodeSolheim/fs-uae-launcher | amitools/vamos/libcore/create.py | Python | gpl-2.0 | 3,188 | 0.008783 | from amitools.vamos.astructs import LibraryStruct
from amitools.vamos.atypes import Library, NodeType
from amitools.fd import read_lib_fd, generate_fd
from .vlib import VLib
from .stub import LibStubGen
from .patch import LibPatcherMultiTrap
from .impl import LibImplScanner
class LibCreator(object):
"""create a vam... | ne, lib_cfg=None, check=False):
name = info.get_name()
if name.endswith('.device'):
is_dev = True
elif name.endswith('.library'):
is_dev = False
else:
raise ValueError("create_lib: %s is neither lib nor dev!" % name)
# get fd: either read from fd or fake one
fd = read_lib_fd(na... | ke_fd(name, lib_cfg)
# if impl is available scan it
scan = None
if impl:
scanner = LibImplScanner()
if check:
scan = scanner.scan_checked(name, impl, fd, True)
else:
scan = scanner.scan(name, impl, fd, True)
# add profile?
if self.profiler:
# get some impl inf... |
akhilaananthram/nupic.research | sound_encoder/live_sound_encoding_demo.py | Python | gpl-3.0 | 2,476 | 0.011712 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | ,\
| data))*window
def visualizeSDRs(sdrs):
sdrsToVisualize = []
for sdr in sdrs:
sdrsToVisualize.append([255 if x else 0 for x in sdr])
imageArray = np.rot90(np.array(sdrsToVisualize))
plt.imshow(imageArray, cmap='Greys', interpolation='nearest')
plt.show()
def recordAnd... |
sio2project/filetracker | filetracker/tests/interaction_test.py | Python | gpl-3.0 | 7,181 | 0.000418 | """Integration tests for client-server interaction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from multiprocessing import Process
import os
import shutil
import tempfile
import time
import unittest
from filetracker.client import Client, Filetracke... | f.assertEqual(f.read(), | b'hello streams')
def test_big_files_should_be_handled_correctly(self):
# To be more precise, Content-Length header should be
# set to the actual size of the file.
src_file = os.path.join(self.temp_dir, 'big.txt')
with open(src_file, 'wb') as sf:
sf.write(b'r')
... |
zozo123/buildbot | master/buildbot/test/unit/test_db_migrate_versions_021_fix_postgres_sequences.py | Python | gpl-3.0 | 2,676 | 0.000747 | # This file is part of Buildbot. Buildbot 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.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | nto each table, giving an explicit id column so
# that the sequence is not advanced correctly, but leave no rows in
# one table to test that corner case
for i, col in enumerate(self.cols):
tbl_name, col_name = col.split('.')
tbl = sa.Table(tbl_name, me... | sa.Column(col_name, sa.Integer, primary_key=True))
tbl.create()
if i > 1:
conn.execute(tbl.insert(), {col_name: i})
def verify_thd(conn):
metadata = sa.MetaData()
metadata.bind = conn
# try inserting *without* an... |
dmlc/tvm | tests/python/topi/python/test_topi_qnn.py | Python | apache-2.0 | 6,744 | 0.001779 | # 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 u... | output.
tvm.testing.assert_allclose(dq.numpy(), real_dq_out.numpy().astype("float32"), rtol=1e-5)
for target, dev in tvm.testing.enabled_targets():
check_target(target, dev)
def test_simulated_dequantize():
verify_simulated_dequantize([1], "int8", [1], -1)
verify_simulated_dequantize([2, ... | ted_dequantize([1, 32, 32, 32], "uint8", [32], -2)
verify_simulated_dequantize([2, 5], "int32", [5], 1)
if __name__ == "__main__":
test_simulated_quantize()
test_simulated_dequantize()
|
sckott/pygbif | test/test-registry-datasets.py | Python | mit | 952 | 0 | """Tests for registry module - datasets method"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_datasets.yaml")
def test_datasets():
"registry.datasets - basic test"
res = registry.datasets()
assert dict == res.__class__
@vcr.use_cassette("test/vcr_cassettes/test_data... | ults"])
res = registry.datasets(limit=3)
assert dict == res.__class__
assert 3 == len(res["results"]) |
@vcr.use_cassette("test/vcr_cassettes/test_datasets_type.yaml")
def test_datasets_type():
"registry.datasets - type param"
res = registry.datasets(type="OCCURRENCE")
vv = [x["type"] for x in res["results"]]
assert dict == res.__class__
assert 100 == len(res["results"])
assert "OCCURRENCE" == ... |
seankelly/buildbot | master/buildbot/test/integration/test_configs.py | Python | gpl-2.0 | 9,493 | 0.000316 | # This file is part of Buildbot. Buildbot 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.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | with comments stripped. Adjustments made
# for compatibility are marked with comments
sample_0_7_6 = """\
c = BuildmasterConfig = {}
from buildbot.buildslave import BuildSlave
c['slaves'] = [BuildSlave("bot1name", "bot1passwd")]
c['slaveP | ortnum'] = 9989
from buildbot.changes.pb import PBChangeSource
c['change_source'] = PBChangeSource()
from buildbot.scheduler import Scheduler
c['schedulers'] = []
c['schedulers'].append(Scheduler(name="all", branch=None,
treeStableTimer=2*60,
builderName... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.