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 |
|---|---|---|---|---|---|---|---|---|
iLotus/googleads-adsensehost-examples | django-quickstart/blog/association.py | Python | apache-2.0 | 1,452 | 0 | #!/usr/bin/env python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | rt AssociationSession
import api_utils
def start_association(user):
"""Uses the API to start a new association session, and stores it."""
service = api_utils.initialize_service()
result = service.associationsessions().start(
productCode='AFC',
websiteUrl='www.examplehost.com/blog/%s' % user.na... | rify_association(token):
"""Uses the API to verify an association session token."""
service = api_utils.initialize_service()
result = service.associationsessions().verify(token=token).execute()
return result
|
VitalPet/bank-statement-reconcile | account_statement_operation_rule/tests/__init__.py | Python | agpl-3.0 | 1,004 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | se, 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 Aff | ero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_rule_rounding
from ... |
enjalot/adventures_in_opencl | experiments/radix/nv/radix.py | Python | mit | 9,590 | 0.009281 | #http://documen.tician.de/pyopencl/
import pyopencl as cl
import numpy as np
import struct
import timing
timings = timing.Timing()
#ctx = cl.create_some_context()
mf = cl.mem_flags
class Radix:
def __init__(self, max_elements, cta_size, dtype):
self.WARP_SIZE = 32
self.SCAN_WG_SIZE = 256
... | % divisor + divisor,)
local_size = (self.SCAN_WG_SIZE, )
scan_args = ( self.scan_buffer,
dst,
src,
| cl.LocalMemory(2 * self.SCAN_WG_SIZE * self.uintsz),
np.uint32(elements),
np.uint32(size)
)
self.scan_prg.scanExclusiveLocal2(self.queue, global_size, local_size, *(scan_args)).wait()
@timings("Scan: update")
def scan_update... |
AOtools/soapy | setup.py | Python | gpl-3.0 | 1,308 | 0.003058 |
import platform
from setuptools import setup, find_packages
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = 'soapy/_version.py'
versioneer.versionfile_build = 'soapy/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'soapy-' # dirname like 'myproject... | 15.0",
"astrop | y >= 1.0",
"aotools >= 1.0",
"pyfftw >= 0.12.0",
"pyyaml >= 5.1.1",
"numba >= 0.40"
],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python... |
tudinfse/fex | experiments/nginx/plot.py | Python | mit | 735 | 0 | import logging
import numpy as np
from core import prepare
from core i | mport draw
BENCH_NAME = 'nginx'
EXP_NAME = BENCH_NAME
COMPILER_NAME = "long"
def main(t="perf"):
logging.info("Processing data")
df = prepare.process_results(t)
if t == "tput":
prepare.reorder_compilers(df, t)
plot = draw.LinePlotTput()
plot.get_data(df, [])
plot.build_plo... | 100, 10),
ylim=(0.1, 0.8),
yticks=np.arange(0.2, 0.79, 0.1),
legend_loc=(0.01, 0.45),
figsize=(5, 2.5),
)
plot.save_plot("%s_%s.pdf" % (BENCH_NAME, t))
else:
logging.error("Unknown plot type")
exit(-1)
|
kedz/cuttsum | trec2015/sbin/l2s/cor.py | Python | apache-2.0 | 320 | 0 | import pandas a | s pd
with open("ssize.100.spe.10.l2.0.iters.5.fltr/summaries.tsv", "r") as f:
df = pd.read_csv(f, sep="\t")
df = df[df["run"] == "L2S.F1"]
print df[["partial", "confidence"]].corr("pearson")
print df[["partial", "confidence"]].corr("spearman")
print df[["partial", "confidence"]]. | corr("kendall")
|
dyegocantu/pingo-py | pingo/intel/tests/test_galileo.py | Python | mit | 1,476 | 0 | import unittest
import pingo
from pingo.test import level0
from pingo.test import level1
from pingo.detect import check_board
running_on_galileo = check_board(pingo.intel.Galileo2)
class GalileoTest(unittest.TestCase):
def setUp(self):
self.board = pingo.intel.Galileo2()
# Level0 Parameters
... | pin = self.board.pins[self.digital_output_pin_number]
assert isinstance(pin, pingo.DigitalPin)
data_pins = len(self.board.pins)
assert data_pins == self.total_pins
@unittest.skipIf(not running_on_galileo, 'Galileo not detected')
class GalileoExceptions(GalileoTest, level0.BoardExceptions):... | , 'Galileo not detected')
class GalileoAnalogRead(GalileoTest, level1.AnalogReadBasics):
pass
@unittest.skipIf(not running_on_galileo, 'Galileo not detected')
class GalileoAnalogExceptions(GalileoTest, level1.AnalogExceptions):
pass
if __name__ == '__main__':
unittest.main()
|
foxtrotmike/pairpred | getBSR.py | Python | gpl-3.0 | 1,525 | 0.028197 | # -*- coding: utf-8 -*-
"""
Created | on Thu Jan 31 16:47:23 2013
@author: root
"""
from dbdscrpp3 import *
import itertools
import matplotlib.pyplot as plt
# import pdb
if __name__=="__main__":
| fname='../Results/result_tppk.res.pkl'
pdbpklpath='../PDBPKLP3'
(auc,(fp,tp),(A,Rx,Dx,Lx,cids,r,dkey))=getAUC(fname)
Mv=np.zeros(len(cids))
Mv.fill(np.nan)
Mvtpr=np.zeros(len(cids))
Mvtpr.fill(np.nan)
for (i,cid) in enumerate(cids):
d=Dx[i]
l=np.array(Lx[i])
(c,... |
DevinZ1993/Code-Cupboard | java/demos/hadoop/gen_data.py | Python | mpl-2.0 | 959 | 0.006257 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import random
import os
import subprocess
if __name__=='__main__':
HADOOP_PATH = "/usr/share/hadoop"
DICT_PATH = "/usr/share/dict/words"
DATA_DIR = os.path.dirname(os.path.realpath(__file__))
OUT_PATH = os.path.join(DATA_DIR, "wordcount.in")
vocab = ... | ICT_PATH, 'r')
line = din.readline()
while len(line)>0:
vocab.append(line[:-1])
line = din.readline() |
din.close()
fout = open(OUT_PATH, 'w')
for i in range(random.randint(10000,20000)):
for j in range(random.randint(100, 1000)):
fout.write(vocab[random.randint(0, len(vocab)-1)]+" ")
fout.write(vocab[random.randint(0, len(vocab)-1)]+"\n")
fout.close()
subprocess.call(... |
endlessm/chromium-browser | native_client/pynacl/run_pynacl_tests.py | Python | bsd-3-clause | 757 | 0.002642 | #!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run all python tests in this directory."""
import sys
import unitte | st
MODULES = [
'directory_storage_test',
'gsd_storage_test',
'hashing_tools_test',
'local_storage_cache_test',
]
# We use absolute imports for Py3 compatibility.
# This means for imports to resolve when testing we need to add the pynacl
# directory to the module search path.
sys.path.insert(0, './')
... | nittest.TestLoader().loadTestsFromNames(MODULES)
result = unittest.TextTestRunner(verbosity=2).run(suite)
if result.wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/email/charset.py | Python | unlicense | 14,131 | 0.005237 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: charset.py
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec']
import codecs
import email.base64mime
import email.quoprimime
from ema... | c-jp',
'euc_kr': 'euc-kr',
'ascii': 'us-ascii'
}
CODEC_MAP = {'gb2312': 'eucgb2312_cn',
'big5': 'big5_tw',
'us-ascii': None
}
def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
"""Add character set properties to the global registry.
charset is the input charac... |
quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
is only valid for header_enc. It describes how message headers and
message bodies in the input charset are to be encoded. Default is no
encoding.
... |
joopert/home-assistant | homeassistant/components/starline/__init__.py | Python | apache-2.0 | 2,876 | 0.002434 | """The StarLine component."""
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from .account import StarlineAccount
from .const import (
DOMAIN,
PLATFORMS,
SERVICE_UPDA... | nc def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up the StarLine device from a config entry."""
account = StarlineAccount(hass, config_entry)
await account.update()
if not account.api.available:
raise ConfigEntryNotReady
if DOMAIN not in hass.d | ata:
hass.data[DOMAIN] = {}
hass.data[DOMAIN][config_entry.entry_id] = account
device_registry = await hass.helpers.device_registry.async_get_registry()
for device in account.api.devices.values():
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, **acco... |
alexykot/bitfund | bitfund/project/views/__init__.py | Python | gpl-3.0 | 288 | 0.003472 | from bitfund.project.views.budget_view import *
from bitfund.project.views.budget_crud import *
from bitfund.project.views.claims import *
from bitfund.project.views.goals import | *
from bitfund.project.views | .charts import *
from bitfund.project.views.budget_ajax_logo_upload import * |
simonz05/activity-feed | tests/test_utility.py | Python | mit | 886 | 0.002257 | # -*- coding: utf-8 -*-
import unittest
from activity_feed import ActivityFeed
class UtilityTest(unittest.TestCase):
def test_key(self):
'should return the correct key for the non-aggregate feed'
a = ActivityFeed()
self.assertEquals(a.feed_key('david'), 'activity_feed:david')
def tes... | e:david')
def test_feederboard_for(self):
'should create a leaderboard using an ex | isting Redis connection'
a = ActivityFeed()
feederboard_david = a.feederboard_for('david')
feederboard_person = a.feederboard_for('person')
self.assertEqual(feederboard_david is None, False)
self.assertEqual(feederboard_person is None, False)
|
PragmaticMates/django-flatpages-i18n | flatpages_i18n/migrations/0002_auto_20200619_1344.py | Python | bsd-3-clause | 630 | 0.003175 | # Generated by Django 2.2.4 on 2020-06-19 11:44
from django.db import migrations, models
import martor.models
class Migration(migrations.Migration | ):
dependencies = [
('flatpages_i18n', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='flatpage_i18n',
name='content',
field=martor.models.MartorField(blank=True, verbose_name='content'),
),
migrations.AlterField(
... | ),
]
|
google-research/disentanglement_lib | disentanglement_lib/utils/aggregate_results.py | Python | apache-2.0 | 2,233 | 0.007613 | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... | uld be aggregated (e.g. /tmp/*/r | esults/aggregate/evaluation.json).
output_path: String with path to output json file (e.g. /tmp/results.json).
"""
logging.info("Loading the results.")
model_results = _get(result_file_pattern)
logging.info("Saving the aggregated results.")
with gfile.Open(output_path, "w") as f:
model_results.to_json... |
acumb/LatticeDNAOrigami | scripts/simutils/select_starting_configs.py | Python | mit | 1,850 | 0.000541 | #!/usr/bin/env python3
"""Select starting configs for each US window"""
import argparse
import pdb
import sys
import random
import copy
from origamipy.op_process import read_ops_from_file
from origamipy.op_process import sort_by_ops
from origamipy.origami_io import *
from origamipy.us_process import create_win_filen... | config_file = PlainTextTrajOutFile(win_filename)
config_file.write_config(traj_file.chai | ns(config), 0)
if __name__ == '__main__':
main()
|
etherkit/OpenBeacon2 | client/win/venv/Lib/site-packages/PyInstaller/hooks/hook-matplotlib.py | Python | gpl-3.0 | 599 | 0.003339 | #--------------------------------------------------------- | --------------------
# Copyright (c) 2013-2019, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------... | _path())")
datas = [
(mpl_data_dir, "mpl-data"),
]
|
nkouevda/slack-rtm-bot | slack_rtm_bot/settings_local.py | Python | mit | 305 | 0 | import logging
import os |
API_TOKEN = os.environ.get('SLACK_RTM_BOT_API_TOKEN')
LOG_FILE = None
LOG_FORMAT = '%(asctime)s: %(levelname)s: %(message)s'
LOG_LEVEL = logging.INFO
READ_INTERVAL_SECONDS = 1.0
# OwnerHandler
CHANN | EL_OWNERS = {}
# ReactionHandler
EMOJI_REACTIONS = {}
MESSAGE_REACTIONS = {}
|
yuewko/neutron | neutron/plugins/bigswitch/routerrule_db.py | Python | apache-2.0 | 1,500 | 0 | # Copyright 2013, Big Switch Networks
# 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 requ... | tionship('NextHop', cascade='all,delete')
action = sa.Column(sa.String(10), nullable=False)
router_id = sa.Column(sa.String(36),
sa.ForeignKey('routers.id',
ondelete="CASCADE"))
class NextHop(model_base.BASEV2):
rule_id = sa.Column(sa.Integ... | sa.ForeignKey('routerrules.id',
ondelete="CASCADE"),
primary_key=True)
nexthop = sa.Column(sa.String(64), nullable=False, primary_key=True)
|
crazybiocomputing/align2seq | matrix/parserEDNA.py | Python | gpl-2.0 | 1,539 | 0.040286 | "This pr | ogram will parse matrix files to convert them into objects usable by JS files"
# libraries' imports for create the parser
## librairy to create the json object
import json
import os
## library for using regular expressions
import re
# opening of all files, each containing an EDNA matrix
EDNAFULL=open("EDNA/EDNAFULL.t... | ixEDNA.json","w")
#creation of the beginning of the file
mat.write("matrixEDNA=")
mat.write("{")
test=os.listdir("./EDNA")
print test
def parserEDNA(matrix1,name):
#reading of the matrix file, line by line
matrix=[]
content= matrix1.read()
lines= content.split("\n")
#for each line, delete spaces, write the matrix... |
HaroldMills/Vesper | vesper/util/detection_score_file_writer.py | Python | mit | 3,438 | 0.007563 | """Module containing `DetectionScoreFileWriter` class."""
import wave
import numpy as np
import vesper.util.signal_utils as signal_utils
class DetectionScoreFileWriter:
"""
Writes a wave file containing detector audio input in one channel
and detection scores in another.
"""
def... | x:end_index]
scores = scores[start_index:end_index]
# Stack samples and scores to make two "audio" channels.
samples = np.vstack((samples, scores))
# Interleave channel samples and convert to bytes.
data = samples.transpose | ().tobytes()
self._writer.writeframes(data)
self._samples_start_index += num_samples
def close(self):
self._writer.close()
|
rperier/linux | Documentation/translations/conf.py | Python | gpl-2.0 | 345 | 0.014493 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-2.0
# -- Additinal options for LaTeX output ------------------------------ | ----
# font config for ascii-art alignment
latex_elements['preamble'] += '''
\\IfFontExistsTF{Noto Sans CJK SC}{
% For CJK ascii-art alignment
\\setmonofont{Noto Sans Mono CJK SC}[AutoFakeSlant]
| }{}
'''
|
redhat-openstack/neutron | neutron/agent/securitygroups_rpc.py | Python | apache-2.0 | 16,600 | 0.000301 | # Copyright 2012, Nachi Ueno, NTT MCL, 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
#
# Unles... | return self.call( | context,
self.make_msg('security_group_rules_for_devices',
devices=devices),
version='1.1')
def security_group_info_for_devices(self, context, devices):
LOG.debug("Get security group information for devices via rpc %r"... |
IfcOpenShell/IfcOpenShell | src/ifcopenshell-python/ifcopenshell/api/material/add_profile.py | Python | lgpl-3.0 | 1,359 | 0.000736 | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat... | ngs[key] = value
def execute(self):
profiles = list(self.settings["profile_set"].MaterialProfiles or [])
profile = self.file.create_entity("IfcMaterialProfile", **{"Material": self.settings["material"]})
profiles.append(profile)
self.settings["profile_set"].MaterialProfiles = profil... | rn profile
|
nellaG/kanban-gallen | kanban_gallen/settings.py | Python | bsd-2-clause | 299 | 0 | #!/usr/bin/env python
# vim: fileencoding=utf-8 tabsto | p=2 softtabstop=2 shiftwidth=2 expandtab
""" settings.py """
# address binding
HOST = '127.0.0.1'
PORT = '5000'
# logger nam | e
LOGGER_NAME = 'kanban-gallen'
# database location setting
SQLALCHEMY_DATABASE_URI = 'sqlite:///../db/database.db'
|
matsjoyce/sandypython | tests/test_getsattr.py | Python | gpl-3.0 | 841 | 0.001189 | import unittest
from sandypython.spec import getsattr
from sandypython.core import add_default_builtins, reset
from sandypython.utils import ActivateSandbox
class TestGetsattr(unittest.TestCase):
def setUp(self) | :
add_default_builtins()
def test_getsattr(self):
def f():
pass
F = f.__class__
with ActivateSandbox():
x = getsattr(f, "__class__")
self.assertEqual(F, x)
self.assertEqual(F, getsattr(f, "__class__"))
with self.assertRaises(AttributeE... | self.assertEqual(F, getsattr(f, "_class__"))
with ActivateSandbox():
print(type(f).__dict__)
x = getsattr(f, "__code__")
self.assertEqual(f.__code__, x)
def tearDown(self):
reset()
tg = TestGetsattr()
tg.setUp()
tg.test_getsattr()
|
boisde/Greed_Island | business_logic/order_collector/transwarp/log.py | Python | mit | 6,028 | 0.002003 | #!/usr/bin/env python
# coding:utf-8
"""
只在单进程时正确工作.
"""
import os
import re
import sys
import time
import shutil
import logging
from logging.handlers import RotatingFileHandler
VERSION = "1.0.0"
def init_log(mod_dir):
logging_msg_format = '[%(asctime)s] [%(levelname)s] [%(module)s] %(message)s'
logging_date... | ]
return result
def doRollover(self):
if self.stream:
self.stream.close()
self.stream = None
# get the tim | e that this sequence started at and make it a TimeTuple
if self.utc:
time_tuple = time.gmtime()
else:
time_tuple = time.localtime()
dfn = self.baseFilename + "." + time.strftime(self.suffix, time_tuple)
if os.path.exists(dfn):
os.remove(dfn)
# ... |
pauljohnleonard/pyo-loris | src/ORIG/pyoLorisSynth2.py | Python | gpl-2.0 | 4,683 | 0.036302 | import loris, os, time
from pyo import *
import math
s = Server().boot()
spc_file="../samples/clarinet.aiff.spc"
# All the oscillators can share a noise generator ?
# Seems to work OK I can not hear any artifacts
white = Noise()
# low pass filter the noise cutoff=500Hz
# (loris uses 4 forward and 4 ... | se:
t=1
ampToneList.append((t,0))
ampNoiseList.append((t,0))
freqList.append((t,f))
t=int(t_sec *sr)
ampTone = a*math.sqrt( 1. - bw )
ampNoise = a*math.sqrt( 2. * bw ) ;
... |
# terminate the modulation lists
t=int((t_sec+fade)*sr)
ampToneList.append((t,0))
ampNoiseList.append((t,0))
freqList.append((t,f))
if t >=size :
print t , size
dur=float(size)/sr
ampNoise... |
hewentian/python-learning | src/python27/functional_programming/sorted.py | Python | apache-2.0 | 506 | 0.003953 | # -*- coding: utf-8 -*-
print sorted([36, 5, 12, 9, 21])
def reversed_cmp(x, y):
if x > y:
return -1
elif x == y:
return 0
else:
return 1
print sorted([36, 5, 12, 9, 21], reversed_cmp)
print sorted(['bob', 'about', 'Zoo', 'Credit'])
def cmp_ignore_case(s1, s2):
u1 = s1.uppe... | s2.upper()
if u1 > u2:
return 1
elif u1 < | u2:
return -1
else:
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
|
Kotti/kotti_contactform | kotti_contactform/__init__.py | Python | bsd-2-clause | 1,603 | 0.001248 | from deform import Form
from pkg_resources import resource_filename
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('kotti_contactform')
def kotti_configure(settings):
settings['pyramid.includes'] += ' kotti_contactform'
settings['kotti.available_types'] += (
' kotti_co... | c-kotti_contactform',
'kotti_contactform:static')
config.scan()
settings = config.get_settings()
if settings.get('kotti_contactform.asset_overrides') is not None:
for override in [a.strip()
for a in settings['kotti_contactform.asset_overrides'].sp... | override_asset(to_override='kotti_contactform', override_with=override)
|
Tesora/tesora-python-troveclient | troveclient/tests/osc/v1/test_database_flavors.py | Python | apache-2.0 | 1,636 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | tabase_flavors.ListDatabaseFlavors(self.app, None)
self.data = [self. | fake_flavors.get_flavors_1()]
self.flavor_client.list.return_value = self.data
def test_flavor_list_defaults(self):
parsed_args = self.check_parser(self.cmd, [], [])
columns, values = self.cmd.take_action(parsed_args)
self.flavor_client.list.assert_called_once_with()
self.as... |
sirmmo/osm-tper-importer | get_files.py | Python | unlicense | 5,117 | 0.028728 | import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import math
import requests
from bs4 import BeautifulSoup
import csv, urllib2
import shapefile
import os.path
import itertools
def dist(x1, y1, x2, y2):
return math.sqrt(math.pow(abs(x2-x1),2)+math.pow(abs(y2-y1),2))
base = "https://solweb.tper.it/web/tools/o... | ,",".")))
upd_csv.writerow(fer_stop)
done_refs.append(fer_stop["codice"])
elif dist(float(osm_stop["lon"]),float(osm_stop["lat"]), float(fer_stop["longitudine"].replace(",",".")), float(fer_stop["latitudine" | ].replace(",","."))) < radius:
#print "magic!!!", dist(float(osm_stop["lon"]),float(osm_stop["lat"]), float(fer_stop["longitudine"].replace(",",".")), float(fer_stop["latitudine"].replace(",",".")))
man_csv.writerow(fer_stop)
done_refs.append(fer_stop["codice"])
for fer_stop in fer_list:
if ... |
vikalpindia/vikalp | vikalp/migrations/0019_auto__chg_field_articlecategory_category_long_description__chg_field_a.py | Python | apache-2.0 | 14,436 | 0.007758 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'ArticleCategory.category_long_description'
db.alter_co... | rue'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'blogposts'", 'to': u"orm['auth.User']"})
},
u'comments.comment': {
'Meta': {'ordering': "('submit_date',)", | 'object_name': 'Comment', 'db_table': "'django_comments'"},
'comment': ('django.db.models.fields.TextField', [], {'max_length': '3000'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'content_type_set_for_comment'", 'to': u"orm['contenttypes.ContentType']"... |
MusculoskeletalAtlasProject/mapclient | src/mapclient/view/managers/package/packagemanagerdialog.py | Python | gpl-3.0 | 3,052 | 0.002294 | """
MAP Client, a program to generate detailed musculoskeletal models for OpenSim.
Copyright (C) 2012 University of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Li... | 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 MAP Client. If not, see <http://www.gnu.org/licenses/>..
"""
import os
from PySide2 import QtWidgets
from mapclient.view.managers.package.ui.ui_packagemanagerdialog import Ui_PackageManagerDialog
class PackageManagerDialog(QtWidgets.QDialog):
"""
Dialog for ... |
Aravinthu/odoo | odoo/tools/parse_version.py | Python | agpl-3.0 | 3,532 | 0.008777 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
## this functions are taken from the setuptools package (version 0.6c8)
## http://peak.telecommunity.com/DevCenter/PkgResources#parsing-utilities
from __future__ import print_function
import re
from odoo.tools import p... | ce.
The returned value will be a tuple of strings. Numeric portions of the
version are padded to 8 digits so they will compare numerically, but
without relying on how numbers compare relative to strings. Dots are
dropped, but dashes are retained. Trailing zeros between alpha segments
or dashes a... | pha string that
alphabetically follows "final" represents a "patch level". So, "2.4-1"
is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
considered newer than "2.4-1", whic in turn is newer than "2.4".
Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
co... |
jonahbull/rabbitpy | tests/message_tests.py | Python | bsd-3-clause | 19,295 | 0.000156 | # -*- coding: utf-8 -*-
"""
Test the rabbitpy.message.Message class
"""
import datetime
import json
import logging
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
import uuid
import mock
from pamqp import body
from pamqp import header
from pamqp import specification
from ra... | str(uuid.uuid4()),
{'timestamp': ['Ohai']})
class TestCreationWithNoneTimestamp(BaseTestCase):
def setUp(self):
super(TestCreationWithNoneTimestamp, self).setUp()
self.msg = message.Message(self.chan, str(uuid.uuid4()),
... | ne(self.msg.properties['timestamp'])
class TestCreationWithStrTimestamp(BaseTestCase):
def setUp(self):
super(TestCreationWithStrTimestamp, self).setUp()
self.msg = message.Message(self.chan, str(uuid.uuid4()),
{'timestamp': str(int(time.time()))})
def test... |
polde-live/pyml | pyml/test/a1_test.py | Python | unlicense | 2,112 | 0.007576 | import unittest
import assignment1 as a1
from sklearn.neighbors import KNeighborsClassifier
class Test_a1_test(unittest.TestCase):
def test_answer1(self):
cancer = a1.answer_one()
self.assertEqual(cancer.index._start, 0)
self.assertEqual(cancer.index._stop, 569)
colnames = ['me... | nn, KNeighborsClassifier)
def test_answer6(self):
self.assertFalse('not implemented | ')
def test_answer7(self):
self.assertTupleEqual(a1.answer_seven().shape, (143,))
def test_answer8(self):
self.assertFalse('not implemented')
if __name__ == '__main__':
unittest.main()
|
ehelms/Opus | opus/lib/prov/deltacloud_old/transition.py | Python | apache-2.0 | 1,356 | 0.001475 | ##############################################################################
# | Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# Y... | se at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or a... |
axeMaltesse/Python-related | Learning-Python/Battleship.py | Python | mit | 1,406 | 0.012091 | #importing | randint
from random import randint
#creating an empty list
board = []
#filling up the list by O and creating a two dimensionall array
for x in range(5):
board.append(["O"] * 5)
#printing function which also includes a spaces to show clear grid
def print_board(board):
for row in board:
print " ".join(... | ant more than 1 ship
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
#remembering the ship
ship_row = random_row(board)
ship_col = random_col(board)
#game loop
for turn in range(4):
guess_row = int(raw_input("Guess Row:"))
guess_co... |
svamp/rp_management | characters/migrations/0012_auto_20160212_1210.py | Python | gpl-3.0 | 1,712 | 0.004089 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('characters', '0011_auto_20160212_1144'),
]
operations = [
migrations.CreateModel(
name='CharacterSpells',
... | igrations.AlterModelOptions(
name='spellinfo',
options={ | 'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'},
),
migrations.AddField(
model_name='spellinfo',
name='name',
field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'),
),
migrations.AlterField(
... |
chair6/bandit | examples/mark_safe.py | Python | apache-2.0 | 102 | 0 | from django.utils import safestring
mystr = '<b>Hel | lo World</b>'
mystr = safestring.m | ark_safe(mystr)
|
ollej/shoutbridge | src/plugins/KraetyzPlugin.py | Python | mit | 2,235 | 0.004478 | # -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
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 use,... | handler='send_warning',
onevents=[ | 'Message'],
onsender = ['Kraetyz'],
textmatch = 'jag tycker',
text = u"/me bannar %s för uttryckande av åsikt.",
),
]
def send_warning(self, shout, command, comobj):
"""
Parse message body and send message with dice roll.
"""
if shout.... |
nealtodd/django-taggit | taggit/migrations/0002_auto_20150616_2121.py | Python | bsd-3-clause | 383 | 0 | # -*- coding: utf- | 8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
]
operations = [
migrations.AlterIndexTogether(
name='taggeditem',
index_toget | her=set([('content_type', 'object_id')]),
),
]
|
suoto/hdlcc | hdl_checker/parser_utils.py | Python | gpl-3.0 | 12,665 | 0.000553 | # This file is part of HDL Checker.
#
# Copyright | (c) 2015 - 2019 suoto (Andre Souto)
#
# HDL Checker 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, eithe | r version 3 of the License, or
# (at your option) any later version.
#
# HDL Checker 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 ... |
zstackio/zstack-woodpecker | integrationtest/vm/virt_plus/capacity/test_expunge_vm_ps_capacity_by_query.py | Python | apache-2.0 | 2,590 | 0.009266 | '''
New Integration Test for expunging KVM VM and check capacity by QueryPrimaryStorage.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as ... | out' : 200,
'noparallel' : True
}
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
delete_policy = None
def test():
global delete_policy
delete_policy = test_lib.lib_set_delete_policy('vm', 'Delay')
test_util.test_dsc('Test storage capacity whe... | ions('state', '=', 'Enabled')
cond = res_ops.gen_query_conditions('status', '=', 'Connected', cond)
host = res_ops.query_resource_with_num(res_ops.HOST, cond, limit = 1)
if not host:
test_util.test_skip('No Enabled/Connected host was found, skip test.' )
return True
ps = res_ops.... |
fmartingr/django-routes | manage.py | Python | gpl-2.0 | 254 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "routes.test_settings")
from | django.core.management import execute_from_command | _line
execute_from_command_line(sys.argv)
|
manusev/plugin.video.kuchitv | resources/tools/loadtxt_ftv.py | Python | gpl-2.0 | 4,888 | 0.009219 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# MonsterTV EPG FórmulaTV.com
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
#------------------------------------------------------------
# Gracias a la librería plugintools de Jesús (www.mimediacenter.info)
#-------------... |
evento = plugintools.find_multiple_matches(schedule, '<div class="prg-item"(.*?)<p class="subtit">')
for entry in evento:
#plugintools.log("entry= "+entry)
event_time = plugintools.find_single_match(entry, '<div class="prg-hour"><p>(.*?)</p>')
if event_time != "":
... | ch(entry, '<p class="tit">[^>]+>(.*?)</p>')
if event_title == "":
event_title = plugintools.find_single_match(entry, '<p class="tit">(.*?)</p>')
event_title = event_title.replace("</a>", "")
file_epg.write('[B]'+event_time+'[/B] '+event_title+'\n')
... |
albemala/almoviesrenamer | src/ui/movie_table_item.py | Python | gpl-3.0 | 671 | 0.00149 | from PyQt5.QtCore import QObject, pyqtProperty
class MovieTableItem(QObject):
def __init__(self, original_name, new_name, parent=None):
super().__init__(parent)
self.__original_name = original_name
self.__new_name = new_name
@pyqtProperty('QString', constant=True)
def orig | inal_name(self):
return self.__original_name
@original_name.setter
def | original_name(self, original_name):
self.__original_name = original_name
@pyqtProperty('QString', constant=True)
def new_name(self):
return self.__new_name
@new_name.setter
def new_name(self, new_name):
self.__new_name = new_name |
xmaruto/mcord | xos/tosca/tests/observerUserTest.py | Python | apache-2.0 | 2,957 | 0.004735 | from observertest import BaseObserverToscaTest
from core.models import Site, Deployment, User, ControllerUser
# Note that as a side effect, these tests will also create a Site
class ObserverUserTest(BaseObserverToscaTest):
tests = ["create_user"]
# hide_observer_output = False # uncomment to display lots of ... | testsite")
def assert_nouser(self, email):
assert(not User.objects.filter(email=email))
def assert_user(self, e | mail, **kwargs):
obj = User.objects.get(email=email)
assert(obj)
for (k,v) in kwargs.items():
if (getattr(obj,k,None) != v):
print "Object %s property '%s' is '%s' and should be '%s'" % (obj, k, getattr(obj,k,None), v)
assert(False)
return obj
... |
freedomtan/workload-automation | wlauto/result_processors/notify.py | Python | apache-2.0 | 2,244 | 0.000891 | # Copyright 2015 ARM Limited
#
# 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.
#
import collections
import sys
from wlauto import ResultProcessor
from wlauto.core.result import IterationResult
from wlauto.exceptions import ResultProcessorError
try:
import notify2
except ImportError:
notify2 = None
class NotifyProcessor(Resul... |
TomNeyland/err | errbot/backends/campfire.py | Python | gpl-3.0 | 4,600 | 0.002174 | import logging
import sys
from errbot.backends.base import Message, build_message, Identifier
from errbot.errBot import ErrBot
from threading import Condition
log = logging.getLogger(__name__)
try:
import pyfire
except ImportError:
log.exception("Could not start the campfire backend")
log.fatal("""
I... | type_='groupchat') # it is always a groupchat in campfire
msg.frm = user + '@' + message.room.get_data()['name'] + '/' + user
msg.to = self.jid # assume it | is for me
self.callback_message(msg)
def error_callback(self, error, room):
log.error("Stream STOPPED due to ERROR: %s in room %s" % (error, room))
self.exit_lock.acquire()
self.exit_lock.notify()
self.exit_lock.release()
def join_room(self, room, username=None, pa... |
jgroszko/django-albums | albums/migrations/0011_drop_old_slug.py | Python | gpl-3.0 | 7,471 | 0.009102 |
from south.db import db
from django.db import models
from albums.models import *
class Migration:
def forwards(self, orm):
# Deleting field 'AlbumItem.slug'
db.delete_column('albums_albumitem', 'slug')
def backwards(self, orm):
# Adding field '... | ', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'M | eta': {'unique_together': "(('content_type', 'codename'),)"},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.A... |
SecurityInnovation/PGPy | pgpy/types.py | Python | bsd-3-clause | 25,400 | 0.003386 | """ types.py
"""
from __future__ import division
import abc
import base64
import binascii
import bisect
import codecs
import collections
import operator
import os
import re
import warnings
import weakref
from enum import EnumMeta
from enum import IntEnum
import six
from .decorators import sdproperty
from .errors i... | m['body'] = bytearray(base64.b64decode(m['body'].encode | ()))
except (binascii.Error, TypeError) as ex:
six.raise_from(PGPError(str(ex)), ex)
if m['crc'] is not None:
m['crc'] = Header.bytes_to_int(base64.b64decode(m['crc'].encode()))
if Armorable.crc24(m['body']) != m['crc']:
warnings.warn('Incorr... |
retooth/morse | morse/models/bans.py | Python | gpl-3.0 | 7,601 | 0.006052 | #!/usr/bin/python
# This file is part of Morse.
#
# Morse is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Morse ... | :
""" an integer that signifies the number of hours
left to serve (only possible on limited bans)
!!! this attribute DOES NOT signify the absolute
| number of hours left, but rather the numbers of
hours left modulo 24
"""
if self.is_permanent:
raise TypeError("this method is not available on permanent bans")
seconds = self.time_left.seconds
return seconds // 60**2
@property
def minutes_left (self):
... |
silviacanessa/oq-hazardlib | openquake/hazardlib/mfd/evenly_discretized.py | Python | agpl-3.0 | 3,967 | 0 | # The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
... | onstraints:
* Bin width is positive.
* Occurrence rates list is not empty.
* Each number in occurrence rates list is non-negative.
* Minimum magnitude is positive.
"""
if not self.bin_width > 0:
raise ValueError('bin width must be positive')
if not s... |
if not all(value >= 0 for value in self.occurrence_rates):
raise ValueError('all occurrence rates must not be negative')
if not any(value > 0 for value in self.occurrence_rates):
raise ValueError('at least one occurrence rate must be positive')
if not self.min_mag >= 0... |
dionyziz/ting | API/chat/tests/__init__.py | Python | mit | 100 | 0 | from chat.t | ests.message import *
from chat.tests.channel imp | ort *
from chat.tests.test_url import *
|
geertj/bluepass | tests/test_validate.py | Python | gpl-3.0 | 5,373 | 0.000186 | #
# This file is part of Bluepass. Bluepass is Copyright (c) 2012-2014
# Geert Jansen.
#
# Bluepass is free software available under the GNU General Public License,
# version 3. See the file LICENSE distributed with this file for the exact
# licensing terms.
from __future__ import absolute_import, print_function
impo... | def test_all_errors(self):
obj = {'foo': 10, 'bar': 10}
fmt = '{foo: str, bar: str}'
vres = validate(obj, fmt)
self.assertEqual(len(vres.er | rors), 1)
vres = validate(obj, fmt, all_errors=True)
self.assertEqual(len(vres.errors), 2)
def test_types(self):
self.assertTrue(match(10, 'int'))
self.assertFalse(match('foo', 'int'))
self.assertTrue(match(10.0, 'float'))
self.assertFalse(match(10, 'float'))
... |
enriclluelles/troposphere_sugar | troposphere_sugar/__init__.py | Python | mit | 129 | 0 | from troposphere_sugar.skel import Skel
from troposphere_sug | ar.command import Command
from troposphere_sugar.decora | tors import *
|
baoboa/Crystal-Space | docs/support/docutils/writers/pseudoxml.py | Python | lgpl-2.1 | 829 | 0 | # Authors: David Goodger
# Contact: goodger@users.sourceforge.net
# Revision: $Revision: 21817 $
# Date: $Date: 2005-07-21 22:39:57 +0200 (Thu, 21 Jul 2005) $
# Copyright: This module has been placed in the public domain.
"""
Simple internal document tree Writer, writes indented pseudo-XML.
"""
__docformat__ = 'reStr... | es = ('writers',)
output = None
"""Final translated form of `document`."""
def translate(self):
self.output = self.document.pformat()
def supports(self, format):
| """This writer supports all format-specific elements."""
return 1
|
ddico/odoo | odoo/addons/base/tests/test_user_has_group.py | Python | agpl-3.0 | 11,831 | 0.003804 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError
class TestHasGroup(TransactionCase):
def setUp(self):
super(TestHasGroup, self).setUp()
self.group0 = 'test... | ser_portal',
'name': "Test User with two user types",
'groups_id': [(6, | 0, [self.grp_portal.id])]
})
with self.assertRaises(ValidationError):
self.grp_internal.users = [(4, test_user.id)]
def test_two_user_types_implied_groups(self):
"""Contrarily to test_two_user_types, we simply add an implied_id to a group.
This will trigger the ... |
SeanTater/tscan | tscan/destripe.py | Python | gpl-3.0 | 1,809 | 0.004422 | import numpy
import scipy.ndimage
import scipy.signal
import cv2
import cli
import code
@cli.Plugin.register
class Destripe(cli.Plugin):
''' Looks for out-of-place vertical or horizontal lines and inpaints them
'''
_args = []
_name = 'destripe'
def neighbor_threshold(self, image):
... | ery line like this:
A B C
abs(A-C) is low
abs(A-B) is high |
abs(C-B) is high
'''
gauss = scipy.ndimage.filters.gaussian_filter1d(image, 5, axis=0)
noise = numpy.abs((gauss - image)/gauss).sum(axis=2).sum(axis=1)
return noise
def noise_threshold(self, noise, z=1):
''' Pick out lines whose scores are more than z stdev ... |
0x1p2/uo_patcher-py | src/file_hash.py | Python | gpl-3.0 | 1,573 | 0.0089 | from hashlib import md5
import os.path
# # # # # # # # # # # # # # # # # # #
# Created by: Ryan Ball (0x1p2/Schism)
# Date created: December 4th, 2015
# # # # # # # # # # # # # # # # # # #
# Reponsible for checking the files.
# Gets the hashes of files
# Checks hashes against each other.
# # # # # # # # # # # # # # ... | e # if not, flag "True" for downloading.
buff = le_file.read() # Send the file into a buffer called "buff"
le_ | md5 = md5(buff).hexdigest() # Get the hash!
return le_md5 # Return the computed md5hash of the file :D
def check_hash(file_installed, file_dl):
''' Simple function for comparing. '''
if not file_installed == file_dl: # Checking the hashes bro, come at m... |
evanbiederstedt/RRBSfun | scripts/PDR_GenomicRegions_mcell45_66.py | Python | mit | 7,713 | 0.011669 |
import glob
import pandas as pd
import numpy as np
import os
os.chdir('/Users/evanbiederstedt/Downloads/annoOld_files')
# set glob subdirectory via cell batch
normalB_cellbatch_mcell = glob.glob("RRBS_NormalBCD19pCD27mcell45_66*.anno")
newdf1 = pd.DataFrame()
for filename in normalB_cellbatch_mcell:
df = pd.re... | /df['totreads_exonsDistance']
df['PDR_Introns'] = df['mixedReads_intronsDistance']/df['totreads_intronsDistance']
df['PDR_Promoters'] = df['mixedReads_promoterDistance']/df['totreads_promoterDistance']
df['PDR_CGIslands'] = df['mixedReads_cgiDistance']/df['totreads_cgiDistance']
df['PDR_CTCF'] = df['mix... | ixedReads_geneDistalRegulatoryModulesDistance']/df['totreads_geneDistalRegulatoryModulesDistance']
df['percent_totalMeth'] = df['methReadCount']/df['total_reads']
df['... |
CreditEaseDBA/Themis | rule_analysis/rule/text/toomany_or.py | Python | apache-2.0 | 192 | 0 | # | -*- coding: utf-8 -*-
def execute_rule(**kwargs):
sql = kwargs.get("sql")
bind_num = kwargs.get("or_num")
| if sql.count(" or ") > bind_num:
return True
return False
|
gosella/autopython | autopython/__init__.py | Python | gpl-3.0 | 104 | 0 | from .presenter import Presenter
__ve | rsion__ = (0, 9)
VERSION = '.'.join(str(d) for d in __version__)
| |
UManPychron/pychron | docs/user_guide/operation/scripts/examples/argus/extraction/jan/PrepareForAirShotExpansion.py | Python | apache-2.0 | 208 | 0.009615 | def main():
info('Prepare for air expansion')
close(des | cription='Microbone to Turbo')
open(description='Microbone to Getter NP-10H')
sleep(2)
open(description= | 'Microbone to Minibone')
|
speed-of-light/pyslider | lib/exp/pre/__init__.py | Python | agpl-3.0 | 3,713 | 0 | __doc__ = """
Preprocess input data, include
`video` format should be `avi` or `mp4`
`slide` format should be `pdf` and auto-convert to `jpg` or
a set of `jpg` images
`summary` save `video` and `slide` infomation to summary store
`reducer` reduce video frames to more distingushable one
`redu... | data = data.drop([maxv])
maxv = curv
else: # drop continuous item
data = data.drop([curv])
else: # seperate sequence start
maxv = curv
prev = curv
return data, before, len(data)
def __get_data(s... |
"""
df = self.load(key)
dmean = df["diff"].mean()
can = df[df["diff"].gt(dmean)]
return can, len(df)
def __results(self, **opts):
oo = opts["origin"]
ff = opts["final"]
info = "Original: {}, thresed: {}, final: {}, ratio: {}".\
format(oo,... |
jwdebelius/break_4w | break4w/continous.py | Python | bsd-2-clause | 10,502 | 0.001428 | import numpy as np
import pandas as pd
from break4w.question import Question
class Continous(Question):
def __init__(self, name, description, units=np.nan, dtype=float,
limits=None,
sig_figs=None, magnitude=1, order=None, **kwargs):
"""A Question object with continous responses
... | s = iseries.apply(f_)
if np.any(iseries.apply(lambda x: x == 'error')):
message = ( |
'the data cannot be cast to %s'
% (str(self.dtype).replace("<class '", '').replace("'>", ''))
)
self._update_log('validate', 'error', message)
raise TypeError(message)
else:
self._update_log(
'validate', 'pass',... |
jhjguxin/PyCDC | Karrigell-2.3.5/test/TemplateTest.py | Python | gpl-3.0 | 2,812 | 0.027738 | """Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
# The code under test is in the .. directory.
import sys
sys.path.append('..')
# We use the Python unit testing framework
import unittest
import thread, time
from util import *
class... | f test_PIH_InsertPython(self):
"""<% and %> tags are used to insert python code in HTML."""
import time
addScript("time.pih")
page = getPage("/time.pih")
today = time.strftime("%d:%m:%y",time.localti | me(time.time()))
expected = getGoldenFile("time.out", date=today)
self.assertEqual(page.status, 200)
self.assertEqual(page.content, expected)
def test_PIH_PrintValue(self):
"""<%= an %> tags are used to print python value."""
addScript("value.pih")
page = getPage("/value.pih")
expected = getGoldenFile("... |
marianc/python-server-typescript-client | Server/modules/utils/dal/common/entities/dataViews/localDtoViewsBase.py | Python | gpl-3.0 | 1,108 | 0.005425 | from modules.utils.dal.common.entities.dataViews.dataViewLocalDto import DataViewLocalDto
from modules.utils.dal.common.entities.dataContext import DataContext
from modules.utils.dal.common.dtos import metadataSrv
from modules.utils.dal.common import utils as dalUtils
class LocalDtoViewsBase:
def __init__(s... | alUtils.getEntityTypeName(enti | tySetName, self.metadata)
return self.getPropertyValue(entityTypeName)
def getPropertyValue(self, entityTypeName: str) -> DataViewLocalDto:
instance = None
if entityTypeName in self.propertyBag:
instance = self.propertyBag[entityTypeName]
else:
instan... |
jackkiej/SickRage | sickbeard/helpers.py | Python | gpl-3.0 | 59,002 | 0.002474 | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
# Git: https://github.com/SickRage/SickRage.git
#
# This file is part of SickRage.
#
# SickRage 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... | hre',
r'\[AndroidTwoU\]$': 'searchre',
r'\[brassetv\]$': 'searchre',
r'\[Talamasca32\]$': 'searchre',
r'\(musicbolt\.com\)$': 'searchre',
r'\ | .\(NLsub\)$': 'searchre',
r'\(NLsub\)$': 'searchre',
r'\.\[BT\]$': 'searchre',
r' \[1044\]$': 'searchre',
r'\.RiPSaLoT$': 'searchre',
r'\.GiuseppeTnT$': 'searchre',
r'\.Renc$': 'searchre',
r'\.gz$': 'searchre',
r'\.English$': 'searchre',
r'\.German... |
SCIP-Interfaces/PySCIPOpt | examples/unfinished/vrp_lazy.py | Python | mit | 4,750 | 0.012632 | """
vrp.py: model for the vehicle routing problem using callback for adding cuts.
approach:
- start with assignment model
- add cuts until all components of the graph are connected
Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
"""
import math
import random
import networkx
from pyscipopt import Mod... | nfopriority = 1, chckpriority = 1, sepafreq = -1, propfreq = -1,
eagerfreq = -1, maxprerounds = 0, delaysepa = False, delayprop = False, needscons = False,
presoltiming = SCIP_PRESOLTIMING.FAST, proptiming = SCIP_PROPTIMING.BEFORELP)
model.optimize()
x = model... | print("Optimal solution:", model.getObjVal())
print("Edges in the solution:")
print(sorted(edges))
|
boisvert42/npr-puzzle-python | 2016/0306_keyboard_adjacent.py | Python | cc0-1.0 | 1,281 | 0.010929 | #!/usr/bin/env python
"""
NPR 2016-03-06
http://www.npr.org/2016/03/06/469327504/five-letters-with-which-to-play-heres-a-puzzle-to-blow-you-away
Bail, Nail, and Mail are three four-letter words that differ only by their first letters.
And those first letters (B, N, and M) happen to be adjacent on a computer keyboard... | What words are they?
"""
from nltk.corpus import brown
from collections import defaultdict
common_words = set([x.lower() for x in brown.words() if len(x) == 4])
# Group words by last three letters
d = defaultdict(set)
for w in common_words:
d[w[1:]].add(w[0])
# Rows on a keyboard
rows = ['qwertyuiop','asdfghjkl... | d(row[i:i+5])
#%%
for k,v in d.iteritems():
if len(v) >= 5:
for five in adjacent_five:
if set(five).issubset(v):
for first_letter in five:
print first_letter + k,
print |
joodicator/PageBot | page/kakasi.py | Python | lgpl-3.0 | 2,024 | 0.010375 | #===============================================================================
import re
from untwisted.magic import sign
from channel import not_quiet
from runtime import later
import message
import util
import limit
import kakasi_lib
link, install, uninstall = util.LinkSet().triple()
#=========================... | h_romaji(bot, | id, target, args, full_msg):
kakasi(bot, id, target or id.nick, args, target is not None)
#===============================================================================
def kakasi(bot, id, target, msg, prefix=True, auto=False, **kwds):
if auto and not kakasi_lib.is_ja(msg): return
raw_reply = kakasi_lib... |
shearichard/spellsplash | splsplsh_project/spellweb/migrations/0004_auto_20140920_0007.py | Python | gpl-3.0 | 1,789 | 0.002236 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('spellweb', '0003_auto_20140920_0006'),
]
operations = [
migrations.CreateModel(
name='Attempt',
fiel... | ],
options={
'ordering': [ | 'level', 'word'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='word',
unique_together=set([('source', 'word')]),
),
migrations.AddField(
model_name='attempt',
name='word',
field=mode... |
famish99/MuchoCorazon | utils/__init__.py | Python | isc | 14 | 0 | import sec | ret | |
PressLabs/cobalt | tests/unit/cobalt/test_cobalt.py | Python | apache-2.0 | 650 | 0 | # Copyright 2016 Presslabs SRL
#
# 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,... | rmissions and
# limitations under the License.
class TestCob | alt:
def test_stop_signals(self, mocker):
pass
|
basbloemsaat/sheepsense_v2 | lib/sheepsense/model/__init__.py | Python | gpl-3.0 | 908 | 0.002203 |
class List_C():
def __init__(
self,
size=0,
):
self.size = size
self._elements = None
def __iter__(self):
self._pos = -1
self._search()
return self
def __next__(self):
self._pos += 1
if self._pos < len(self._elements):
... | s]
else:
raise StopIteration
# contract
def _search(self):
pass
def _get_length(self):
self._search()
if self._elements == None:
return 0
return len(self._elements)
def _get_elements(self):
self._search()
return self._ele... | turn self.length
length = property(_get_length)
elements = property(_get_elements)
|
kelvan/coapWL | coapserver.py | Python | gpl-2.0 | 2,068 | 0.003385 | import asyncio
import json
import aiocoap.resource as resource
import aiocoap
from pyWL.database import Station, Line
from pyWL.realtime import Departures
import json_serializer
class DepartureResource(resource.ObservableResource):
def __init__(self):
super().__init__()
self.notify()
def not... | station = stations[0]
dep = Departures(station.get_stops | ())
dep.refresh()
payload = json.dumps(dep, ensure_ascii=False, default=json_serializer.default)
else:
return aiocoap.Message(code=aiocoap.NOT_FOUND, payload='Station not found'.encode('ascii'))
response = aiocoap.Message(code=aiocoap.CONTENT, payload=payload... |
OCA/server-tools | excel_import_export_demo/report_action/partner_list/report_partner_list.py | Python | agpl-3.0 | 943 | 0 | # Copyright 2019 Ecosoft Co., Ltd | (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class ReportPartnerList(models.TransientMode | l):
_name = "report.partner.list"
_description = "Wizard for report.partner.list"
partner_ids = fields.Many2many(comodel_name="res.partner")
results = fields.Many2many(
"res.partner",
string="Results",
compute="_compute_results",
help="Use compute fields, so there is not... |
repotvsupertuga/tvsupertuga.repository | script.module.universalscrapers/lib/universalscrapers/scraper.py | Python | gpl-2.0 | 2,679 | 0.006719 | import abc
import xbmcaddon
abstractstaticmethod = abc.abstractmethod
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(callable)
class Scraper:
__metaclass__ = a... | urns:
a list of video sources represented by dicts with format:
{'source': video source (str), 'quality': quality (str), 'scraper': scraper name (str) , 'url': url (str), 'direct': bool}
"""
pass
def scrape_episode(self,title, show_year, year, season, episode, imdb, tvdb, debrid =... | -> str
show_year: year tv show started -> str
year: year episode premiered -> str
season: season number of the episode -> str
episode: episode number -> str
imdb: imdb identifier -> str
tvdb: tvdb identifier -> str
debrid: boolean indicating whether to use debrid... |
ctn-waterloo/nengo_theano | examples/singleneuron.py | Python | mit | 977 | 0.029683 | import nengo.nef_theano as nef
net=nef.Network('Single Neuron') # Create the network
net.make_input('input',[-0.45]) # Create | a controllable input
# with a starting value of -.45
net.make('neuron',neurons=1,dimensions=1, # Make 1 neuron representing
max_rate=(100,100),intercept=(-0.5,-0.5), # 1 dimension, with a maximum
encoders=[[1]],noise=3) ... | pt of
# -0.5, encoder of 1 (i.e. it
# responds more to positive
# values) and a noise of
# variance 3
net.connect('input',... |
Haynie-Research-and-Development/jarvis | deps/lib/python3.4/site-packages/Cryptodome/Signature/DSS.py | Python | gpl-2.0 | 15,276 | 0.000131 | #
# Signature/DSS.py : DSS.py
#
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condition... | # Also applicable to ECDSA
def __init__(self, key, encoding, order, private_key):
super(DeterministicDsaSigScheme, self).__init__(key, encoding, order)
self._private_key = pr | ivate_key
def _bits2int(self, bstr):
"""See 2.3.2 in RFC6979"""
result = Integer.from_bytes(bstr)
q_len = self._order.size_in_bits()
b_len = len(bstr) * 8
if b_len > q_len:
result >>= (b_len - q_len)
return result
def _int2octets(s |
yland/coala | coalib/bearlib/abstractions/__init__.py | Python | agpl-3.0 | 110 | 0 | """
The abstractions package contains classes tha | t serve as interfaces for
helper classes in the | bearlib.
"""
|
JuniorJPDJ/pyChomikBox | ChomikBox/utils/FileTransferProgressBar.py | Python | lgpl-3.0 | 3,099 | 0.00355 | import time
import sys
def sizeof_fmt(num, unit='B'):
# source: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
for uprexif in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "{:3.2f | } {}{}".format(num, uprexif, uni | t)
num /= 1024.0
return "{:3.2f} Yi{}".format(num, unit)
output = sys.stderr
progress_format = '{n} [{b}] {p:3.1f}% ({d}/{a}) {s}'
class FileTransferProgressBar(object):
# inspired by clint.textui.progress.Bar
def __init__(self, filesize, name='', width=32, empty_char=' ', filled_char='#', hide=... |
scities-data/metro-atlas_2014 | bin/names/cbsa_names.py | Python | bsd-2-clause | 1,257 | 0.026253 | """ cbas_names.py
Extract the names of CBSAs from the list given by the OMB.
"""
from xlrd import open_workbook
#
# READ DATA
#
book = open_workbook('data/gz/List1.xls',on_demand=True)
for sheet_name in book.sheet_names():
sheet = book.sheet_by_name(sheet_name)
# Read
## CBSA fips
cbsa_fips = ... | and i<1885:
cbsa_fips.append( (cell.value).encode('utf8') )
## Names
names = []
for i,cell in enumerate(sheet.col(3)): #
if i>2 and i<1885:
names.append( (cell.value).encode('utf8') )
## County fips
county_fips = []
for i,(cell1,cell2) in enumerate(zip(sheet.co... | ('utf8') +
(cell2.value).encode('utf8') )
# Assemble
name_list = {}
for name, c, county in zip(names, cbsa_fips, county_fips):
name_list[c] = name
book.unload_sheet(sheet_name)
#
# WRITE DATA
#
# Names
with open('data/misc/cbsa_names.txt', 'w') as out... |
mhbu50/erpnext | erpnext/manufacturing/doctype/production_plan_item/production_plan_item.py | Python | gpl-3.0 | 216 | 0.00463 | # Copyright (c) 2015, Frappe | Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. | See license.txt
from frappe.model.document import Document
class ProductionPlanItem(Document):
pass
|
TBIproject/WolfEyes | WolfEyes/Utils/TypeChecker.py | Python | bsd-3-clause | 2,472 | 0.002832 | # -*- coding: utf-8 -*-
"""
WOLFEYES'S FRAMEWORK
Python 3 / OpenCV 3
This file describes some TypeCheking decorators.
Might be useless, but allows for almost very precise type checking,
especially on keyworded args, which might help.
"""
# 'kargs' get the arguments and passes the decorator
def args(*types, **ktypes)... | -fou
if len(types) is 1 and not isinstance(types[0], type) and callable(types[0]):
raise ValueError("You should not pass a function to TypeError.ret, maybe you did not write as '@TypeError.ret()...'")
|
# This decorator will modify the function 'func'
def decorator(func):
def modified(*args, **kargs):
# This is the modified function, 'modified' Works
# like a proxy, just passes the arguments and
# checks the type of the return's value
ret = func(*args,... |
mxOBS/deb-pkg_trusty_chromium-browser | v8/tools/push-to-trunk/auto_roll.py | Python | bsd-3-clause | 4,392 | 0.008197 | #!/usr/bin/env python
# Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import json
import os
import sys
import urllib
from common_includes import *
import chromium_roll
class CheckActiv... | .FindLastTrunkPush(
| branch="origin/candidates", include_patches=True)
self["last_push"] = self.GetCommitPositionNumber(push_hash)
class DetectLastRoll(Step):
MESSAGE = "Detect commit ID of the last Chromium roll."
def RunStep(self):
# Interpret the DEPS file to retrieve the v8 revision.
# TODO(machenbach): This shou... |
NicovincX2/Python-3.5 | Analyse (mathématiques)/Analyse numérique/Interpolation numérique/Spline/Spline cubique d'Hermite/cubic_spline_tri.py | Python | gpl-3.0 | 3,203 | 0.002498 | # -*- coding: utf-8 -*-
import os
# a simple cubic spline example.
#
# generate some random data in 10 intervals -- note the data changes
# each time this is run.
#
# Our form of the spline polynomial comes from Pang, Ch. 2
#
# solve the matrix system for the splines
#
# plot the splines
#
# M. Zingale (2013-02-10)
... | ad this at
# the beginning and for l we will pad at the end.
u = numpy.zeros(n - 1)
d = numpy.zeros(n - 1)
l = numpy.zeros(n - 1)
d[:] = 4.0 * dx
u[:] = dx
u[0] = 0.0
l[:] = dx
l[n - 2] = 0.0
# use our own tridiagonal solver
xsol = tridiag( | l, d, u, b)
# check that our tridiagonal solver works by doing Ax = b and comparing
# to the original b
print("original b:\n", b)
print("computed Ax:\n", triMultAx(l, d, u, xsol))
# x now hold all the second derivatives for points 1 to n-1. Natural
# boundary conditions set p'' = 0 at i = 0 and n
# ppp will be our a... |
trieb/mqtt-examples | Send IP Address/send_ip_mqtt.py | Python | mit | 1,172 | 0.024744 | #!/usr/bin/python3
import time
from datetime import datetime
import urllib.request
import json
import paho.mqtt.client as mqtt
DEBUG = False
# Config params
broker_address = "<broker address>"
subscribe_topic = "<topic>"
publish_topic = "<topic to publish on on>"
def getIP():
request = urllib.reques... | f(DEBUG):
print("Received message")
print(msg.topic, ": ", str(msg.payload))
# Initiate mqtt-client
mqttc = mqtt.Client()
mqttc.on_connect = on | _connect
mqttc.on_message = on_message
mqttc.connect(broker_address, 1883, 60)
mqttc.loop_start()
running = True
while running:
# Get the external IP
IP = getIP()
if(DEBUG):
print(IP)
mqttc.publish(publish_topic, IP, qos=0, retain=True)
time.sleep(5)
mqttc.loop_stop()
running = False |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSanguniangWordpressCom.py | Python | bsd-3-clause | 560 | 0.033929 |
def extractSanguniangWordpressCom(item):
'''
Parser for 'sanguniang.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loi... | terous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildRelea | seMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
kawamon/hue | desktop/core/ext-py/billiard-3.5.0.5/billiard/einfo.py | Python | apache-2.0 | 3,671 | 0 | from __future__ import absolute_import
import sys
import traceback
__all__ = ['ExceptionInfo', 'Traceback']
DEFAULT_MAX_FRAMES = sys.getrecursionlimit() // 8
class _Code(object):
def __init__(self, code):
self.co_filename = code.co_filename
self.co_name = code.co_name
self.co_argcount ... | fl["__traceback_hide__"] = frame.f_locals["__traceback_hide__"]
except KeyError:
pass
self.f_back = None
self.f_trace = None
self.f_exc_traceback = None
self.f_exc_type = None
self.f_exc_value = None
self.f_code = self.Code(frame.f_code)
self... | class _Object(object):
def __init__(self, **kw):
[setattr(self, k, v) for k, v in kw.items()]
class _Truncated(object):
def __init__(self):
self.tb_lineno = -1
self.tb_frame = _Object(
f_globals={"__file__": "",
"__name__": "",
... |
helicontech/zoo | Zoocmd/cmdline/commands/uninstall.py | Python | apache-2.0 | 3,047 | 0.003977 | # -*- coding: utf-8 -*-
import logging
from core.core import Core
import core.core
from core.parameters_parser import ParametersParserStr
from core.product_collection import ProductCollection
from core.dependency_manager import DependencyManager
from core.parameters_manager import ParametersManager
from core.parameters... | :
result_list = []
for product in product_list:
if "and" in product:
inner_list = UninstallCommand.flat_deps4products(product["and"], installed)
result_list += inner_list
# we can process only one level of "or" list
if "or" in product... | nd.flat_deps4products(product["or"], installed))
# installed version is not existed
if "product" in product and product["product"]["installed_version"] == '':
if not installed:
result_list.append(product["product"])
continue
#... |
xbmc/atv2 | xbmc/lib/libPython/Python/Demo/parser/example.py | Python | gpl-2.0 | 5,722 | 0.001748 | """Simple code to extract class & function docstrings from a module.
This code is used as an example in the library reference manual in the
section on using the parser module. Refer to the manual for a thorough
discussion of the operation of this code.
"""
import os
import parser
import symbol
import token
import ty... | elf._function_info[name]
cl | ass FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None):
self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
class ClassInfo(SuiteInfoBase):
def __init__(self, tree = None):
self._name = tree[2][1]
SuiteInfoBase.__init__(self,... |
jeffery9/mixprint_addons | point_of_sale/controllers/main.py | Python | agpl-3.0 | 5,627 | 0.009597 | # -*- coding: utf-8 -*-
import logging
import simplejson
import os
import openerp
from openerp.addons.web.controllers.main import manifest_list, module_boot, html_template
class PointOfSaleController(openerp.addons.web.http.Controller):
_cp_path = '/pos'
@openerp.addons.web.http.httprequest
def app(self,... | cript>' % i for i in manifest_list(req, None, 'js'))
css = "\n ".join('<link rel="stylesheet" href="%s">' % i for i in manifest_list(req, None, 'css'))
cookie = req.httprequest.cookies.get("instance0|session_id")
session_id = cookie.replace("%22","")
template = html_template.repl... | ml manifest="/pos/manifest?session_id=%s"'%session_id)
r = template % {
'js': js,
'css': css,
'modules': simplejson.dumps(module_boot(req)),
'init': 'var wc = new s.web.WebClient();wc.appendTo($(document.body));'
}
return r
@openerp.addons.web... |
google/pigweed | pw_env_setup/py/pw_env_setup/windows_env_start.py | Python | apache-2.0 | 2,955 | 0.000382 | # -*- coding: utf-8 -*-
# Copyright 2020 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); y | ou may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.ap | ache.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 limit... |
fabsx00/python-joern | testing/tests/__init__.py | Python | gpl-3.0 | 212 | 0 |
from lookupTests import *
from compositionTests import *
from udgTests | import *
from dataFlowTests import *
from cfgTests import *
from parsingTests import *
f | rom interproc import *
from initGraphTests import *
|
IL2HorusTeam/il2fb-ds-config | il2fb/config/ds/schemas/helpers.py | Python | lgpl-3.0 | 1,174 | 0 | # coding: utf-8
from schematics.types import StringType, | IntType, FloatType, BooleanType
from il2fb.config.ds.compat import configparser
_NO_VALUE = object()
_TYPE_TO_GETTER_MAP = {
StringType: 'get',
IntType: 'getint',
FloatType: 'getfloat',
BooleanType: 'getboolean',
}
def _get_getter(class_type, ini):
try:
method_name = _TYPE_TO_GETTER_MA... | return ini.get
def field_from_ini(field, ini, section, option, default=_NO_VALUE):
getter = _get_getter(field.typeclass, ini)
try:
return getter(section, option)
except (configparser.NoSectionError, configparser.NoOptionError):
return (
default
if default is not _N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.