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 |
|---|---|---|---|---|---|---|---|---|
opticode/eve | eve/io/media.py | Python | bsd-3-clause | 2,207 | 0 | # -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class Med | iaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
in | herit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
... |
wasade/american-gut-web | amgut/lib/data_access/sql_connection.py | Python | bsd-3-clause | 7,011 | 0.000143 | from __future__ import division
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The American Gut Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------... | e SQL query
many: bool, optional
If true, performs an execute many call
Returns
-------
pgcursor : psycopg2.cursor
The cursor in which the SQL query was executed
Raises
------
ValueError
If there is some error executing the SQ... | if many:
for args in sql_args:
self._check_sql_args(args)
else:
self._check_sql_args(sql_args)
# Execute the query
with self.get_postgres_cursor() as cur:
try:
if many:
cur.executemany(sql, sql_args)
... |
sanacl/GrimoireELK | grimoire/elk/git.py | Python | gpl-3.0 | 15,586 | 0.002695 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
#
# Copyright (C) 2015 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later ve... | SortingHat.add_identity(self.sh_db, user, SH_GIT_COMMIT)
else:
if user_data not in self.github_logins:
| self.github_logins[user_data] = sh_identity['username']
logging.debug("GitHub-commit exists. username:%s user:%s",
sh_identity['username'], user_data)
commit_hash = item['data']['commit']
if item['data']['Author']:
user =... |
adamziel/django_translate | django_translate/management/commands/tranzdump.py | Python | mit | 8,550 | 0.004094 | # -*- coding: utf-8 -*-
import os
import os.path
import re
import sys
import string
from django.apps.registry import apps
from django.core.management.base import BaseCommand, CommandError
from python_translate.extractors import base as extractors
from python_translate import operations
from python_translate.translat... | gue):
if isinstance(extractor, extractors.ChainExtractor):
su | bextractors = list(extractor._extractors.values())
else:
subextractors = [extractor]
for subextractor in subextractors:
if not isinstance(subextractor, extractors.BaseExtractor):
subextractor.extract(root_path, extracted_catalogue)
continue
... |
sivel/ansible-modules-core | network/iosxr/iosxr_config.py | Python | gpl-3.0 | 11,400 | 0.000965 | #!/usr/bin/python
#
# 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 version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME... |
martwo/ndhist | examples/python/fill_1d_generic_axis.py | Python | bsd-2-clause | 790 | 0.037975 | import numpy as np
import ndhist
h = ndhist.ndhist((np.array([0,1,2,3,4,5,6,7,8,9,11], dtype=np.dtype(np.float64)),
)
, dtype=np.dtype(np.float6 | 4))
h.fill([-0.1, 0, 0.9, 1, 3.3, 9.9, 10, 11.1])
print(h.bc)
class V(object):
def __init__(self, v=0):
self._v = v
def __lt__(self, rhs):
print("%f < %f"%(self._v, rhs._v))
re | turn self._v < rhs._v
def __add__(self, rhs):
print("%f + %f"%(self._v, rhs._v))
return V(self._v + rhs._v)
h2 = ndhist.ndhist((np.array([V(0),V(1),V(2),V(3),V(4),V(5),V(6),V(7),V(8),V(9),V(10)], dtype=np.dtype(object)),
)
, dtype=np.dtype(np.float64))
h2.fil... |
microblink/NNPACK | src/x86_64-fma/fft16x16.py | Python | bsd-2-clause | 23,581 | 0.002417 | from __future__ import absolute_import
from __future__ import division
from peachpy import *
from peachpy.x86_64 import *
from common import butterfly, sqrt2_over_2
from common import butterfly, sqrt2_over_2, cos_npi_over_8, interleave
def fft8_bitreverse(n):
return int(format(n, "03b")[::-1], 2)
def load_ym... | ut_real[4], ymm_real1) # bit-reversal: 1->4
ymm_imag0, ymm_imag1 = butterfly(imag[0], imag[1], negate_out_b=True, writeback=False)
store_ymm_result(out_imag[4], ymm_imag1) # bit-reversal: 1->4
VMOVAPS(ymm_sqrt2_over_2, Constant.float32x8(sqrt2_over_2))
for i, (data_lo, data_hi) in enumerate(zip(data[4:... | negate_b=fft2_negate_b.get(id(data_hi), False), scale_b=fft2_scale_b.get(id(data_hi)))
butterfly(ymm_real0, ymm_imag0)
store_ymm_result(out_real[0], ymm_real0)
store_ymm_result(out_imag[0], ymm_imag0)
# Bit reversal
for i in range(8):
new_i = fft8_bitreverse(i)
if new_i >... |
FiveEye/ProblemSet | LeetCode/lc992.py | Python | mit | 1,820 | 0.008242 | def add(s, i, x):
n = len(s)
while i < n:
s[i] += x
i += (i&(-i))
def get(s, i):
ret = 0
while i != 0:
ret += s[i]
i -= (i&(-i))
return ret
def find(s, k):
n = len(s)
beg = 0
end = n
tt = get(s, n-1)
while beg < end:
mid = (beg + end) // ... | 0
w = 1
while w * 2 < n:
w *= 2
while w > 0:
| while i+w >= n or s[i+w] > tk:
w //= 2
if w == 0:
break
if w == 0:
break
tk -= s[i+w]
i += w
w //= 2
#print("findR tk:", tk, i+1)
return i+1
class Solution:
def subarraysWithKDistinct(self, A: List[int], K: int)... |
gedankenstuecke/opensnp-fun | 01_analyse.py | Python | mit | 2,478 | 0.031881 | #!/usr/bin/env python
# encoding: utf-8
import glob
import os
import subprocess
cwd = os.getcwd()
'''
Conv | ert 23andMe files to
PLINK format
'''
def twenty3_and_me_files():
"""Return the opensnp files that are 23 and me format"""
all_twenty3_and_me_files= glob.glob('../opensnp_datadump.current/*.23andme.txt')
fifteen_mb = 15 * 1000 * 1000
non_junk_files = [path for path in all_twenty3_and_me_files if os.path.getsize(p... | tuff"""
try:
os.mkdir("23andme_plink")
except:
print "can't create output-folder"
exit
for f in usable_files:
# gid is the genotype-ID
gid = f.split("/")[-1].split("_")[1].replace("file","")
# converts the genotyping file to plink format, using the gid as sample name
call = "./plink --23file "+ f + " F... |
narendergupta/mooc | mooc/src/gen_utils.py | Python | gpl-2.0 | 1,796 | 0.007795 | import os
def lowercase(source):
if type(source) is str:
return source.lower()
elif type(source) is dict:
return dict((k,lowercase(v)) for k,v in source.items())
elif type(s | ource) is list:
return [lowercase(x) for x in | source]
else:
return source
def unique(source):
if type(source) is list:
return list(set(source))
elif type(source) is dict:
return dict((k,unique(v)) for k,v in source.items())
else:
return source
def float_precise_str(source, precision=2):
if type(source) is fl... |
ARPA-SIMC/arkimet | python/tests/test_arki_check.py | Python | gpl-2.0 | 34,243 | 0.004088 | # python 3.7+ from __future__ import annotations
import arkimet as arki
import unittest
import os
from contextlib import contextmanager
from arkimet.cmdline.check import Check
from arkimet.test import Env, CmdlineTestMixin, LogCapture
class StatsReporter:
def __init__(self):
self.op_progress = []
... | ds")
self.assertEqual(out, "testds: check 3 files ok\n")
out = self.call_output_success("testenv/testds", "--fix")
self.assertEqual(out, "testds: check 3 files ok\n")
out = self.call_output_success("testenv/testds", "--repack")
| self.assertEqual(out, "testds: repack 3 files ok\n")
out = self.call_output_success("testenv/testds", "--repack", "--fix")
self.assertRegex(
out,
r"(testds: repack: running VACUUM ANALYZE on the dataset index(, if applicable)?\n)?"
... |
ericlee0803/surrogate-GCP | gp/GPsim.py | Python | bsd-3-clause | 1,664 | 0.026442 | import sys
import time
import logging
import threading
import GPy
import numpy as np
import matplotlib.pyplot as plt
import pdb
from GPhelpers import *
from IPython.display import display
from poap.strategy import FixedSampleStrategy
from poap.strategy import InputStrategy
from poap.tcpserve import ThreadedTCPServer
fr... | - self.batchsize*self.fevalcost
eval_logX = np.random.uniform(bounds[0], bounds[1], self.batchsize)
eval_logY = f(eval_logX)
ybest = np.amin(eval_logY)
while(self.money > 0):
# calc Gaussian Process
m = calcGP(eval_logX, eval_logY)
# calc batchsize, break if necessary
self.batchsize = np.floor... | self.money = self.money - self.batchsize*self.fevalcost
X = batchNewEvals_EI(m, bounds=1, batchsize=self.batchsize, fidelity=1000)
Y = f(X)
eval_logY = np.concatenate([eval_logY, Y])
eval_logX = np.concatenate([eval_logX, X])
ynew = np.amin(eval_logY)
if(np.absolute(ynew - ybest) < breakcond):
p... |
Ultimaker/Cura | plugins/3MFReader/WorkspaceDialog.py | Python | lgpl-3.0 | 14,135 | 0.002971 | # Copyright (c) 2020 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Optional, Dict, cast
from PyQt5.QtCore import pyqtSignal, QObject, pyqtProperty, QCoreApplication
from UM.FlameProfiler import pyqtSlot
from UM.PluginRegistry import PluginRegistry
from UM.Applicati... | mUserSettingsChanged)
def numUserSettings(self) -> int:
return self._num_user_settings
@pyqtProperty(bool, notify=objectsOnPlateChanged)
def hasObjectsOnPlate(self) -> bool:
return self._objects_on_plate
def setHasObjectsOnPlate(self, objects_on_plate):
if self._objects_on_plat... | ("QVariantList", notify = materialLabelsChanged)
def materialLabels(self) -> List[str]:
return self._material_labels
def setMaterialLabels(self, material_labels: List[str]) -> None:
if self._material_labels != material_labels:
self._material_labels = material_labels
self... |
indico/indico-migrate | indico_migrate/importer.py | Python | gpl-3.0 | 6,978 | 0.002436 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | , tables=None):
for name, cls in sorted(db.Model._decl_class_registry.iteritems(), key=itemgetter(0)):
table = getattr(cls, '__table__', None)
if table is None:
continue
elif schema is not None and table.schema != schema:
continue
e... | imary key
candidates = [col for col in table.c if col.autoincrement and col.primary_key]
if len(candidates) != 1 or not isinstance(candidates[0].type, db.Integer):
continue
serial_col = candidates[0]
sequence_name = '{}.{}_{}_seq'.format(table.schema, cls.... |
ksmaheshkumar/grr | lib/data_stores/mysql_data_store_test.py | Python | apache-2.0 | 1,991 | 0.008036 | #!/usr/bin/env python
"""Tests the mysql data store."""
import unittest
# pylint: disable=unused-import,g-bad-import-order
from grr.lib | import server_plugins
# pylint: enable=unused-import,g-bad-import-order
import logging
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import data_store
from grr.lib import data_store_test
from grr.lib import flags |
from grr.lib import test_lib
from grr.lib.data_stores import mysql_data_store
class MysqlTestMixin(object):
def InitDatastore(self):
self.token = access_control.ACLToken(username="test",
reason="Running tests")
# Use separate tables for benchmarks / tests so they c... |
FND/tiddlyspace | setup.py | Python | bsd-3-clause | 1,806 | 0.018826 | AUTHOR = 'Osmosoft'
AUTHOR_EMAIL = 'tiddlyspace@osmosoft.com'
NAME = 'tiddlywebplugins.tiddlyspace'
DESCRIPTION = 'A discoursive social model for TiddlyWiki'
VERSION = '1.0.76' # NB: duplicate of tiddlywebplugins.tiddlyspace.__init__
import os
from setuptools import setup, find_packages
setup(
namespace_packag... | webplugins.oom',
'tiddlywebplugins.prettyerror>=0.9.2',
'tiddlywebplugins.pathinfohack>=0.9.1',
'tiddlywebplug | ins.form',
'tiddlywebplugins.reflector>=0.6',
'tiddlywebplugins.atom>=1.3.7',
'tiddlywebplugins.mysql2>=2.1.0',
'tiddlywebplugins.privateer',
'tiddlywebplugins.lazy>=0.4',
'tiddlywebplugins.relativetime',
'tiddlywebplugins.jsonp>=0.4',
'tiddlywebplugins.te... |
kuke/models | fluid/adversarial/tutorials/mnist_model.py | Python | apache-2.0 | 2,821 | 0 | """
CNN on mnist data using fluid api of paddlepaddle
"""
import paddle
import paddle.fluid as fluid
def mnist_cnn_model(img):
"""
Mnist cnn model
Args:
img(Varaible): the input image to be recognized
Returns:
Variable: the label prediction
"""
conv_pool_1 = fluid.nets.simple... | break
print("pass_id=" + str(pass_id) + " pass_acc=" + str(pass_acc.e | val()[
0]))
fluid.io.save_params(
exe, dirname='./mnist', main_program=fluid.default_main_program())
print('train mnist done')
if __name__ == '__main__':
main()
|
sdrogers/ms2ldaviz | ms2ldaviz/decomp_create_motifset.py | Python | mit | 1,879 | 0.029803 | import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings")
import django
django.setup()
from decomposition.models import *
from basicviz.models import *
# Script to transform an experiment into a motifset for decomposition
if __name__ == '__main__':
experiment_name = sys.argv[1]
... | features:
gf = GlobalFeature.objects.get_or_create(name = localfeature.name,
min_mz = localfeature.min_mz,
| max_mz = localfeature.max_mz,
featureset = fs)[0]
FeatureMap.objects.get_or_create(localfeature = localfeature,
globalfeature = gf)
n_done += 1
if n_done % 100 == 0:
print(n_done,len(original... |
brn0/gitosis | gitosis/run_hook.py | Python | gpl-2.0 | 2,455 | 0.000815 | """
Perform gitosis actions for a git hook.
"""
from ConfigParser import NoOptionError, NoSectionError
import errno
import logging
import os
import sys
import shutil
from gitosis import repository
from gitosis import ssh
from gitosis import gitweb
from gitosis import gitdaemon
from gitosis import app
from gitosis imp... | util.getSSHAuthorizedKeysPath(config=cfg)
ssh.writeAuthorizedKeys(
path=authorized_keys,
keydir=os.path.join(export, 'keydir'),
)
def update_mirro | rs(cfg, git_dir):
mirror.push_mirrors(cfg, git_dir)
class Main(app.App):
def create_parser(self):
parser = super(Main, self).create_parser()
parser.set_usage('%prog [OPTS] HOOK')
parser.set_description(
'Perform gitosis actions for a git hook')
return parser
de... |
cxong/Slappa | keyboard.py | Python | mit | 1,293 | 0.000773 | from config import *
class Keyboard:
def __init__(self):
self.keys = None
self.left = pygame.K_LEFT
self.right = pygame.K_RIGHT
self.jump = pygame.K_UP
self.hit_left = pygame.K_a
self.hit_right = pygame.K_d
self.hit_up = pygame.K_w
if GCW_ZERO:
... | self.hit_right = pygame.K_LCTRL
self.hit_up = pygame.K_SPACE
self.on_down = N | one
def update(self):
self.keys = pygame.key.get_pressed()
def is_escape(self):
return self.keys is not None and self.keys[pygame.K_ESCAPE]
def dir(self):
if self.keys is None:
return 0
if self.keys[self.left]:
return -1
elif self.keys[self.... |
ebigelow/LOTlib | LOTlib/Inference/MHShared.py | Python | gpl-3.0 | 769 | 0.002601 | from math import | log, exp, isnan
from random import random
def MH_acceptance(cur, prop, fb, acceptance_temperature=1.0):
"""Return a true/false, do we accept the proposal given the current sample.
Also handles all the weird corner cases for computing MH acceptance ratios.
"""
# If we get infs or are in a stupid sta... | mple priors since they may be -inf both
r = -log(2.0)
elif isnan(prop):
# Never accept
r = float("-inf")
else:
r = (prop-cur-fb) / acceptance_temperature
# And flip
return r >= 0.0 or random() < exp(r)
|
dgsantana/arsenalsuite | cpp/lib/PyQt4/pyuic/uic/port_v3/ascii_upper.py | Python | gpl-2.0 | 1,612 | 0.013648 | #############################################################################
##
## Copyright (c) 2012 Riverbank Computing Limited <info@riverbankcomputing.com>
##
## This file is part of PyQt.
##
## This file may be used under the terms of the GNU General Public
## License versions 2.0 or 3.0 as published by t | he Free Software
## Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
## included in the packaging of this file. Alternatively you may (at
## your option) use any later version of the GNU General Public
## License if such license has been publicly approved by Riverbank
## Computing Limited (or its su... | ) and the KDE Free Qt
## Foundation. In addition, as a special exception, Riverbank gives you
## certain additional rights. These rights are described in the Riverbank
## GPL Exception version 1.1, which can be found in the file
## GPL_EXCEPTION.txt in this package.
##
## If you are unsure which license is appropriate... |
veger/ansible | lib/ansible/modules/storage/netapp/na_elementsw_node.py | Python | gpl-3.0 | 8,394 | 0.001787 | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Node Operation
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | .pending_nodes
else:
list_nodes = all_nodes.nodes
for current_node in list_no | des:
if self.state == "absent" and \
(current_node.node_id in self.node_id or current_node.name in self.node_id or current_node.mip in self.node_id):
if self.check_node_has_active_drives(current_node.node_id):
self.module.fail_json(msg='Erro... |
bitmovin/bitmovin-python | tests/bitmovin/services/inputs/sftp_input_service_tests.py | Python | unlicense | 6,702 | 0.002835 | import unittest
import json
from bitmovin import Bitmovin, Response, SFTPInput
from bitmovin.errors import BitmovinApiError
from tests.bitmovin import BitmovinTestCase
class SFTPInputTests(BitmovinTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClas... | _get_sample_sftp_input()
created_input_response = self.bitmovin.inputs.SFTP.create(sample_input)
self.assertIsNotNone(created_input_response)
self.assertIsNotNone(created_input_response.resource)
self.assertIsNotNone(created_input_response.resource.id)
self._compare_sftp_inputs(s... | self.assertIsNotNone(inputs.resource)
self.assertIsNotNone(inputs.response)
self.assertIsInstance(inputs.resource, list)
self.assertIsInstance(inputs.response, Response)
self.assertGreater(inputs.resource.__sizeof__(), 1)
def test_retrieve_sftp_input_custom_data(self):
(... |
grlee77/scipy | scipy/special/_precompute/zetac.py | Python | bsd-3-clause | 591 | 0 | """Compute the Taylor series for zeta(x) - 1 | around x = 0."""
try:
import mpmath
except ImportError:
pass
def zetac_series(N):
coeffs = []
with mpmath.workdps(100):
coeffs.append(-1.5)
for n in range(1, N):
coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n)
coeffs.append(coeff)
return coeffs
... | zetac_series(10)
coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
for x in coeffs]
print("\n".join(coeffs[::-1]))
if __name__ == '__main__':
main()
|
jfterpstra/bluebottle | bluebottle/homepage/serializers.py | Python | bsd-3-clause | 554 | 0 | from bluebottle.projects.serializers import ProjectPreviewSerializer
from bluebottle.quotes.serializers import QuoteSerializer
from bluebottle.slides.serializers import SlideSerializer
from bluebottle.statistics.serializers import StatisticSerializer
from rest_framework import serializers
class HomePageSerializer(ser... | = QuoteSerializer(many=True)
slides = Sli | deSerializer(many=True)
statistics = StatisticSerializer(many=True)
projects = ProjectPreviewSerializer(many=True)
|
richgieg/flask-now | config.py | Python | mit | 4,539 | 0 | import os
from datetime import timedelta
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
###########################################################################
# [ Application ]
###########################################################################
APP_TITLE = 'WebApp'
... | ################################################################
# Ensures that the "remember me" cookie isn't accessible by
# client-sides scripts.
REMEMBER_COOKIE_HTTPONLY = True
| # Time-to-live for the "remember me" cookie.
REMEMBER_COOKIE_DURATION = timedelta(days=365)
# Must be disabled for the application's security layer to
# function properly.
SESSION_PROTECTION = None
###########################################################################
# [ Flask-Mail ]
... |
youtube/cobalt | third_party/web_platform_tests/fetch/api/resources/stash-put.py | Python | bsd-3-clause | 301 | 0 | def main(request, response):
url_dir = '/'.join(request.url_parts.pat | h.split('/')[:-1]) + '/'
key = request.GET.first("key")
value = request.GET.first("value")
request.server.stash.put(key, value, u | rl_dir)
response.headers.set('Access-Control-Allow-Origin', '*')
return "done"
|
skarra/CalDAVClientLibrary | caldavclientlibrary/protocol/http/tests/test_util.py | Python | apache-2.0 | 4,886 | 0.011871 | ##
# Copyright (c) 2006-2013 Apple 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 l... | rseStatusLine(unittest.TestCase):
def testParseTokenOK(self):
self.assertEqual(parseStatusLine("HTTP/1.1 200 OK"), 200)
def testParseTokenBadStatus(self):
self.assertEqual(parseStatusLine("HTTP/1.2 2001 OK"), 0)
def testParseTokenBadVersion(self):
self.assertEqual(parseStatusLin... | arseStatusLine("HTTP/1.1 OK"), 0)
def testParseTokenBad(self):
self.assertEqual(parseStatusLine("HTTP/1.1"), 0)
|
siliconsmiley/QGIS | python/plugins/processing/algs/gdal/proximity.py | Python | gpl-2.0 | 4,529 | 0.001766 | # -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... | nts.append('-nodata')
arguments.append(values)
values = unicode(self.getParameterValue(self.BUF_VAL))
if values < 0:
arguments.append('-fixed-buf-val')
arguments.append(values)
commands = []
if isWindows():
commands = ['cmd.exe', '/C ', '... | rguments)]
return commands
|
pywinauto/pywinauto | pywinauto/__init__.py | Python | bsd-3-clause | 7,043 | 0.003124 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistributi... | # Probe the selected COM threading mode
pythoncom.CoInitializeEx(com_init_mode)
pythoncom.CoUninitialize()
except pythoncom.com_error:
w | arnings.warn("Revert to STA COM threading mode", UserWarning)
com_init_mode = 2 # revert back to STA
return com_init_mode
sys.coinit_flags = _get_com_threading_mode(sys)
#=========================================================================
class WindowNotFoundError(Exception):
""... |
catalyst-cooperative/pudl | src/pudl/metadata/resources/eia861.py | Python | mit | 23,777 | 0.000505 | """Definitions of data tables primarily coming from EIA-861."""
from typing import Any, Dict, List
RESOURCE_METADATA: Dict[str, Dict[str, Any]] = {
"advanced_metering_infrastructure_eia861": {
"description": "The data contain number of meters from automated meter readings (AMR) and advanced metering infras... | ital_access_customers',
'direct_load_control_customers',
'energy_served_ami_mwh',
'entity_type',
'home_area_network',
'non_amr_ami',
'report_date',
'short_form',
'state',
'util... | "primary_key": [
'balancing_authority_code_eia',
'customer_class',
'report_date',
'state',
'utility_id_eia',
],
},
"field_namespace": "eia",
"sources": ["eia861"],
"etl_group": "eia861... |
laurmurclar/mitmproxy | mitmproxy/contrib/kaitaistruct/png.py | Python | mit | 11,809 | 0.003049 | # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
# The source was png.ksy from here - https://github.com/kaitai-io/kaitai_struct_formats/blob/9370c720b7d2ad329102d89bdc880ba6a706ef26/image/png.ksy
import array
import struct
import zlib
from enum import Enum
from kaita... | self._root)
self.green = self._root.Point(self._io, self, self._root)
self.blue = self._root.Point(self._io, self, self._root)
class IhdrChunk(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
| self._root = _root if _root else self
self.width = self._io.read_u4be()
self.height = self._io.read_u4be()
self.bit_depth = self._io.read_u1()
self.color_type = self._root.ColorType(self._io.read_u1())
self.compression_method = self._io.read_u1()
... |
SebastianSchildt/potatonet-power | gui/netclient.py | Python | mit | 699 | 0.048641 | import socket
HOST, PORT = "localhost", 2222
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def init():
global sock
try:
sock.connect((HOST, PORT))
return True
except:
print("Can not open connection")
return False
def transceive(command):
global sock
try:
sock.sendall(bytes(command+"\n","ut... | ata=readline(sock)
return data
except OSError as e:
print("Communication error: {0}".format(err))
return("505 ")
def close():
global sock
sock.close()
def readline(sock, recv_buffer=4096, delim='\n'):
buffer = ''
data = True
while data:
data = sock.recv(recv_buffer)
buffer += data.decode("utf-8")
| if buffer[-1] == '\n':
return buffer[:-1]
|
antoniov/tools | clodoo/check_one2many.py | Python | agpl-3.0 | 3,475 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
# import oerplib
# from os0 import os0
try:
from clodoo import clodoo
except ImportError:
import clodoo
try:
from z0lib.z0lib import z0lib
except ImportError:
try:
from z0lib import z0lib
except ImportError:
import ... | > 3):
print(text)
msg_time = time.time()
parser = z0lib.parseoptargs("Odoo test environment",
| "© 2017-2018 by SHS-AV s.r.l.",
version=__version__)
parser.add_argument('-h')
parser.add_argument("-c", "--config",
help="configuration command file",
dest="conf_fn",
metavar="file",
default='./inv2draf... |
kruegg21/casino_analytics | src/main.py | Python | apache-2.0 | 14,236 | 0.007516 | import helper
import json
import pandas as pd
import mpld3
import numpy as np
import requests
import factor_analysis
import visualizations
from datetime import timedelta, datetime
from netwin_analysis import netwin_analysis
from sqlalchemy import create_engine
from generateresponsefromrequest import get_intent_entity_f... | ject) -- this is an object holding
everything we need to know
| about the query
'''
# Get JSON Watson conversations response to natual language query
response = get_intent_entity_from_watson(nl_query, error_checking = False)
# Transform JSON Watson conversations response to query parameters object
query_params = query_parameters()
query_p... |
sharkykh/nyaa | import_to_es.py | Python | gpl-3.0 | 4,652 | 0.00172 | #!/usr/bin/env python
"""
Bulk load torents from mysql into elasticsearch `nyaav2` index,
which is assumed to already exist.
This is a one-shot deal, so you'd either need to complement it
with a cron job or some binlog-reading thing (TODO)
"""
import sys
import json
# This should be progressbar33
import progressbar
fr... | # order by created_time, but oh well
"id": t.id,
"display_name": t.display_name,
"created_time": t.created_time,
# not analyzed but included so we can render magnet links
# without querying sql again.
| "info_hash": t.info_hash.hex(),
"filesize": t.filesize,
"uploader_id": t.uploader_id,
"main_category_id": t.main_category_id,
"sub_category_id": t.sub_category_id,
"comment_count": t.comment_count,
# XXX all the bitflags are numbers
... |
jasminka/goska | goska/wsgi.py | Python | bsd-3-clause | 385 | 0.002597 | """
WSGI con | fig for goska project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "goska.settings")
from django.core.w | sgi import get_wsgi_application
application = get_wsgi_application()
|
GovReady/govready-q | siteapp/migrations/0022_remove_project_title.py | Python | gpl-3.0 | 1,363 | 0.002935 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-12-10 17:17
from __future__ import unicode_literals
from django.db import migrations
# Move project.title into project.root_task.title_override before
# dropping the project.title column if project.title != project.root_task.module.title.
def forwards_func(... | ect.root_task.title
project.save()
class Migration(migrations.Migration):
dependencies = [
( | 'siteapp', '0021_auto_20171029_2217'),
('guidedmodules', '0034_title_override'),
]
operations = [
migrations.RunPython(forwards_func, reverse_func),
migrations.RemoveField(
model_name='project',
name='title',
),
]
|
isudox/leetcode-solution | python-algorithm/leetcode/problem_247.py | Python | mit | 1,241 | 0.000806 | """247. Strobogrammatic Number II
https://leetcode.com/problems/strobogrammatic-number-ii/
Given an integer n, return all the strobogrammatic numbers that
are of length n. You may return the answer in any order.
A strobogrammatic number is a number that looks the same when
rotated 180 degrees (looked at upside down).... | ammatic(self, n: int) -> List[str]:
def helper(k: int) -> List[str]:
list1 = ["0", "1", "8"]
list2 = ["00", "11", "69", "88", "96"]
if k == 1:
return list1
if k == 2:
return list2
ret = []
prev = k - 2 if k %... | interval in (list2 if k % 2 == 0 else list1):
ret.append(num[:split] + interval + num[split:])
return ret
ans = helper(n)
ans = [num for num in ans if len(num) == 1 or not num.startswith('0')]
return ans
|
dnjohnstone/hyperspy | hyperspy/misc/machine_learning/import_sklearn.py | Python | gpl-3.0 | 1,124 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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.
#
# HyperSpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy o... |
KevinGoodsell/caduceus | test/test_handle.py | Python | epl-1.0 | 5,924 | 0.002532 | # Copyright 2012 Kevin Goodsell
#
# This software is licensed under the Eclipse Public License (EPL) V1.0.
from __future__ import with_statement
import time
import unittest
import STAF
class HandleTests(unittest.TestCase):
def assertSTAFResultError(self, rc, func, *args, **kwargs):
try:
fun... | mit, 'local', 'queue', 'get type STAF/RequestComplete')
# Check retained result
result = h.submit('local', 'service', ['free request', req])
self.assertEqual(result['rc'], '0')
self.assertEqual(resul | t['result'], 'PONG')
# QUEUE AND RETAIN
req = h.submit('local', 'ping', 'ping', STAF.REQ_QUEUE_RETAIN)
self.assertTrue(req.isdigit())
time.sleep(2)
# Check queued result
result = h.submit('local', 'queue', 'get type STAF/RequestComplete')
... |
jbedorf/tensorflow | tensorflow/python/ops/ragged/ragged_map_fn_op_test.py | Python | apache-2.0 | 10,897 | 0.00257 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | , [6, 7]]],
expected_output=[6, 22],
result_dtype=dtypes.int64,
),
# [d1] -> [d1, (d2)]
dict(
fn=mo.range,
elems=[4, 0, 2],
expected_output=[[0, 1, 2, 3], [], [0, 1]],
result_dtype=ragged_tensor.RaggedTensorT | ype(
dtype=dtypes.int64, ragged_rank=1),
),
# [d1] -> [d1, (d2), (d3)]
dict(
fn=lambda x: ragged_math_ops.range(mo.range(x)),
elems=[5, 0, 3],
expected_output=[[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]], [],
[[], [0], [0, 1]]],
... |
spookylukey/django-autocomplete-light | test_project/fk_autocomplete/autocomplete_light_registry.py | Python | mit | 196 | 0.005102 | i | mport autocomplete_light
from cities_light.models import City
autocomplete_light.register(City, search_fields=('search_names',),
autocomplete_js_attributes={'placeho | lder': 'city name ..'})
|
kevinleake01/textpatgen | 12-workspace-py/tpl-py-0001.py | Python | gpl-2.0 | 774 | 0.011628 | #!/usr/bin/env python
####################################
#
# --- TEXTP | ATGEN TEMPLATE ---
#
# Users can change the output by editing
# this file directly.
#
####################################
import sys
sys.stdout.write('####################################\n')
sys.stdout.write('#\n')
sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n')
sys.stdout.write('#\n')
sys.stdout.write('# -... | in range(0, 16):
for width in range(0, 15):
sys.stdout.write('X-%04X ' % num)
num=num+1
width=width+1
length=length+1
sys.stdout.write('X-%04X\n' % num)
num=num+1
sys.stdout.write('# -- End of file.\n');
sys.stdout.flush()
|
unho/translate | translate/convert/csv2po.py | Python | gpl-2.0 | 9,967 | 0.000602 | # -*- coding: utf-8 -*-
#
# Copyright 2003-2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... | a pofile, and returns it. uses templatepo if
given at construction
"""
self.csvfile = thecsvfile
if self.pofile is None:
self.pofile = po.pofile()
mergemode = False
else:
mergemode = True
if self.pofile.units and self.pofile.units[0].i... | self.pofile.updateheader(content_type="text/plain; charset=UTF-8",
content_transfer_encoding="8bit")
else:
targetheader = self.pofile.makeheader(charset="UTF-8",
encoding="8bit")
targetheader.addnote(... |
smart-solution/icy | icy_sale_webkit/__init__.py | Python | lgpl-3.0 | 1,084 | 0.000923 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011-2013 Serpent Consulting Services (<http://www.serpentcs.com>)
#
# This program is free software: you can redistribute it and/or modify
# it... | 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/>.
#
########################### | #################################################
import report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
openstack/mistral | mistral/tests/unit/services/test_workbook_service.py | Python | apache-2.0 | 8,847 | 0 | # Copyright 2014 - Mirantis, Inc.
# Copyright 2020 Nokia Software.
#
# 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... | self.assertEqual('my_wb', second_wb.name)
self.assertEqual(second_namespace, second_wb.namespace)
def test_create_workbook_with_default_namespace(self):
wb_db = wb_service.create_workbook_v2(WORKBOOK)
self.assertIsNotNone(wb_db)
self.as | sertEqual('my_wb', wb_db.name)
self.assertEqual('', wb_db.namespace)
db_api.delete_workbook('my_wb')
def test_update_workbook(self):
namespace = 'test_workbook_service_0123_namespace'
# Create workbook.
wb_db = wb_service.create_workbook_v2(WORKBOOK, namespace=namespace)
... |
912/M-new | virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/creation.py | Python | gpl-2.0 | 4,546 | 0.00176 | from django.conf import settings |
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND'
@cached_property
def ... | ettings, 'POSTGIS_TEMPLATE', 'template_postgis')
with self.connection.cursor() as cursor:
cursor.execute('SELECT 1 FROM pg_database WHERE datname = %s LIMIT 1;', (template_postgis,))
if cursor.fetchone():
return template_postgis
return None
def sql_indexes_fo... |
adamwen829/instapush-py | instapush/instapush.py | Python | mit | 2,190 | 0.00411 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
import json
import requests
class Instapush(object):
def __init__(self, user_token):
self.user_token = user_token
self._headers = {}
@property
def headers(self):
if not self._headers:... | id
self.secret = secret
self._headers = {}
@property
def headers(self):
if not self._headers:
self._headers = {'Content-Type': 'application/json',
'x-instapush-appid': self.appid,
'x-instapush-appsecret': self.secret}
... | oad = {'title': event_name,
'trackers': trackers,
'message': message}
ret = requests.post('http://api.instapush.im/v1/events/add',
headers=self.headers,
data=json.dumps(payload)).json()
return ret
def lis... |
xtso520ok/mitmproxy | libmproxy/console/flowlist.py | Python | mit | 8,997 | 0.002223 | from __future__ import absolute_import
import urwid
from . import common
def _mkhelp():
text = []
keys = [
("A", "accept all intercepted flows"),
("a", "accept this intercepted flow"),
("C", "clear flow list or eventlog"),
("d", "delete flow"),
("D", "duplicate flow"),
... | fied.")
return
self.state.revert(self.flow)
self.master.sync_list_view()
self.master.statusbar.message("Reverted.")
elif key == "w":
self.master.prompt_onekey(
"Save",
(
("all flows", "a"),
... | ),
self.save_flows_prompt,
)
elif key == "X":
self.flow.kill(self.master)
elif key == "enter":
if self.flow.request:
self.master.view_flow(self.flow)
elif key == "|":
self.master.path_prompt(
"... |
Tehsmash/networking-cisco | networking_cisco/plugins/cisco/common/utils.py | Python | apache-2.0 | 3,017 | 0 | # Copyright 2015 Cisco Systems, 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... | wraps
import imp
import time
from oslo_log import log as logging
from neutron_lib import exceptions as nexception
from networking_cisco._i18n import _
LOG = logging.getLogger(__name__)
class DriverNotFound(nexception.NotFound):
m | essage = _("Driver %(driver)s does not exist")
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
"""Retry calling the decorated function using an exponential backoff.
Reference: http://www.saltycrane.com/blog/2009/11/trying-out-retry
-decorator-python/
:param ExceptionToCheck: the exception ... |
daniLOLZ/variaRoba | Python/32.py | Python | mit | 1,364 | 0.040323 | # Hangman for real tho(t)
import random
def pickWord(words):
toReturn = random.choice(lol)
return toReturn
def drawHangman(parts):
if parts >= 1:
print(" O")
if parts >= 4:
print("/|\\") |
elif parts >= 3:
print("/|")
elif parts >= 2:
print(" |")
if parts >= 6:
print("/ \\")
elif parts == 5:
pri | nt("/")
print("\n")
with open("scrabble.txt", "r") as paroleFile:
lol = paroleFile.read().split("\n")
word = pickWord(lol)
completo = False
okLetter = False
guessedLetters = set()
progress = ["_" for i in range(len(word))]
remainingLetters = len(word)
guesses = 0
while not completo:
okLetter = False
for i in pro... |
ravenac95/virtstrap | virtstrap-core/virtstrap/project.py | Python | mit | 3,644 | 0.000823 | """
virtstrap.project
-----------------
This module contains all the abstractions for dealing with a Project.
Using this object simplifies creating commands that are used to manage
the project.
"""
import os
import sys
from virtstrap import constants
from virtstrap.config import VirtstrapConfig
from virtstrap.utils i... | self._options = opti | ons
def _find_project_dir(self):
return find_project_dir()
@property
def name(self):
return self._project_name
@property
def config_file(self):
if not os.path.isfile(self._config_file):
return None
return self._config_file
def set_options(self, opt... |
contactr2m/remote_repo | src/rating/middleware.py | Python | mit | 625 | 0.0016 | try:
from hashlib import md5
except ImportError:
from md5 import md5
class ratingMiddleware(object):
def process_request(self, request):
request.rating_token = self.generate_token(request)
def generate_token(self, request):
raise NotImple | mentedError
class ratingIpMiddleware(ratingMiddleware):
def generate_token(self, request):
return request.META['REMOTE_ADDR']
class ratingIpUseragentMiddleware(ratingMiddleware):
def generate_token(self, request):
s = ''.join((request.META['REMOTE_ADDR'], reques | t.META['HTTP_USER_AGENT']))
return md5(s).hexdigest()
|
scipy/scipy-svn | scipy/stats/tests/test_mstats_basic.py | Python | bsd-3-clause | 20,295 | 0.034097 | """
Tests for the stats.mstats module (support for maskd arrays)
"""
import numpy as np
from numpy import nan
import numpy.ma as ma
from numpy.ma import masked, nomask
import scipy.stats.mstats as mstats
from numpy.testing import TestCase, run_module_suite
from numpy.ma.testutils import assert_equal, assert_almost_e... | .rankdata(x,axis=0),[[1,1,1,1,1],[2,2,2,2,2,]])
class TestCorr(TestCase):
#
def test_pearsonr(self):
"Tests some computations of Pearson's r"
x = ma.arange(10)
olderr = np.seterr(all='ignore')
try:
assert_almost_equal(mstats.pearsonr(x,x)[0], 1.0)
assert... | x = ma.array(x, mask=True)
pr = mstats.pearsonr(x,x)
finally:
np.seterr(**olderr)
assert_(pr[0] is masked)
assert_(pr[1] is masked)
#
def test_spearmanr(self):
"Tests some computations of Spearman's rho"
(x, y) = ([5.05,6.75,3.21,2.66],[... |
bitglue/pyflakes | pyflakes/test/test_other.py | Python | mit | 42,084 | 0 | """
Tests for various Pyflakes behavior.
"""
from sys import version_info
from pyflakes import messages as m
from pyflakes.test.harness import TestCase, skip, skipIf
class Test(TestCase):
def test_duplicateArgs(self):
self.flakes('def fu(bar, bar): pass', m.DuplicateArgument)
def test_localReferen... | pass
def a(): pass
except:
pass
''', m.RedefinedWhileUnused)
def test_redefinedIfElseInListComp(self):
"""
Test that shadowi | ng a variable in a list comprehension in
an if and else block does not raise a warning.
"""
self.flakes('''
if False:
a = 1
else:
[a for a in '12']
''')
@skipIf(version_info >= (3,),
'in Python 3 list comprehensions execute in a se... |
i3visio/osrframework | osrframework/wrappers/disqus.py | Python | agpl-3.0 | 3,885 | 0.004377 | ################################################################################
#
# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Softwa... | # Strings that will imply that the query number is not appearing
self.validQuery = {}
# The regular expression '.+' will match any query.
#self.validQuery["phonefy"] = ".*"
self.validQuery["usufy"] = ".+"
#self.validQuery["searchfy"] = ".*"
###################
... | = []
self.notFoundText["usufy"] = ["Page not found (404) - Disqus"]
#self.notFoundText["searchfy"] = []
#########################
# Fields to be searched #
#########################
self.fieldsRegExp = {}
# Definition of regular expressions to be searched in ph... |
Intel-Corporation/tensorflow | tensorflow/python/pywrap_tensorflow.py | Python | apache-2.0 | 3,448 | 0.008121 | # Copyright 2020 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... | l equivalent for py_extension.
# Externally in opensource we must enable exceptions to load the shared object
# by exposing the PyInit symbols with pybind. This error will only be
# caught internally or if someone changes the name of the target _pywrap_tensorflow_internal.
# This logic is used in other interna... | ing py_extension.
except ModuleNotFoundError:
pass
if _use_dlopen_global_flags:
pywrap_dlopen_global_flags.reset_dlopen_flags()
elif _can_set_rtld_local:
sys.setdlopenflags(_default_dlopen_flags)
except ImportError:
raise ImportError(
f'{traceback.format_exc()}'
f'\n\nFailed to load the... |
bcroq/kansha | kansha/app/comp.py | Python | bsd-3-clause | 15,658 | 0.001086 | # -*- coding:utf-8 -*-
# --
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
import cgi
import sys
import json
import time
import pstats
import urllib... | _manager.create_template_from_board(event.emitter, *event.data)
class MainTask(component.Task):
def __init__(self, app_title, theme, config, card_extensions, services_service):
self.app_title = app_title
self.theme = theme
self._services = services_service
self.ap | p_banner = config['pub_cfg']['banner']
self.favicon = config['pub_cfg']['favicon']
self.app = services_service(
Kansha,
self.app_title,
self.app_banner,
self.favicon,
self.theme,
card_extensions,
)
self.config = conf... |
CartoDB/cartoframes | cartoframes/data/clients/sql_client.py | Python | bsd-3-clause | 11,090 | 0.001623 | from ...io.managers.context_manager import ContextManager
COLLISION_STRATEGIES = ['fail', 'replace']
class SQLClient:
"""SQLClient class is a client to run SQL queries in a CARTO account.
It also provides basic SQL utilities for analyzing and managing tables.
Args:
credentials (:py:class:`Creden... | ut the schema of a table.
Args:
table_name (str): name of the table.
raw (bool, optional): return raw dict data if set to True.
Default False.
Example:
>>> sql.schem | a('table_name')
Column name Column type
-------------------------------------
cartodb_id number
the_geom geometry
the_geom_webmercator geometry
column1 string
column2 number
... |
webmasterraj/FogOrNot | flask/lib/python2.7/site-packages/pandas/io/tests/test_pytables.py | Python | gpl-2.0 | 175,872 | 0.008284 | import nose
import sys
import os
import warnings
import tempfile
from contextlib import contextmanager
import datetime
import numpy as np
import pandas
import pandas as pd
from pandas import (Series, DataFrame, Panel, MultiIndex, Categorical, bdate_range,
date_range, Index, DatetimeIndex, isnull)
... | yield filenames
else:
filenames = [ create_tempfile(path) ]
yield filenames[0]
finally:
for f in filenames:
| safe_remove(f)
# set these parameters so we don't have file sharing
tables.parameters.MAX_NUMEXPR_THREADS = 1
tables.parameters.MAX_BLOSC_THREADS = 1
tables.parameters.MAX_THREADS = 1
def _maybe_remove(store, key):
"""For tests using tables, try removing the table to be sure there is
no content f... |
timdelbruegger/freecopter | src/python3/sensorfusion/fusion_master.py | Python | mit | 987 | 0.004053 | from state.logging_state_provider import LoggingStateProviderWithListeners
from sensorfusion.height_provider import HeightProvider
from sensorfusion.attitude_provider import AttitudeProvider, AttitudeState
class SensorFusionMaster(LoggingStateProviderWithListeners):
"""
This class is responsib | le for taking the single sensor fusion results and integrating them into a VehicleState.
- AttitudeProvider (gyro, accelerometer, magnetometer) -> AttitudeState (orientation in air)
- HeightProvider (gps, ultrasonic sensor, barometer, attitude) -> HeightState (height above ground, vertical speed)
"""
... | ()
self.heightProvider = HeightProvider()
def update(self):
# this will trigger the heightProvider via the listener
attitude = self.attitudeProvider.update()
vehicle_state = self.heightProvider.update(attitude)
return vehicle_state
|
rebaltina/DAT210x | Module5/assignment5.py | Python | mit | 5,502 | 0.011087 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot') # Look Pretty
def plotDecisionBoundary(model, X, y):
fig = plt.figure()
ax = fig.add_subplot(111)
padding = 0.6
resolution = 0.0025
colors = ['royalblue','forestgreen','ghostwhite']
... | rifiable. In the real world, you wouldn't
# specify a random_state.
#
# .. your code here ..
from sklearn.cross_validation import train_test_split
data_train, data_test, label_train, label_test = train_test_split(X, y, test_size=0.33, random_state=1)
#
# TODO: Create an instance of SKLearn's Normalizer class and then ... | a_train)
# NOTE: The reason you only fit against your training data is because in a
# real-world situation, you'll only have your training data to train with!
# In this lab setting, you have both train+test data; but in the wild,
# you'll only have your training data, and then unlabeled data you want to
# apply your m... |
arruda/rmr | rmr/scripts/skoob_crawler.py | Python | mit | 1,068 | 0.011236 | # -*- coding: utf-8 -*-
import requests
import lxml
from lxml import html
main_url = "http://www.skoob.com.br"
def books_for_author(url=None):
"return the books of a given author"
print "acessing: %s" % url
books_found = []
r = requests.get(url)
root = lxml.html.fromstring(r.content)
... | ct("a.l15ab")[0].text_content()
books_found.append(title,)
# print title
next_page = None
try:
next_page = root.cssselect("div.proximo span.l13 a")[0].get("href")
books_found.extend(books_for_author(main_url+next_page))
except IndexError:
pass
return ... | thor(url)
print "============"
for book in books:
print book |
ppwwyyxx/tensorflow | tensorflow/python/training/saving/functional_saver.py | Python | apache-2.0 | 10,645 | 0.004039 | # Copyright 2015 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... | low.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_spec
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_io_ops... | nsorflow.python.ops import string_ops
from tensorflow.python.training.saving import saveable_hook
from tensorflow.python.training.saving import saveable_object
from tensorflow.python.training.saving import saveable_object_util
from tensorflow.python.util import nest
class _SingleDeviceSaver(object):
"""Saves and re... |
apbard/scipy | scipy/optimize/optimize.py | Python | bsd-3-clause | 105,325 | 0.000218 | #__docformat__ = "restructuredtext en"
# ******NOTICE***************
# optimize.py module by Travis E. Oliphant
#
# You may copy and use this module as you see fit with no
# guarantee implied provided you keep this notice in all copies.
# *****END NOTICE************
# A collection of optimization algorithms. Version ... | """
The Hessian matrix of the Rosenbrock f | unction.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
See Also
--------
rosen, rosen_der, rosen_hess_prod
"""
... |
s20121035/rk3288_android5.1_repo | cts/tools/utils/buildCts.py | Python | gpl-3.0 | 16,411 | 0.01304 | #!/usr/bin/python
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | r match in pattern.finditer(content):
result[match.group(1)] = match.group(2)
stream.close()
return result
class CtsBuilder(object):
"""Main class for generating test descriptio | ns and test plans."""
def __init__(self, argv):
"""Initialize the CtsBuilder from command line arguments."""
if len(argv) != 6:
print 'Usage: %s <testRoot> <ctsOutputDir> <tempDir> <androidRootDir> <docletPath>' % argv[0]
print ''
print 'testRoot: Directory under which to search for C... |
tobspr/LUI | Demos/B_Frame.py | Python | mit | 1,147 | 0.000872 |
from DemoFramework import DemoFramework
from LUIVerticalLayout import LUIVerticalLayout
from LUIFrame import LUIFrame
from LUILabel import LUILabel
from LUIButton import LUIButton
from LUIObject import LUIObject
import random
f = DemoFramework()
f.prepare_demo("LUIFrame")
# Constructor
f.add_constructor_parameter(... | ": lambda: frame.set_size(300, 160),
| "Fit to children": lambda: frame.clear_size(),
})
run()
|
fictorial/pygameui | pygameui/textfield.py | Python | mit | 3,128 | 0.000959 | import pygame
import view
import label
import callback
class TextField(view.View):
"""Editable single line of text.
There are no fancy keybindings; just backspace.
Signals
on_text_change(text_field, text)
on_return(text_field, text)
"""
def __init__(self, frame, text='', plac... | text or ''
self.placeholder = placeholder
| self.label = label.Label(pygame.Rect((0, 0), frame.size),
text or placeholder)
self.label.halign = label.LEFT
self.add_child(self.label)
self.enabled = True
self.max_len = None
self.secure = False
self.on_return = callback.Signal()
... |
alxgu/ansible | lib/ansible/modules/remote_management/manageiq/manageiq_alerts.py | Python | gpl-3.0 | 12,976 | 0.002004 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Red Hat Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | in self.miq_expression:
# miq_expression is a field that needs a special case, because
# it's returned surrounded by a dict named exp even though we don't
# send it with that dict.
self.miq_expression = self.miq_expression['exp']
def __eq__(self, othe... | ect to execute alert management operations in manageiq.
"""
def __init__(self, manageiq):
self.manageiq = manageiq
self.module = self.manageiq.module
self.api_url = self.manageiq.api_url
self.client = self.manageiq.client
self.alerts_url = '{api_url}/alert_definitions'.... |
sivakuna-aap/superdesk-core | superdesk/io/feed_parsers/wenn_parser.py | Python | agpl-3.0 | 3,652 | 0.002738 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import date... | /feed.wenn.com/xmlns/2010/03/wenn_cm'
GEORSS_NS = 'http://www.georss.org/georss'
def can_parse(self, xml):
return xml.tag == self.qname('feed', self.ATOM_NS) and len(xml.findall(
self.qname('NewsManagement', self.WENN_NM_NS))) > 0
def parse(self, xml, provider=None):
itemList =... | for entry in xml.findall(self.qname('entry', self.ATOM_NS)):
item = {}
self.set_item_defaults(item)
self.parse_content_management(item, entry)
self.parse_news_management(item, entry)
item['body_html'] = self.get_elem_content(entr... |
JeffHeard/sondra | sondra/files.py | Python | apache-2.0 | 7,919 | 0.001515 | from functools import lru_cache
import os
import rethinkdb as r
from sondra.document.schema_parser import ValueHandler
try:
from werkzeug.utils import secure_filename
except ImportError:
import re
def secure_filename(name):
name = re.sub(r'\s+', '-', name) # Replace white space with dash
... | in a concrete class")
def store_file(self, collection, ident_ext, stream):
raise NotImplementedError("Implement store_stream in an concrete class")
def delete_file(self, collection, ident_ext):
raise NotImplementedError("Implement delete_file in a concrete class")
def delete_from_collecti... | delete_file(collection, ident)
self._table(collection).get(id).delete().run(self._conn)
def delete_for_document(self, document, key=None):
if key is not None:
existing = self._table(document.collection)\
.get_all(document, index='document')\
.filter({'key... |
rule0x42/education | Python/daysBetweenDates.py | Python | gpl-3.0 | 2,697 | 0 | # Define a daysBetweenDates procedure that would produce the
# correct output if there was a correct nextDay procedure.
#
# Udacity course work
def isLeapYear(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
def... | if month1 == month2:
# 'assert not' makes this true for a result
# of: days = 0
return day1 < day2
return False
def nextDay(year, month, day):
| """Simple version: assume every month has 30 days"""
if day < daysInMonth(year, month):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
""... |
meirwah/st2contrib | packs/hubot/actions/post_result.py | Python | apache-2.0 | 5,619 | 0.00089 | import json
import httplib
import requests
import six
import pyaml
from six.moves.urllib.parse import urljoin
from st2actions.runners.pythonrunner import Action
__all__ = [
'PostResultAction'
]
def _serialize(data):
return pyaml.dump(data)
def format_possible_failure_result(result):
'''
Error resu... | body['whisper'] = whisper
data = json.du | mps(body)
self.logger.info(data)
response = requests.post(url=url, headers=headers, data=data)
if response.status_code == httplib.OK:
self.logger.info('Message successfully posted')
else:
self.logger.exception('Failed to post message: %s' % (response.text))
... |
SE2Dev/PyCoD | __init__.py | Python | mit | 158 | 0 | # <pep8 compliant>
from .xmodel import Model
from .xanim import Anim
from .san | im | import SiegeAnim
version = (0, 3, 0) # Version specifier for PyCoD
|
amazinger2013/OpenSesame | libqtopensesame/items/sketchpad.py | Python | gpl-3.0 | 1,289 | 0.013964 | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as pub | lished by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenSesame is distributed in the hope | that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OpenSesame. If not, see <http://www.gnu.org/li... |
agustinhenze/nikola.debian | docs/sphinx/conf.py | Python | mit | 8,386 | 0 | # -*- coding: utf-8 -*-
#
# Nikola documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 22 17:43:37 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.
#
# Al... |
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this director | y. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typ... |
saltukalakus/elastalert | elastalert/kibana.py | Python | apache-2.0 | 13,457 | 0.001115 | # -*- coding: utf-8 -*-
import urllib
from util import EAException
dashboard_temp = {'editable': True,
u'failover': False,
u'index': {u'default': u'NO_TIME_FILTER_OR_INDEX_PATTERN_NOT_MATCHED',
u'interval': u'none',
u'patte... | u'group': [u'default'],
u'interactive': True,
u'interval': u'1m',
u'intervals': [u'auto',
u'1s',
... | u'1m',
u'5m',
u'10m',
u'30m',
u'1h',
... |
ishikota/PyPokerEngine | tests/examples/players/console_player_test.py | Python | mit | 2,602 | 0.009608 | from tests.base_unittest import BaseUnitTest
from examples.players.console_player import ConsoleP | layer
class ConsolePlayerTest(BaseUnitTest):
def setUp(self):
self.valid_actions = [\
{'action': 'fold', 'amount': 0},\
{'action': 'call', 'amount': 10},\
{'action': 'raise', 'amount': {'max': 105, 'min': 15}}\
]
self | .round_state = {
'dealer_btn': 1,
'street': 'preflop',
'seats': [
{'stack': 85, 'state': 'participating', 'name': u'player1', 'uuid': 'ciglbcevkvoqzguqvnyhcb'},
{'stack': 100, 'state': 'participating', 'name': u'player2', 'uuid': 'zjttlanhlvpqzebrwmieho'}
],
'... |
plenario/plenario | config.py | Python | mit | 220 | 0.004545 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'd | b_r | epository')
SQLALCHEMY_TRACK_MODIFICATIONS = False |
hzlf/openbroadcast | website/shop/shop/tests/util.py | Python | gpl-3.0 | 6,686 | 0.001047 | #-*- coding: utf-8 -*-
from decimal import Decimal
from django.contrib.auth.models import User, AnonymousUser
from django.core.exceptions import ImproperlyConfigured
from django.test.testcases import TestCase
from shop.addressmodel.models import Address, Country
from shop.models.cartmodel import Cart
from shop.util.add... | (self.request, 'user', self.user)
res = get_shipping_address_from_request(self.request)
self.assertEqual(res, None)
def test_get_shipping_address_from_request_with_preset_and_user(self):
setattr(self.request, 'user', self.user)
assign_address_to_request(self.request, self.address, s... | d_session(self):
assign_address_to_request(self.request, self.address, shipping=True)
res = get_shipping_address_from_request(self.request)
self.assertEqual(res, self.address)
#==========================================================================
# Billing
#====================... |
NoMod-Programming/PyRobotC | examples/InTheZone/FantasticBox - Tank Control.py | Python | mit | 3,175 | 0.013543 | #region config
vex.pragma(config, I2C_Usage, I2C1, i2cSensors)
vex.pragma(config, Sensor, in1, leftLight, sensorLineFollower)
vex.pragma(config, Sensor, in2, middleLight, sensorLineFollower)
vex.pragma(config, Sensor, in3, rightLight, sensorLineFollower)
vex.pragma(config, Sensor, in4, wristPot, sensorPotentiometer)
ve... | EncoderOnI2CPort, _, AutoAssign)
vex.pragma(config, Sensor, I2C_3, _,sensorQuadEncoderOnI2CPort, _, AutoAssign)
vex.pragma(c | onfig, Sensor, I2C_4, _,sensorQuadEncoderOnI2CPort, _, AutoAssign)
vex.pragma(config, Sensor, I2C_5, _,sensorQuadEncoderOnI2CPort, _, AutoAssign)
vex.pragma(config, Motor, port1, frontRightMotor, tmotorVex393_HBridge, openLoop, reversed)
vex.pragma(config, Motor, port2, rearRightMotor, tmotorVex393_MC29, openLoop, reve... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/boto/exception.py | Python | agpl-3.0 | 17,106 | 0.00152 | # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# 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 res... | r response. If body isn't present,
# then just ignore the error response.
if self.body:
# Check if it looks like a ``dict``.
if hasattr(self.body, 'items'):
# It's not a string, so trying to parse it will fail.
# But since it's data, we can work wi... | uestId', None)
if 'Error' in self.body:
# XML-style
error = self.body.get('Error', {})
self.error_code = error.get('Code', None)
self.message = error.get('Message', None)
else:
# JSON-sty... |
apache/climate | obs4MIPs/obs4MIPs_process.py | Python | apache-2.0 | 19,825 | 0.015687 | #!/usr/bin/env python
#
# 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
# "... | data_structure'])
cmor.set_cur_dataset_attribute( 'source_type', rc['source_type' ])
cmor.set_cur_dataset_attribute( 'source_id' | , rc['source_id' ])
cmor.set_cur_dataset_attribute( 'realm', rc['realm' ])
cmor.set_cur_dataset_attribute( 'obs_project', rc['obs_project' ])
cmor.set_cur_dataset_attribute( 'processing_version',
rc['processing_version'] )
... |
SoftwareHeritage/swh-web-ui | swh/web/tests/api/views/test_release.py | Python | agpl-3.0 | 3,819 | 0.000786 | # Copyright (C) 2015-2019 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from datetime import datetime
from hypothesis import given
... | =0
),
offset=0,
negative_utc=False,
),
message=b"sample release message",
name=b"sample release",
synthetic=False,
target=hash_to_bytes(target),
target_type=target_type,
)
archive_dat... | k_api_get_responses(api_client, url, status_code=200)
expected_release = archive_data.release_get(new_release_id)
if target_type == ObjectType.CONTENT:
url_args = {"q": "sha1_git:%s" % target}
else:
url_args = {"sha1_git": target}
target_url = reverse(
... |
BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/File.py | Python | gpl-2.0 | 4,640 | 0.003017 | # Copyright 1999 by Jeffrey Chang. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Code for more fancy file handles.
Classes:
UndoHandle File object decorator with sup... |
Strip the SGML tags from str.
"""
if not str: # empty string, don't do anything.
return ''
# I need to make sure that I don't return an empty string if
# the buffer is not empty. This can happen if there's a newline
# chara... | s_newline = str[-1] in ['\n', '\r']
self._parser.data = '' # clear the parser's data (don't reset)
self._parser.feed(str)
if self._parser.data:
str = self._parser.data
elif is_newline:
str = '\n'
else:
... |
zwadar/pyqode.core | examples/modes/right_margin.py | Python | mit | 640 | 0.007813 | """
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys
from pyqode.qt import QtWidgets
from pyqode.cor | e.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import RightMarginMode
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
editor = CodeEdit()
editor.backend.start(server.__file__)
editor.resize(800, 600)
margin = editor.modes.append(RightMarginMod... |
editor.close()
del editor
del app
|
ubirch/aws-tools | virtual-env/lib/python2.7/site-packages/boto/sqs/message.py | Python | apache-2.0 | 9,892 | 0.002932 | # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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, copy, modi... | an encode method that accepts a value of the same type as the body
parameter of the constructor and returns a string of characters that are able to be stored in an
SQS message body (see rules above).
The Message class must provide a decode method that accepts a string of characters that c | an be
stored (and probably were stored!) in an SQS message and return an object of a type that is consistent
with the "body" parameter accepted on the class constructor.
The Message class must provide a __len__ method that will return the size of the encoded message
that would be stored in SQS based on the current sta... |
rampantpixels/rpmalloc-benchmark | configure.py | Python | unlicense | 14,222 | 0.037126 | #!/usr/bin/env python
"""Ninja build configurator for foundation library"""
import sys
import os
import copy
sys.path.insert(0, os.path.join('build', 'ninja'))
import generator
generator = generator.Generator(project = 'rpmalloc', variables = {'bundleidentifier': 'com.rampantpixels.rpmalloc.$(binname)', 'nowarning... | nchmark', 'test']
generator.bin(module = 'hoard', sources = ['benchmark.c'], binname = 'benchmark-hoard', basepath = 'benchmark', implicit_deps = [hoard_lib, benchmark_lib, test_lib], libs = hoard_depend_libs, includepaths = includepaths, variables = hoard_variables)
gperftoolsincludepaths = [
os.path.join('benchmar... | 'gperftools', 'src', 'base'),
os.path.join('benchmark', 'gperftools', 'src', target.get())
]
gperftoolsbasesources = [
'dynamic_annotations.c', 'linuxthreads.cc', 'logging.cc', 'low_level_alloc.cc', 'spinlock.cc',
'spinlock_internal.cc', 'sysinfo.cc'
]
if not target.is_windows():
gperftoolsbasesources += ['thread_l... |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/game_rpg_simulation1.py | Python | mit | 3,330 | 0.007808 | # game_rpg_simulation.py written by Duncan Murray 30/3/2015
import os
import random
def main():
"""
Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another... | e']
def __str__(self):
res = ''
res += 'Character : ' + self.name + '\n'
res += 'Statistics : STA=' + str(self.sta) + ' | , INT=' + str(self.int) + ', STR=' + str(self.str) + '\n'
res += 'Status : ' + self.status + '\n'
res += 'Carrying : '
for i in self.backpack:
res += i + ', '
res += str(self.gold) + ' Gold'
return res
class Battle():
"""
manages a fight betw... |
johnctitus/troposphere | examples/VPC_With_VPN_Connection.py | Python | bsd-2-clause | 6,123 | 0 | # Converted from VPC_With_VPN_Connection.template located at:
# http://aws.amazon.com/cloudformation/aws-cloudformation-templates/
from troposphere import Join, Output
from troposphere import Parameter, Ref, Tags, Template
from troposphere.ec2 import PortRange
from troposphere.ec2 import NetworkAcl
from troposphere.ec... | e a stack \
from this template.""")
VPNAddress = t.add_parameter(Parameter(
"VPNAddress",
Type="String",
Description="IP Address of your VPN device",
| MinLength="7",
AllowedPattern=r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})",
MaxLength="15",
ConstraintDescription="must be a valid IP address of the form x.x.x.x",
))
OnPremiseCIDR = t.add_parameter(Parameter(
"OnPremiseCIDR",
ConstraintDescription=(
"must be a valid IP CIDR range of t... |
StegSchreck/RatS | RatS/base/base_ratings_parser.py | Python | agpl-3.0 | 7,162 | 0.002932 | import os
import sys
import time
from bs4 import BeautifulSoup
from progressbar import ProgressBar
class RatingsParser:
def __init__(self, site, args):
| self.site = site
self.args = args
if not self.site.CREDENTIALS_VALID:
return
self.m | ovies = []
self.movies_count = 0
self.site.open_url_with_521_retry(self.site.MY_RATINGS_URL)
self.exports_folder = os.path.abspath(
os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, "RatS", "exports"
)
)
if not os.path.exists... |
athoik/enigma2 | lib/python/Plugins/Extensions/DVDBurn/TitleList.py | Python | gpl-2.0 | 17,688 | 0.025328 | import DVDProject, TitleList, TitleCutter, TitleProperties, ProjectSettings, DVDToolbox, Process
from Screens.Screen import Screen
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.HelpMenu import HelpableScreen
from Screens.TaskView import JobView
from Components.Task impor... | d.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
... | position="0,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;19" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"... |
Azure/azure-sdk-for-python | sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_prefixes_operations.py | Python | mit | 11,684 | 0.004622 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | """Creates or updates the peering prefix.
:param resource_group_name: The resource group nam | e.
:type resource_group_name: str
:param peering_service_name: The peering service name.
:type peering_service_name: str
:param prefix_name: The prefix name.
:type prefix_name: str
:param peering_service_prefix: The IP prefix for an peering.
:type peering_service_... |
UNH-CORE/RVAT-Re-dep | pyrvatrd/processing.py | Python | mit | 35,800 | 0.002207 | # -*- coding: utf-8 -*-
"""This module contains classes and functions for processing data."""
from __future__ import division, print_function
import numpy as np
from pxl import timeseries as ts
from pxl.timeseries import calc_uncertainty, calc_exp_uncertainty
import matplotlib.pyplot as plt
from scipy.io import loadma... | section
nrun = int(nrun)
section_raw_dir = os.path.join("Data", "Raw", section)
if nrun < 0:
runs = []
for f in os.listdir(section_raw_dir):
try:
runs.append( | int(f))
except ValueError:
pass
self.nrun = sorted(runs)[nrun]
else:
self.nrun = nrun
self.raw_dir = os.path.join(section_raw_dir, str(self.nrun))
self.loaded = False
self.t2found = False
self.not_loadable = False
... |
armink/rt-thread | tools/buildbot.py | Python | apache-2.0 | 1,963 | 0.001528 | import os
import sys
def usage():
print('%s all -- build all bsp' % os.path.basename(sys.argv[0]))
print('%s clean -- clean all bsp' % os.path.basename(sys.argv[0]))
print('%s project -- update all prject files' % os.path.basename(sys.argv[0]))
BSP_ROOT = os.path.join("..", "bsp")
if len(sys.argv) ... |
os.system('scons --directory=' + project_dir + command)
if os.path.isfile(os.path.join(project_dir, 'template.uvprojx')):
print('prepare MDK5 project file on ' + project_dir)
command = ' --target=mdk5 -s'
os.system('scons --directory=' + project_dir + command)... | ' --target=iar -s'
os.system('scons --directory=' + project_dir + command)
sys.exit(0)
else:
usage()
sys.exit(0)
projects = os.listdir(BSP_ROOT)
for item in projects:
project_dir = os.path.join(BSP_ROOT, item)
if os.path.isfile(os.path.join(project_dir, 'SConstruct')):
if os.s... |
andrei-karalionak/ggrc-core | test/integration/ggrc_workflows/converters/test_workflow_export_csv.py | Python | apache-2.0 | 11,531 | 0.002168 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for workflow object exports."""
from os.path import abspath, dirname, join
from flask.json import dumps
from ggrc.app import app
from ggrc_workflows.models import Workflow
from integration.ggrc im... | w and cycle mappings """
data = [
{
"object_name": "Cycle", # cycle with title wf-1
"filters": {
"expression": {
"op": {"name": "relevant"},
"object_name": "Workflow",
"slugs": ["wf-1"],
},
... | "expression": {
"op": {"name": "relevant"},
"object_name": "__previous__",
"ids": ["0"],
},
},
"fields": "all",
}, {
"object_name": "CycleTaskGroup", # two cycle groups
"filters": {
... |
buriburisuri/ebgan | mnist_ebgan_generate.py | Python | mit | 943 | 0.003181 | import sugartensor as tf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from model import *
__author__ = 'namju.kim@kakaobrain.com'
# set log level to debug
tf.sg_verbosity(10)
#
# hyper parameters
#
batch_size = 100
# random uniform seed
z = tf.random_uniform((batch_size, z_dim))
# ge... | g_restore(sess, tf.train.latest_checkpoint('asset/train'), category='generator')
# run generator
imgs = sess.run(gen.sg_squeeze())
# plot result
_, ax = plt.subplots(10, 10, sharex=True, sharey=True)
for i in range(10):
for j in range(10):
ax[i][j].imshow(imgs[i * 10 + j], 'gra... | )
ax[i][j].set_axis_off()
plt.savefig('asset/train/sample.png', dpi=600)
tf.sg_info('Sample image saved to "asset/train/sample.png"')
plt.close()
|
lehoanganh/kcsdb | chef-repo/.chef/murder-kcsd/dist/BitTornado/BT1/PiecePicker.py | Python | apache-2.0 | 11,915 | 0.004784 | # Written by Bram Cohen
# see LICENSE.txt for license information
from random import randrange, shuffle
from BitTornado.clock import clock
try:
True
except:
True = 1
False = 0
class PiecePicker:
def __init__(self, numpieces,
rarest_first_cutoff = 1, rarest_first_priority_cutoff = 3,
... | erseed = False
self.seeds_connected = 0
self._init_interests()
def _init_interests(self):
self.interests = [[] for x in xrange(self.priority_step)]
self.level_in_interests = [self.p | riority_step] * self.numpieces
interests = range(self.numpieces)
shuffle(interests)
self.pos_in_interests = [0] * self.numpieces
for i in xrange(self.numpieces):
self.pos_in_interests[interests[i]] = i
self.interests.append(interests)
def got_have(self, piece):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.