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 |
|---|---|---|---|---|---|---|---|---|
vishnevskiy/battlenet | tests/test_regions.py | Python | mit | 1,132 | 0.001767 | import os
import battlenet
try:
import unittest2 as unittest
except ImportError:
import unittest as unittest
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_KEY')
class RegionsTest(unittest.TestCase):
def setUp(self):
self.connection = battlenet.Connecti... | ttlenet.KOREA)
self.assertTrue(len(realms) > 0)
def test_tw(self):
realms = self.connection.get_all_realms(battlenet.TAIWAN)
self.assertTrue(len(realms) > 0)
def test_cn(self):
realms = self.connection.get_all_realms(battlenet.CHINA)
| self.assertTrue(len(realms) > 0)
def tearDown(self):
del self.connection
if __name__ == '__main__':
unittest.main()
|
whymirror/unholy | decompyle/decompyle/dis_23.py | Python | mit | 6,551 | 0.005343 | """Disassembler of Python byte code into mnemonics."""
import sys
import types
from opcode_25 import *
from opcode_25 import __all__ as _opcodes_all
__all__ = ["dis","disassemble","distb","disco"] + _opcodes_all
del _opcodes_all
def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no ... | index += 1
addr = 0
line_incr = 0
labels = findlabels(code)
n = len(code)
i = 0
extended_arg = 0
free = None
while i < n: |
c = code[i]
op = ord(c)
if i >= addr:
lineno += line_incr
while table_index < table_length:
addr += byte_increments[table_index]
line_incr = line_increments[table_index]
table_index += 1
if line_incr:
... |
davislidaqing/Mcoderadius | toughradius/console/libs/pyforms/__init__.py | Python | agpl-3.0 | 12,706 | 0.009762 | #coding:utf-8
import sys,os
import copy
import re
import itertools
import net
"""basic from web.py: makes web apps (http://webpy.org)"""
__version__ = "0.37"
__author__ = [
"Aaron Swartz <me@aaronsw.com>",
"Anand Chitipothu <anandology@gmail.com>"
]
__license__ = "public domain"
__contributors__ = "see https:... | rage([(i.name, i.get_value()) for i in self.inputs])
d = property(_get_d)
class Input(object):
def __init__(self, name, *validators, **attrs):
self.name = name
self.validators = validators
self.attrs = attrs = AttributeList(attrs)
self.description = attrs.pop('descripti... | ('value', None)
self.pre = attrs.pop('pre', "")
self.post = attrs.pop('post', "")
self.hr = attrs.pop('hr',False)
self.note = None
self.id = attrs.setdefault('id', self.get_default_id())
if 'class_' in attrs:
attrs['class'] = attrs['class_']
... |
ooici/coi-services | ion/agents/platform/platform_agent_stream_publisher.py | Python | bsd-2-clause | 10,637 | 0.003572 | #!/usr/bin/env python
"""
@package ion.agents.platform.platform_agent_stream_publisher
@file ion/agents/platform/platform_agent_stream_publisher.py
@author Carlos Rueda
@brief Stream publishing support for platform agents.
"""
__author__ = 'Carlos Rueda'
import logging
import uuid
from coverage_model.paramet... | rror("%r: No stream_config given in CFG", self._platform_id)
return
for stream_name, stream_config in stream_info.iteritems():
self._construct_stream_and_publisher(stream_name, stream_config)
log.debug("%r: PlatformAgentStreamPublisher complete", self._platform_id)
def _co... | , stream_config):
if log.isEnabledFor(logging.TRACE): # pragma: no cover
log.trace("%r: _construct_stream_and_publisher: "
"stream_name:%r, stream_config:\n%s",
self._platform_id, stream_name,
self._pp.pformat(stream_config))
... |
skosukhin/spack | lib/spack/spack/cmd/__init__.py | Python | lgpl-2.1 | 9,998 | 0.0004 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | )
header = "%s{%s} / %s{%s}" % (spack.spec.architecture_color,
architecture, spack.spec.compiler_color,
compiler)
tty.hline(colorize(header), char='-')
specs = in | dex |
zhangyage/Python-oldboy | day07/ssh_client2.py | Python | apache-2.0 | 880 | 0.025074 | #!/usr/bin/env py | thon
# -*- coding:utf-8 -*-
'''
使用paramiko模块远程管理服务器
通过key登录
'''
import paramiko
private_key_path = 'D:\workspace\Python-oldboy\day07\zhangyage_pass'
#key = paramiko.RSAKey.from_private_key_file(filename, passwo | rd)
key = paramiko.RSAKey.from_private_key_file(private_key_path,'12345678') #private_key_path是秘钥文件的位置,'12345678'是秘钥的口令
ssh = paramiko.SSHClient() #实例化一个客户端
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #自动恢复yes,在我们使用ssh客户端链接的时候第一次的时候都会让我们输入一个yes确定的
ssh.connect('192.168.75.133', 22, username='root'... |
HaBaLeS/digital-mess-cleaner | filesorter.py | Python | mit | 4,411 | 0.009522 | import exifread
import os
import shutil
import dmcutils
from dmcutils import mylog
report = {}
trashFiles = [
'.DS_Store',
'Thumbs.db',
'.picasa.ini'
]
def processVideo(file):
vp = os.path.join(args.targetFolder,'videos')
if not os.path.exists(vp):
os.mkdir(vp)
outPath = os.path.j... | dswith(('.mp4', '.mov', '.avi')):
processVideo(file)
pass
elif any(bf.lower() in str(file).lower() for bf in trashFiles):
mylog("Deleting %s because defindes as Trash" % file)
os.remove(file)
pass
else:
mylog("Unhandled %s " % file)
def scanAndProcessFolders(inp... | ir):
mylog("Starting in " + inputDir)
fileList = []
for root, dirs, files in os.walk(inputDir):
for file in files:
candidate = os.path.join(root, file)
fileList.append(candidate);
for candidate in fileList:
processImage(candidate);
def processImage(img):... |
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/Bio/Blast/NCBIStandalone.py | Python | apache-2.0 | 74,333 | 0.000592 | # Copyright 1999-2000 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.
# Patches by Mike Poidinger to support multiple databases.
# Updated by Peter Cock in 2007... | rse the
XML output instead. The plain text parser in this module still works at the
time of writing, but is considered obsolete and updating it to cope with the
latest versions of BLAST is not a priority for us.
This module also provides code to work with the "legacy" standalone version of
NCBI B | LAST, tools blastall, rpsblast and blastpgp via three helper functions of
the same name. These functions are very limited for dealing with the output as
files rather than handles, for which the wrappers in Bio.Blast.Applications are
preferred. Furthermore, the NCBI themselves regard these command line tools as
"legacy"... |
vr2262/framer | vlc/vlc.py | Python | mit | 256,336 | 0.004837 | #! /usr/bin/python
# Python ctypes bindings for VLC
#
# Copyright (C) 2009-2012 the VideoLAN team
# $Id: $
#
# Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr>
# Jean Brouwers <MrJean1 at gmail.com>
# Geoff Salmon <geoff.salmon at gmail.com>
#
# This library is free software; you can redistr... | _Cobject(cls, ctype):
"""(INTERNAL) New instance from ctypes.
"""
o = object.__new__(cls)
o._as_parameter_ = ctype
return o
def _Constructor(cls, ptr=_internal_guard):
"""(INTERNAL) New wrapper from ctypes.
"""
if ptr == _internal_guard:
rais | e VLCException("(INTERNAL) ctypes class. You should get references for this class through methods of the LibVLC API.")
if ptr is None or ptr == 0:
return None
return _Cobject(cls, ctypes.c_void_p(ptr))
class _Cstruct(ctypes.Structure):
"""(INTERNAL) Base class for ctypes structures.
"""
_fi... |
NeuroRoboticTech/Jetduino | Software/Python/grove_thumb_joystick.py | Python | mit | 3,602 | 0.003609 | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about t... | tantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DA... | OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import jetduino
from jetduino_pins import *
# Connect the Grove Thumb Joystick to analog port A0
# GrovePi Port A0 u... |
Capitains/MyCapytain | MyCapytain/errors.py | Python | mpl-2.0 | 2,639 | 0.003412 | # -*- coding: utf-8 -*-
"""
.. module:: MyCapytain.errors
:synopsis: MyCapytain errors
.. moduleauthor:: Thibault Clérice <leponteineptique@gmail.com>
"""
class MyCapytainException(BaseException):
""" Namespacing errors
"""
class JsonLdCollectionMissing(MyCapytainException):
""" Error thrown when ... | return "Capit | ainsXPathError("+self.message+")" |
mat128/python-ubersmith-remote-module-server | ubersmith_remote_module_server/server.py | Python | apache-2.0 | 915 | 0.002186 | # Copyright 2016 Internap
#
# 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.
from flask import Flask
from ubersmith_remote_module_server import api, router
class Server(object):
def __init__(self, modules):
self.router = router.Router()
self.ap... |
levibostian/myBlanky | googleAppEngine/google/appengine/tools/old_dev_appserver.py | Python | mit | 133,803 | 0.007593 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | y, and a relative URL to use for logins,
creates an HTTP server that can be used to test an application locally. Uses
stubs instead of actual APIs when SetupStubs() is called first.
Example:
root_path = '/path/to/application/directory'
login_url = '/login'
port = 8080
server = dev_appserver.CreateServer(root_p... | oogle.appengine.tools import os_compat
import __builtin__
import BaseHTTPServer
import base64
import binascii
import calendar
import cStringIO
import cgi
import cgitb
import email.Utils
import errno
import hashlib
import heapq
import httplib
import imp
import inspect
import logging
import mimetools
import mimetypes
im... |
hackshel/metaCollecter | src/metaManager/modules/defines.py | Python | bsd-3-clause | 312 | 0.032051 | PORT = {}
PORT['metaManager'] = 10087
CGI_SOCK = {}
CGI_SOCK[ 'metaManager' ] = '/tmp/metaManager_fcgi_sock'
SOCK = {}
SOCK[ 'logqueue' ] = '/tmp/logqueue_sock'
PIDPATH = | {}
PIDPATH[ 'metaManager' ] = '/var/run/metaManager.server.pid'
PIDPATH[ 'managerChewer' | ] = '/var/run/data.chewer.pid'
|
oriel-hub/api | deploy/bootstrap.py | Python | gpl-2.0 | 2,753 | 0.00109 | #!/usr/bin/env python3
"""
bootstrap.py will set up a virtualenv for you and update it as required.
Usage:
bootstrap.py # update virtualenv
bootstrap.py fake # just update the virtualenv timestamps
bootstrap.py clean # delete the virtualenv
bootstrap.py -h | --help # p... | cept getopt.error as msg:
return print_error_msg('Bad options: %s' % msg) |
# process options
for o, a in opts:
if o in ("-h", "--help"):
print_help_text()
return 0
if o in ("-f", "--force"):
force_update = True
if o in ("-r", "--full-rebuild"):
full_rebuild = True
i... |
cp16net/trove | trove/guestagent/datastore/mysql/service.py | Python | apache-2.0 | 43,814 | 0.000023 | # Copyright 2013 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 co... | "mysqld", "h")
pid = out.split()[0]
# TODO(rnirmal): Need to create new statuses for instances
# where the mysql service is up, but unresponsive
LOG.info(_('MySQL Service Status %(pid)s is BLOCKED.') %
| {'pid': pid})
return rd_instance.ServiceStatuses.BLOCKED
except exception.ProcessExecutionError:
LOG.exception(_("Process execution failed."))
mysql_args = load_mysqld_options()
pid_file = mysql_args.get('pid_file',
... |
erikhvatum/RisWidget | ris_widget/examples/simple_point_picker.py | Python | mit | 6,323 | 0.003163 | # The MIT License (MIT)
#
# Copyright (c) 2016 WUSTL ZPLAB
#
# 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, modif... | to receive keyboard events
Qt.QGraphicsItem.ItemIsSelectable |
Qt.QGraphicsItem.ItemIsMovable |
| Qt.QGraphicsItem.ItemSendsGeometryChanges
)
point_item.installSceneEventFilter(self)
self.point_items.append(point_item)
point_item.setPos(pos)
def delete_selected(self):
for idx, item in reversed(list(enumerate((self.point_items)))):
if item.isSelected():
... |
nesdis/djongo | djongo/sql2mongo/sql_tokens.py | Python | agpl-3.0 | 12,682 | 0.000552 | import abc
import re
from typing import Union as U, Iterator, Optional as O
from pymongo import ASCENDING, DESCENDING
from sqlparse import tokens, parse as sqlparse
from sqlparse.sql import Token, Identifier, Function, Comparison, Parenthesis, IdentifierList, Statement
from . import query as query_module
from ..excepti... | if isinstance(tok, IdentifierList):
for aid in tok.get_identifiers():
yield self.get_value(aid)
else:
yield self.get_value(tok)
def __init | __(self, token: Token, query: 'query_module.BaseQuery'):
super().__init__(token, query)
def get_value(self, tok: Token):
if tok.ttype == tokens.Name.Placeholder:
return self.placeholder_index(tok)
elif tok.match(tokens.Keyword, 'NULL'):
return None
elif tok.m... |
helifu/kudu | examples/python/basic-python-example/basic_example.py | Python | apache-2.0 | 2,977 | 0.00168 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ': 2})
session.apply(op)
# Flush write operations, if failures occur, print them.
try:
session.flush()
except kudu.KuduBadStatus:
print(session.get_pending_errors())
# Create a scanner and add a predicate.
scanner = table.scanner()
scanner.add_predicate(tabl | e['ts_val'] == datetime(2017, 1, 1))
# Open scanner and print all tuples.
# Note: This doesn't scale for large scans
# The expected output: [(1, datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>))]
print(scanner.open().read_all_tuples())
|
h2020-endeavour/iSDX | pctrl/policy_loader.py | Python | apache-2.0 | 1,264 | 0.015032 | import os
import json
from ss_rule_scheme import update_outbound_rules, init_inbound_rules, init_outbound_rules, msg_clear_all_outbound, ss_process_policy_change
base_path = os.path.abspath(os.path.join(os.path.realpath(__file__),
".."))
test_file = os.path.join(base_path, "blackholin... | inbound_policies,[],final_switch)
print "Rule Messages to be removed INBOUND:: "+str(rule_msgs)
#rule_msgs2 = | init_outbound_rules(1, outbound_policies, [], final_switch)
#print ("Rule Messages OUTBOUND:: "+str(rule_msgs2))
#if 'changes' in rule_msgs2:
# if 'changes' not in rule_msgs:
# rule_msgs['changes'] = []
# rule_msgs['changes'] += rule_msgs2['changes']
#TODO: Initialize Outbound Policies from RIB
... |
CompassionCH/compassion-accounting | donation_report_compassion/__init__.py | Python | agpl-3.0 | 409 | 0 | ####################################################################### | #######
#
# Copyright (C) 2018-2020 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty i | n Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from . import reports
|
KarolBedkowski/wxgtd | wxgtd/wxtools/validators/__init__.py | Python | gpl-2.0 | 638 | 0.004724 | # -*- coding: utf-8 -*-
""" Validators for wx widgets.
Copyright (c) Karol Będko | wski, 2006-2013
This file is part of wxGTD
This is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, version 2.
"""
__author__ = "Karol Będkowski"
__copyright__ = "Copyright (c) Karol Będkowski, 2006-2013"
... | ValidatorDate', 'ValidatorTime',
'ValidatorColorStr']
from .validator import Validator, ValidatorDv, ValidatorDate, ValidatorTime, \
ValidatorColorStr
|
showa-yojyo/notebook | source/_sample/apgl/distribution.py | Python | mit | 553 | 0 | #!/usr/bin/env | python
import scipy.sparse as sps
from apgl.graph.GeneralVertexList import GeneralVertexList
from apgl.graph.SparseGraph import SparseGraph
numVertices = 10
vList = GeneralVertexList(numVertices)
Wght = sps.lil_matrix((numVertices, numVertices))
graph = SparseGraph | (vList, W=Wght, undirected=False)
# Add some edges to the graph.
# Vertices are indexed starting from 0.
graph[0, 1] = 1
graph[0, 2] = 1
# Set the label of the 0th vertex to [2, 3].
graph.setVertex(0, "abc")
graph.setVertex(1, 123)
print(graph.inDegreeDistribution())
|
diogo149/autocause | autocause/autocause_settings.py | Python | mit | 7,414 | 0.001619 | import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.p... | ATEGORICAL["discretizer10"],
B=BIN | ARY_TO_CATEGORICAL["identity"],
C=CATEGORICAL_TO_CATEGORICAL["identity"],
)
"""
Whether or not the converters can result in a 2D output. This must be set to True
if any of the respective converts can return a 2D output.
"""
NUMERICAL_CAN_BE_2D = True
CATEGORICAL_CAN_BE_2D = False
"""
Estimators used to provide a ... |
bdang2012/taiga-back-casting | taiga/projects/custom_attributes/services.py | Python | agpl-3.0 | 2,749 | 0.001092 | # Copyright (C) 2014-2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014-2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | ation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for mo... | not, see <http://www.gnu.org/licenses/>.
from django.db import transaction
from django.db import connection
@transaction.atomic
def bulk_update_userstory_custom_attribute_order(project, user, data):
cursor = connection.cursor()
sql = """
prepare bulk_update_order as update custom_attributes_userstorycus... |
oxc/Flexget | flexget/plugins/metainfo/subtitles_check.py | Python | mit | 2,678 | 0.003361 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import os
import logging
import tempfile
from flexget import plugin
from flexget.event import event
log = logging.getLogger('check_subtitles')
class MetainfoSubs(object):
... | red
try:
subliminal.region.configure('dogpile.cache.dbm',
arguments={'filename': os.path.join(tempfile.gettempdir(), 'cachefile.dbm'),
'lock_factory': MutexLock})
except RegionAlreadyConfigured:
... |
def on_task_metainfo(self, task, config):
# check if explicitly disabled (value set to false)
if config is False:
return
for entry in task.entries:
entry.register_lazy_func(self.get_subtitles, ['subtitles'])
def get_subtitles(self, entry):
if entry.get(... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/paris/household_x_neighborhood/hhnper2_nbnper2.py | Python | gpl-2.0 | 1,879 | 0.031932 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
# This is a simple test variable for the interaction of gridcells and households.
from opus_core.variables.variable import Variable
from urbansim.functions import attribute_label
class hhnp... | #[0, 0, 0],
#[0, 1, 0],
#[0, 0, 1]])
#self.assertEqual(ma.allclose(values, should_be, rtol=1e-20),
#True, msg = "Error in " + self.variable | _name)
#opus_unittest.main()
|
IntelLabs/hpat | examples/series/series_lt.py | Python | bsd-2-clause | 1,748 | 0 | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that | the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in th... | .
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE ... |
criswell/noink | src/tests/test_DelEntry.py | Python | agpl-3.0 | 740 | 0.005405 | #!/usr/bin/env python
'''
##BOILERPLATE_COPYRIGHT
##BOILERPLATE_COPYRIGHT_END
'''
import unittest, copy
from testRoot imp | ort RootClass
from noink.user_db import UserDB
from noink.entry_db import EntryDB
class AddEntry(RootClass):
def test_AddEntry(self):
userDB = UserDB()
entryDB = EntryDB()
u = userDB.add("jontest", "pass", "Jon Q. Testuser")
title = 'Little Buttercup'
entry = 'There once w... | entryDB.add(copy.deepcopy(title), entry, u)
self.assertTrue(e.title == title)
if __name__ == '__main__':
unittest.main()
|
b-mueller/mythril | tests/mythril/mythril_leveldb_test.py | Python | mit | 2,235 | 0.003579 | import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB",... | ldb_search = MythrilLevelDB(leveldb=config.eth_db)
with pytest.raises(CriticalError):
leveldb_search.contract_hash_to_address("0x23")
@patch(
"mythril.ethereum.interface.leveldb.client.EthLevelDB.contract_hash_to_address",
return_value="0xddbb615cb2ffaff7233d8a6f3601621de94795e1",
)
@patch("mythri... | urn_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBReader", return_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBWriter", return_value=None)
def test_leveldb_hash_search_correct_input(mock_hash_to_address, f1, f2, f3):
config = MythrilConfig()
config.set_api_leveldb(... |
ibackus/testdust | testdust/diffusion/plot.py | Python | mit | 4,000 | 0.009 | # -*- coding: utf-8 -*-
"""
Contains functions to plot the results of the dustydiffusion test.
@author: ibackus
"""
import matplotlib.pyplot as plt
import numpy as np
import pynbody
import diskpy
#sim, epsEstimator, ts, runpars = analyze.loadSim(simdir)
def crossSection(sim, ts, crossSectionTimes=[0, 1, 10]):
""... | s)
actualPlotTimes = np.zeros(nt)
title = 'plot times: '
if colorcode:
markercolor = None
else:
markercolor = 'k'
for iPlot in range(nt):
iTime = abs(ts - epsPlotTimes[iPlot]).argmin()
# Calculate stuff
f = sim[iTime]
t = ts... | ]
actualPlotTimes[iPlot] = t
print t
r = np.linspace(0, f['r'].max(), nr)
epsAnalytic = epsEstimator(r, t)
# Plot
scatter=plt.plot(f['r'], f['dustFrac'], 'o', markersize=3,
markeredgecolor='none', label='t={:.2g}'.format(float(t)),
... |
Suwmlee/XX-Net | Python3/lib/ctypes/test/test_byteswap.py | Python | bsd-2-clause | 11,726 | 0.000768 | import sys, unittest, struct, math, ctypes
from binascii import hexlify
from ctypes import *
def bin(s):
return hexlify(memoryview(s)).decode().upper()
# Each *simple* type that supports different byte orders has an
# __ctype_be__ attribute that specifies the same type in BIG ENDIAN
# byte order, and a... | yte.__ctype_be__, c_ubyte)
self.assertIs(c_char.__ctype_le__, | c_char)
self.assertIs(c_char.__ctype_be__, c_char)
def test_struct_fields_1(self):
if sys.byteorder == "little":
base = BigEndianStructure
else:
base = LittleEndianStructure
class T(base):
pass
_fields_ = [("a", c_ubyte),
... |
grafeas/client-python | grafeas/models/discovery_discovered_details.py | Python | apache-2.0 | 3,542 | 0.000282 | # coding: utf-8
"""
An API to insert and retrieve metadata on cloud artifacts.
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1alpha1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
... | self._operation = None
self.discriminator = None
if operation is not None:
self.operation = operation
@property
def operation(self):
"""Gets the operation of this DiscoveryDiscoveredDetails. # noqa: E501
Output only. An operation that indicates the status of... | tails. # noqa: E501
:rtype: GooglelongrunningOperation
"""
return self._operation
@operation.setter
def operation(self, operation):
"""Sets the operation of this DiscoveryDiscoveredDetails.
Output only. An operation that indicates the status of the current scan. # noq... |
quarkslab/irma | common/src/ftp/sftpv2.py | Python | apache-2.0 | 3,911 | 0 | #
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA 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 in the top-level directory
# of this distribution and at:
#
# http:... | ENSE-2.0
#
| # No part of the project, including this file, may be copied,
# modified, propagated, or distributed except according to the
# terms contained in the LICENSE file.
import stat
import socket
from irma.common.base.exceptions import IrmaSFTPv2Error
from irma.common.ftp.ftp import FTPInterface
from ssh2.session import Ses... |
HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/Applications/ParaView/Testing/Python/CTHAMRClip.py | Python | gpl-3.0 | 1,836 | 0.003813 | #/usr/bin/env python
import QtTesting
import QtTestingImage
object1 = 'pqClientMainWindow/MainControlsToolbar/actionOpenData'
QtTesting.playCommand(object1, 'activate', '')
object2 = 'pqClientMainWindow/FileOpenDialog'
QtTesting.playCommand(object2, 'filesSelected', '$PARAVIEW_DATA_ROOT/SPCTH/Dave_Karelitz_Small/spct... | Dock/proxyTabWidget/qt_tabwidget_stackedwidget/objectInspector/Accept'
QtTesting.playCommand(object4, 'activate', '')
object5 = 'pqClientMainWindow/representationToolbar/displayRepresentation/comboBox'
QtTesting.playCommand(object5, 'set_string', 'Surface')
object6 = 'pqClientMainWindow/variableToolbar/displayColor/Var... | ainWindow/cameraToolbar/actionPositiveX'
QtTesting.playCommand(object7, 'activate', '')
object8 = 'pqClientMainWindow/menubar/menuFilters/pqProxyGroupMenuManager0/Cut'
QtTesting.playCommand(object8, 'activate', '')
QtTesting.playCommand(object4, 'activate', '')
object9 = 'pqClientMainWindow/proxyTabDock/proxyTabWidget/... |
weichen2046/IntellijPluginDevDemo | enterprise-repo/enterprepo/pluginrepo/apps.py | Python | apache-2.0 | 160 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_lite | rals
from django.apps import AppConfig
class PluginrepoConfig(AppCon | fig):
name = 'pluginrepo'
|
FancyRice/RitoAPI | ritoapi/tests/test_stress.py | Python | mit | 655 | 0.003053 | from ritoapi.endpoints.match_v3 import MatchV3
import threading
def _load_matches(match_v3, sample_region, sample_match_id, count):
for i in range(count): |
data = match_v3.matches(sample_region, sample_match_id)
assert(data['gameId'] == sample_match_id)
def test_matches_stress(sample_api_key, sample_rate_limit, sample_region, sample_match_id):
match_v3 = | MatchV3(sample_api_key, sample_rate_limit)
threads = []
for i in range(10):
t = threading.Thread(target=_load_matches, args=(match_v3, sample_region, sample_match_id, 20))
threads.append(t)
t.start()
for t in threads:
t.join()
|
PaloAltoNetworks-BD/SplunkforPaloAltoNetworks | Splunk_TA_paloalto/bin/splunk_ta_paloalto/aob_py3/cloudconnectlib/splunktalib/schedule/scheduler.py | Python | isc | 4,153 | 0.001445 | from future import standard_library
standard_library.install_aliases()
from builtins import object
import threading
from time import time
import random
import queue
from ..common import log
class Scheduler(object):
"""
A simple scheduler which schedules the periodic or once event
"""
import sortedcon... | self._wakeup_q.put(True)
def _do_jobs(self):
while 1:
(sleep_time, jobs) = self.get_ready_jobs()
self._do_execution(jobs)
try:
done = self._wakeup_q.get(timeout=sleep_time)
except queue.Empty:
pass
else:
... | break
self._started = False
log.logger.info("Scheduler exited.")
def get_ready_jobs(self):
"""
@return: a 2 element tuple. The first element is the next ready
duration. The second element is ready jobs list
"""
now = time()
ready_jobs = [... |
khalibartan/pgmpy | pgmpy/tests/test_factors/test_discrete/test_Factor.py | Python | mit | 56,244 | 0.004054 | import unittest
import warnings
from collections import OrderedDict
import numpy as np
import numpy.testing as np_test
from pgmpy.extern.six.moves import range
from pgmpy.factors.discrete import DiscreteFactor
from pgmpy.factors.discrete import JointProbabilityDistribution as JPD
from pgmpy.factors import factor_divi... | bug in reduce
card3 = [3, 3, 3, 2, 2, 2, 2, 2, 2]
self.phi3 = DiscreteFactor(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
card3, np.arange(np.prod(card3), dtype=np.float))
self.tup1 = ('x1', 'x2')
self.tup2 = ('x2', 'x3')
self.tup3 = ('x3', ... | p3], [2, 3, 4], np.random.uniform(3, 10, size=24))
self.phi5 = DiscreteFactor([self.tup1, self.tup2, self.tup3], [2, 3, 4], range(24))
self.card6 = [4, 2, 1, 3, 5, 6]
self.phi6 = DiscreteFactor([self.tup1, self.tup2, self.tup3, self.tup1 + self.tup2,
self.tup... |
albertz/music-player | src/Events.py | Python | bsd-2-clause | 2,934 | 0.039877 |
from collections import deque
from threading import RLock, Condition, currentThread
import sys
import time
class OnRequestQueue:
ListUsedModFunctions = ("append", "popleft")
class QueueEnd:
def __init__(self, queueList=None):
if queueList is not None:
self.q = queueList
else:
self.q = deque()
se... | self.cond:
return "<QueueEnd %r>" % self.q
def put(self, item):
with self.cond:
if self.cancel: return False
self.q.append(item)
self.cond.notifyAll()
def setCancel(self):
with self.cond:
self.cancel = True
self.cond.notifyAll()
def __init__(self):
self.queues = set()
def put(self... | rgs):
q = self.QueueEnd(**kwargs)
thread = currentThread()
thread.waitQueue = q
if thread.cancel:
# This is to avoid a small race condition for the case
# that the thread which wants to join+cancel us was faster
# and didn't got the waitQueue. In that case, it would
# have set the cancel already to ... |
weylin/CloudBot | plugins/google.py | Python | gpl-3.0 | 1,653 | 0.00242 | import random
from cloudbot.util import http, formatting
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query)
# @hook.command("googleimage", "gis", "image... | d['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'No results fou | nd.'
result = parsed['responseData']['results'][0]
title = http.unescape(result['titleNoFormatting'])
title = formatting.truncate_str(title, 60)
content = http.unescape(result['content'])
if not content:
content = "No description available."
else:
content = http.html.fromstrin... |
svaarala/duktape | util/filter_test262_log.py | Python | mit | 3,455 | 0.002894 | #!/usr/bin/env python2
import os
import sys
import json
import yaml
def main():
with open(sys.argv[1], 'rb') as f:
known_issues = yaml.safe_load(f.read())
skipstrings = [
'passed in strict mode',
'passed in non-strict mode',
'failed in strict mode as expected',
'failed... | ors.append(line + ' // diagnosed: ' + kn['diagnosed'])
elif kn.has_key('knownissue'):
# Don't bump tofix_count, as testcase exp | ected result is not certain
known_errors.append(line + ' // KNOWN: ' + kn['knownissue'])
else:
tofix_count += 1
unknown_errors.append(line + ' // ??? (rule matches)')
kn['used'] = True # mark rule used
match... |
the-zebulan/CodeWars | tests/kyu_6_tests/test_longest_2_character_substring.py | Python | mit | 1,191 | 0 | import unittest
from katas.kyu_6.longest_2_character_substring import substring
class SubstringTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(substring(''), '')
def test_equals_2(self):
self.assertEqual(substring('a'), 'a')
def test_equals_3(self):
self.ass... | self.assertEqual(substring('abacd'), 'aba')
def test_equals_9(self):
self.assertEqual(substring('abcba'), 'bcb')
def test_equals_10(self):
self.assertEqual(substring('bbacc'), 'bba')
def test_equals_11(self):
self.assertEqual(substring('ccddeeff'), 'ccdd')
def test_equa... | self.assertEqual(substring('cefageaacceaccacca'), 'accacca')
|
portfors-lab/sparkle | test/tests/gui/__init__.py | Python | gpl-3.0 | 599 | 0.013356 | import sip
sip.setdestroyonex | it(0)
import os, shutil
import numpy as np
from sparkle.QtWrapper import QtGui
tempfolder = os.path.join(os.path.abspath(os.path.dirname(__file__)), u"tmp")
app = None
# executes once before all tests
def setup():
if not os.path.exists(tempfolder):
os.mkdir(tempfolder)
np.warnings.filterwarnings('ig... | )
np.warnings.resetwarnings()
global app
app.exit(0)
app = None
|
phborba/dsgtoolsop | numericalVertexEdit/resources.py | Python | gpl-2.0 | 7,700 | 0.000649 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.7.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x05\x96\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x0... | ad\x02\x98\xa6\x49\x28\x14\xb2\x1e\x25\xc7\x0e\xd9\xad\x03\x20\
\x09\x21\x6c\x03\xab\x36\xfb\x8f\xaf\x58\xb9\xe2\xdd\xda\xda\x5a\
\x1d\xe0\xd8\xd1\x63\x6c\xdd\xb6\x95\xd3\x9f\x9f\xa6\xf9\x9d\x4a\
\x52\x7d\x1f\x91\xf8\xbb\x0b\x91\x4a\x24\x34\x39\xf9\xd8\x66\x89\
\x90\x80\xc0\xa4\x80\x8a\x8d\xef\xcd\x75\x2a\x9e\xc1\x40\x... | \x3e\xc0\x4a\x44\x6f\x4e\x0a\
\xb0\xcb\x22\xad\xe4\x55\x0d\x63\x6e\x05\x0e\xed\x85\x2c\xbf\xaa\
\xcf\xa6\x70\xe9\xfb\xb8\xf2\x97\x32\x32\xf0\x15\xfd\x37\x37\xda\
\xf7\x20\xad\xdc\x5e\x64\x4a\x76\x64\xdf\x3f\xe7\x8c\xc5\xcc\x7f\
\xe5\x20\xae\xfc\xa5\xc4\xcd\x41\x46\x87\x2e\x3d\xf5\xfd\x17\x20\
\xf7\x44\x65\x01\x64\x75\x... |
maikodaraine/EnlightenmentUbuntu | bindings/python/python-efl/tests/evas/test_04_object_box.py | Python | unlicense | 1,720 | 0.001163 | #!/usr/bin/env python
from efl import evas
import unittest
class TestBoxBasics(unittest.TestCase):
def setUp(self):
self.canvas = evas.Canvas(method="buffer",
size=(400, 500),
viewport=(0, 0, 400, 500))
self.canvas.engine_info_se... |
box.append(r1)
box.append(r2)
box.remove_all(True)
self.assertEqual(r1.is_deleted(), True)
self.assertEqual(r2.is_ | deleted(), True)
box.delete()
if __name__ == '__main__':
unittest.main(verbosity=2)
evas.shutdown()
|
hagabbar/pycbc_copy | pycbc/types/array.py | Python | gpl-3.0 | 33,597 | 0.004643 | # Copyright (C) 2012 Alex Nitz, Josh Willis, Andrew Miller, Tito Dal Canton
#
# 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... | (float32,compex64, etc)
copy: This defines whether the initial_array is copied to instantiate
the array or is simply referenced. If copy is false, new data is not
created, and so all arguments that would force a copy are ignored.
The default is to copy the given object.
"""
... | tial_array._data
if not copy:
if not _scheme_matches_base_array(initial_array):
raise TypeError("Cannot avoid a copy of this array")
elif issubclass(type(self._scheme), _scheme.CPUScheme):
# ArrayWithAligned does not copy its memory; all
... |
marco-c/pluotsorbet | tests/sslEchoServer.py | Python | gpl-2.0 | 2,382 | 0.00084 | #!/usr/bin/env python
import socket, ssl
# This is a copy of _RESTRICTED_SERVER_CIPHERS from the current tip of ssl.py
# <https://hg.python.org/cpython/file/af793c7580f1/Lib/ssl.py#l174> except that
# RC4 has been added back in, since it was removed in Python 2.7.10,
# but SSLStreamConnection only supports RC4 cipher... | ber (_ssl.c:581)
#
# Whereas the SSLEOFError doesn't prevent the server from working
# (it seems to happen only when the server is first started, and it
# stops happening if we simply ignore it and try again a few times)
# so we leave ssl_version at ssl.PROTOCOL_SSLv3 and ignore ... | t error.
#
# If we catch SSLEOFError specifically, then Travis fails with:
# AttributeError: 'module' object has no attribute 'SSLEOFError'
# So we catch the more general exception SSLError.
continue
try:
data = connstream.read()
while data:
con... |
thedrow/streamparse | examples/wordcount/multilang/resources/sentence_splitter.py | Python | apache-2.0 | 274 | 0 | from pystorm.bolt import BasicBolt
class SentenceSplitterBolt(BasicBolt):
def process(self, tup):
sentence = tup.values[0]
for word in sentence | .sp | lit(' '):
BasicBolt.emit(word)
if __name__ == '__main__':
SentenceSplitterBolt().run()
|
coxmediagroup/googleads-python-lib | examples/adwords/adwords_appengine_demo/views/add_campaign_view.py | Python | apache-2.0 | 2,387 | 0.005027 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 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.
"""Handles request to add a Campaign to a client account."""
__author__ = 'Mark Saniscalchi'
import os
from handlers.ap... | s.ndb_handler import InitUser
import webapp2
from google.appengine.api import users
from google.appengine.ext.webapp import template
class AddCampaign(webapp2.RequestHandler):
"""View that either adds a Campaign or displays an error message."""
def post(self):
"""Handle post request."""
client_customer_... |
gilt/incubator-airflow | airflow/migrations/versions/947454bf1dff_add_ti_job_id_index.py | Python | apache-2.0 | 1,041 | 0.001921 | # -*- coding: utf-8 -*-
#
# 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 b | y applicable law or agreed to in writing, software
# distributed under the Lic | ense 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.
"""add ti job_id index
Revision ID: 947454bf1dff
Revises: bdaa763e6c56
Create Date: 2017-08-15 15:1... |
geo2tag-logistics/Geo2Logistics | logistics/migrations/0001_initial.py | Python | apache-2.0 | 5,033 | 0.004769 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-08 19:59
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | els.C | harField(max_length=50)),
('description', models.TextField(blank=True, null=True)),
('passenger_phone', models.CharField(blank=True, max_length=50, null=True)),
('passenger_name', models.CharField(blank=True, max_length=50, null=True)),
('start_position', ... |
afreeorange/rosalind | SUBS/motif.py | Python | mit | 684 | 0.001462 | import sys
def find_motif_locations(dna, motif):
motif_locations = []
if len(dna) < len(motif):
raise ValueError('Motif can\'t be shorter than sequence')
if len(motif) == len(dna) and motif != dna:
return motif_locations
for _ in range(len(dna) - len(motif) + 1):
if dna[_:_ ... | _name__ == '__main__':
sequences = open(sys.argv[1]).read().sp | lit()
print(
' '.join(
str(_)
for _ in
find_motif_locations(
sequences[0],
sequences[1]
)
)
)
|
paalge/scikit-image | doc/examples/features_detection/plot_blob.py | Python | bsd-3-clause | 2,997 | 0 | """
==============
B | lob Detection
==============
Blobs are bright on dark or dark on bright regions in an image. In
this example, blobs are detected using 3 algor | ithms. The image used
in this case is the Hubble eXtreme Deep Field. Each bright dot in the
image is a star or a galaxy.
Laplacian of Gaussian (LoG)
-----------------------------
This is the most accurate and slowest approach. It computes the Laplacian
of Gaussian images with successively increasing standard deviation... |
yusaira-khan/un-iife-ize | tests/vars.py | Python | mit | 2,836 | 0.000705 | __author__ = 'yusaira-khan'
import unittest
import un_iife_ize.un_iife_ize as un_iife_ize
class CheckVar(unittest.TestCase):
def test_simple(self):
statement = [('var hello,world=5;', 0)]
exp = [('hello=undefined,world=5;', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
... | v = un_iife_ize.Var(statement)
v.extract_all()
ret = v.all
self.assertEqual(ret, exp)
def test_deliberate_iife(self):
statement = [('var hello=function(){;}', 0)]
exp = [('hello=function(){;}', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
... | qual(ret, exp)
def test_deliberate_iife_barc(self):
statement = [('var hello = (function(){;}())', 0)]
exp = [(' hello = (function(){;}())', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
ret = v.all
print(ret, len(exp[0][0]), len(ret[0][0]))
self.ass... |
JacobJacob/pyew | jdisasm.py | Python | gpl-2.0 | 19,835 | 0.013511 | #! /usr/bin/python2.4
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope t... | ('aastore | ', 1),
1: ('aconst_null', 1),
25: ('aload', 2),
42: ('aload_0', 1),
43: ('aload_1', 1),
44: ('aload_2', 1),
45: ('aload_3', 1),
189: ('anewarray', 3),
176: ('areturn', 1),
176: ('areturn', 1),
190: ('arraylength', 1),
190: ('arraylength', 1),
58: ('astore', 2),
75: ('... |
GreenJoey/My-Simple-Programs | python/500L Async Scraper/simple-url-getter.py | Python | gpl-2.0 | 1,959 | 0.001021 | import socket
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
sock = socket.socket()
sock.setblocking(False) |
selector = DefaultSelector()
urls_todo = set(['/'])
seen_urls = set(['/'])
class Fetcher:
def __init__(self, url):
| self.response = b''
self.url = url
self.sock = None
def fetch(self):
# This method fetches the url
self.sock = socket.socket()
self.sock.setblocking(False)
try:
self.sock.connect(('xkcd.com'), 80)
except BlockingIOError:
pass
... |
google/burst-denoising | kpn_data_provider.py | Python | apache-2.0 | 21,051 | 0.018241 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | pscale, jitter, smalljitter):
# patches is [BURST_LENGTH, h_up, w_up, 3]
j_up = jitter * upscale
h_up = height * upscale # + 2 * j_up
w_up = width * upscale # + 2 * j_up
bigj_patches = patches
delta_up = (jitter - smalljitter) * upscale
smallj_patches = patches[:, delta_up:-delta_up, delta_up:-delta_up, ... | prob = tf.minimum(tf.cast(tf.random_poisson(1.5, []), tf.float32)/BURST_LENGTH, 1.)
for k in range(BURST_LENGTH - 1):
flip = tf.random_uniform([])
p2use = tf.cond(flip < prob, lambda : bigj_patches, lambda : smallj_patches)
curr.append(tf.random_crop(p2use[i, ...], [h_up, w_up, 3]))
... |
Secretions/zmdomainexport | zimbrasoap/__init__.py | Python | gpl-2.0 | 144 | 0.013889 | #!/usr/bin/python
__version__ = '0.0.1'
import pysimplesoap.client
import pysimplesoap.simplexml
from zimbrasoap.soap import soap, | admin,mai | l
|
darth-dodo/project_lumos | lumos/migrations/0010_softskills_slug.py | Python | mit | 428 | 0 | # -*- coding: utf-8 -*- |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lumos', '0009_proglang_slug'),
]
operations = [
migrations.AddField(
model_name='softskills',
name='slug',
fiel... | ),
]
|
vswamy/nightson | nightson/managers/base_entity_manager.py | Python | apache-2.0 | 1,373 | 0.002185 | from __future__ import absolute_import
import momoko
from tornado import | gen
from psycopg2.extras import RealDictConnection
def initialize_database():
db = momoko.Pool(
dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''',
size=5,
connection_factory=RealDictConnection,
)
db.connect()
return db
class BaseEntityManager(obje... | def __init__(self):
pass
def __init__(self, request):
self.request = request
@gen.coroutine
def execute_sql(self, sql):
''' Executes an sql statement and returns the value '''
cursor = yield BaseEntityManager.db.execute(sql)
raise gen.Return(cursor)
def get_va... |
zero-os/0-orchestrator | pyclient/zeroos/orchestrator/client/EnumContainerStatus.py | Python | apache-2.0 | 139 | 0 | from enum import Enum
class EnumContainerStatus(Enum):
running | = "running"
halted = "halted | "
networkKilled = "networkKilled"
|
spirrello/spirrello-pynet-work | applied_python/lib/python2.7/site-packages/pysmi/reader/localfile.py | Python | gpl-3.0 | 4,425 | 0.003164 | #
# This file is part of pysmi software.
#
# Copyright (c) 2015-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysmi.sf.net/license.html
#
import os
import sys
import time
from pysmi.reader.base import AbstractReader
from pysmi.mibinfo import MibInfo
from pysmi.compat import decode
from pysmi import debug
from py... | stance of *FileReader* serving a directory.
Args:
path (str): directory to search MIB files
Keyword Args:
recursive (bool): whether to include subdirectories
ignoreErrors (bool): ignore filesystem access errors
"""
self._path = os.path.... | self._indexLoaded = False
def __str__(self): return '%s{"%s"}' % (self.__class__.__name__, self._path)
def getSubdirs(self, path, recursive=True, ignoreErrors=True):
if not recursive:
return [path]
dirs = [path]
try:
subdirs = os.listdir(path)
ex... |
tiancj/emesene | emesene/gui/gtkui/RichWidget.py | Python | gpl-3.0 | 4,161 | 0.004086 | # -*- coding: utf-8 -*-
# This file is part of emesene.
#
# emesene 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.
#
#... | self.put_link(child.href)
else:
self._put_formatted(child, fg_color, bg_color, font, size,
bold, italic, underline, | strike)
def put_image(self, path, tip=None):
'''insert an image at the current position
tip it's the alt text on mouse over'''
raise NotImplementedError('Not implemented')
def new_line(self):
'''put a new line on the text'''
raise NotImplementedError('Not implemented')
... |
fish2000/django-signalqueue | signalqueue/settings/__init__.py | Python | bsd-3-clause | 4,884 | 0.006347 |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('My Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
import tempfile, os
from django import contrib
tempdata = tempfile.mkdtemp()
approot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
adminroot = os.path.join(contrib.__path__[0], 'admin')
DATAB... | 'OPTIONS': dict(app_label='signalqueue',
modl_name='EnqueuedSignal'),
},
'celery': {
'ENGINE': 'signalqueue.wor | ker.celeryqueue.CeleryQueue',
'INTERVAL': 30, # 1/3 sec
'OPTIONS': dict(celery_queue_name='inactive',
transport='redis', port=8356),
},
}
SQ_ADDITIONAL_SIGNALS=['signalqueue.tests']
SQ_WORKER_PORT = 11201
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
try:
from kombu import Queu... |
ShaolongHu/lpts | tests/fio.py | Python | gpl-2.0 | 4,566 | 0.007627 | # -*- coding:utf-8 -*-
'''
fio测试工具执行脚本
'''
import os,shutil,re,time,sys,copy
from test import BaseTest
from lpt.lib.error import *
from | lpt.lib import lptxml
from lpt.lib import lptlog
from lpt.lib.s | hare import utils
from lpt.lib import lptreport
class TestControl(BaseTest):
'''
继承BaseTest属性和方法
'''
def __init__(self, jobs_xml, job_node, tool, tarball='fio-2.1.10.tar.bz2'):
super(TestControl, self).__init__(jobs_xml, job_node, tool, tarball)
def setup(self):
'''编译源码,设置程序
... |
booya-at/freecad_glider | freecad/freecad_glider/tools/line_tool.py | Python | lgpl-2.1 | 36,337 | 0.001431 | from __future__ import division
import sys
if sys.version_info.major > 2:
from importlib import reload
from PySide import QtGui, QtCore
import traceback
import numpy as np
import FreeCAD as App
import FreeCADGui as Gui
from ._tools import BaseTool, input_field, text_field
from ._glider import draw_glider, draw_l... | tach_x_val, self.attach_y_val, self.attach_z_val]:
spinbox.setMaximum(10.)
spinbox.setMinimum(-10.)
spinbox.valueChanged.connect(self.update_lw_att_pos)
self.lw_att_lay.addWidget(self.attach_x_val)
self.lw_att_lay.addWidget(self.attach_y_val)
self.lw_att_lay.... | QtGui.QDoubleSpinBox()
self.up_att_force.setSingleStep(0.1)
self.up_att_lay.setWidget(0, text_field, QtGui.QLabel('force'))
self.up_att_lay.setWidget(0, input_field, self.up_att_force)
self.up_att_force.valueChanged.connect(self.update_up_att_force)
self.up_att_rib = QtGui.QSpi... |
jlongever/RackHD | test/benchmark/api_v2_0/discovery_tests.py | Python | apache-2.0 | 142 | 0.007042 | from proboscis import test
@test(groups=['benchmark.discovery'])
class BenchmarkDiscoveryTests(object):
def __init_ | _(self):
p | ass
|
donlee888/JsObjects | Python/ComplexPaths02/src/main/mypackage/MyPackageMod01.py | Python | mit | 122 | 0.02459 | '''
Cre | ated on May 26, 2012
@author: Charlie
'''
class MyPackageMod01(object):
def | __init__(self):
pass |
ColoradoSchoolOfMines/acm-website | mozzarella/controllers/__init__.py | Python | gpl-3.0 | 50 | 0 | """ | Controllers for the mozzarella application."" | "
|
amadeusproject/amadeuslms | themes/migrations/0003_auto_20170112_1408.py | Python | gpl-2.0 | 560 | 0.001786 | # -*- coding: utf- | 8 -*-
# Generated by Django 1.10 on 2017-01-12 17:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('themes', '0002_auto_20170110_1809'),
]
operations = [
migrations.AlterField(
model_... | name='css_style',
field=models.CharField(choices=[('green', 'Green'), ('red', 'Red'), ('black', 'Black')], default='green', max_length=50, verbose_name='Css Style'),
),
]
|
jonathanmeier5/teamstore | saleor/checkout/views/shipping.py | Python | bsd-3-clause | 3,737 | 0.00107 | from django.shortcuts import redirect
from django.template.response import TemplateResponse
from ..forms import AnonymousUserShippingForm, ShippingAddressesForm
from ...userprofile.forms import get_address_form
from ...userprofile.models import Address
from ...teamstore.utils import get_team
def anonymous_user_shipp... | checkout.shipping_address = address_form.instance
checkout.email = user_form.c | leaned_data['email']
return redirect('checkout:shipping-method')
return TemplateResponse(
request, 'checkout/shipping_address.html', context={
'address_form': address_form, 'user_form': user_form,
'group_shipping': team.group_shipping, 'checkout': checkout})
def us... |
rohitranjan1991/home-assistant | homeassistant/components/rachio/switch.py | Python | mit | 19,041 | 0.00084 | """Integration with the Rachio Iro sprinkler system controller."""
from abc import abstractmethod
from contextlib import suppress
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from ho... | SUBTYPE_ZONE_COMPLETED,
SUBTYPE_ZONE_PAUSED,
SUBTYPE_ZONE_STARTED,
SUBTYPE_ZONE_STOPPED,
)
_LOGGER = logging.getLogger(__name__)
ATTR_DURATION = "duration"
ATTR_PERCENT = "percent"
ATTR_SCHEDULE_SUMMARY = "Summary"
ATTR_SCHEDULE_ENABLED = "Enabled"
ATTR_SCHEDULE_DURATION = "Duration"
ATTR_SCHEDULE_TYP... | = "Type"
START_MULTIPLE_ZONES_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_DURATION): cv.ensure_list_csv,
}
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
... |
LinuCC/sturo | src/lib/usonic.py | Python | gpl-2.0 | 3,134 | 0.021378 | #!/usr/bin/python
import time
import RPi.GPIO as GPIO
# remember to change the GPIO values below to match your sensors
# GPIO output = the pin that's connected to "Trig" on the sensor
# GPIO input = the pin that's connected to "Echo" on the sensor
def reading(sensor):
# Disable any warning message such as GPIO pins... | pin that's connected to "Echo" on the sensor
while GPIO.input(27) == 0:
signaloff = time.time()
# listen to the input pin. Once a signal is received, record the
# time the signal came through
# change this value to the pin you are using
# GPIO input = the pin that's connected to "Echo" on th | e sensor
while GPIO.input(27) == 1:
signalon = time.time()
# work out the difference in the two recorded times above to
# calculate the distance of an object in front of the sensor
timepassed = signalon - signaloff
# we now have our distance but it's not in a useful unit of
# measurement. So now we co... |
Stiliyan92/accounting-system | common/config_parser.py | Python | gpl-2.0 | 828 | 0.001208 | import configparser
CONFIG_PATH = 'accounting.conf'
class MyConfigParser():
| def __init__(self, config_path=CONFIG_PATH):
self.config = configparser.ConfigParser(allow_no_value=True)
self.config.read(config_path)
def config_section_map(self, section):
""" returns all configuration options in 'section' in a dict with
key: config_option and value: the read ... | try:
dict1[option] = self.config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
dict1[option] = None
return dict1
# getint(section, option)
# getboolean(section, option)
|
fahadsultan/CausalRelations | to_txt.py | Python | apache-2.0 | 551 | 0.039927 | import os
from bs4 import BeautifulSoup
count = pd.DataFrame(columns = ['filename', 'count'])
for folder, subs, files in os.walk('data/xml'):
for filename in files:
try:
if ('.xml' in | filename) and (filename[0] != '.'):
f = open(os.path.join(folder, filename))
soup = BeautifulSoup(f.read())
tokens = soup.findAll('token')
tokens_arr = [token.text for token in tokens]
text = ' '.join(tokens_arr)
f = open('data/text/'+filename, 'w')
f.write(text | )
f.close()
except Exception as e:
print e
continue |
kyon-bll/.dotfiles | .emacs.d/elpa/jedi-core-20191011.1750/jediepcserver.py | Python | mit | 15,847 | 0.000252 | #!/usr/bin/env python
"""
Jedi EPC server.
Copyright (C) 2012 Takafumi Arakaki
Author: Takafumi Arakaki <aka.tkf at gmail.com>
This file is NOT part of GNU Emacs.
Jedi EPC server 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 So... | pcserver')
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__)
parser.add_argument(
'--address', default='localhost')
parser.add_argument(
'--port', default=0, type=int)
parser.add_argument(
'--port-file', '-f', default='-', type=argparse.FileType(... | le to write port on. default is stdout.')
parser.add_argument(
'--sys-path', '-p', default=[], action='append',
help='paths to be inserted at the top of `sys.path`.')
parser.add_argument(
'--sys-path-append', default=[], action='append',
help='paths to be appended at the end of `sys.path`.')
parser.add... |
diegocepedaw/oncall | e2e/test_schedules.py | Python | bsd-2-clause | 6,315 | 0.002375 | # Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.parse
import requests
from testutils import prefix, api_v0
HOUR = 60 * 60
DAY = HOUR * 24
@prefix... | chedule['events']) == 1
assert schedule['events'][0]['start'] == tuesday9am
assert schedule['events'][0]['duration'] == 48 * HOUR
assert schedule['advanced_mode'] == 1
# test 'schedule' endpoint
re = requests.get(api_v0('schedules/%s' % (schedule_id)))
assert re.status_code == 200
| assert re.json() == data[0]
updated_events = [{'start': 0, 'duration': 100}, {'start': 150, 'duration': 200}]
# verify schedule updates properly
re = requests.put(api_v0('schedules/' + schedule_id),
json={'role': role_name_2,
'team': team_name_2,
... |
igemsoftware/SYSU-Software2013 | project/Python27_32/Lib/site-packages/pypm/common/util.py | Python | mit | 7,802 | 0.003204 | # Copyright (c) 2010 ActiveState Software Inc. All rights reserved.
"""
pypm.common.util
~~~~~~~~~~~~~~~~
Assorted utility code
"""
import os
from os import path as P
import sys
import re
from contextlib import contextmanager
import logging
import time
import textwrap
from datetime import datetime
f... |
class BareDateTime(six.text_type):
"""Wrapper around the DateTime object with our own s | tandard string
representation
"""
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"
FORMAT = DATE_FORMAT + ' ' + TIME_FORMAT
@classmethod
def to_string(cls, dt):
"""Convert the datetime object `dt` to a string
with format as defind by this class
"""
return ... |
google/merge_pyi | testdata/heuristics.comment.py | Python | apache-2.0 | 631 | 0.006339 | from typing import Any
# Copyright (c) 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0)
# If not annotate_pep484, info in pyi files is augmented with heuristics to decide if un-annotated
# arguments are "Any" or "" (like "self")
class B(object):
def __init__(self):
pass
def f(self, ... | pass
@ | classmethod
def f4(cls):
pass
|
vmindru/ansible | lib/ansible/context.py | Python | gpl-3.0 | 2,049 | 0.003416 | # Copyright: (c) 2018, Toshio Kuratomi <tkuratomi@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
"""
Context of the running Ansible.
In the... | tils.context_objec | ts import CLIArgs, GlobalCLIArgs
__all__ = ('CLIARGS',)
# Note: this is not the singleton version. The Singleton is only created once the program has
# actually parsed the args
CLIARGS = CLIArgs({})
# This should be called immediately after cli_args are processed (parsed, validated, and any
# normalization perfor... |
puttarajubr/commcare-hq | corehq/apps/app_manager/tests/test_case_meta.py | Python | bsd-3-clause | 2,721 | 0.00147 | from django.test.testcases import SimpleTestCase
from corehq.apps.app_manager.const import APP_V2
from corehq.apps.app_manager.models import Application, Module, OpenCaseAction, ParentSelect, OpenSubCaseAction, \
AdvancedModule, LoadUpdateAction, AdvancedOpenCaseAction
from mock import patch
class CaseMetaTest(Si... |
def test_hierarchy(self):
| app, expected_hierarchy = self.get_test_app()
meta = app.get_case_metadata()
self.assertDictEqual(meta.type_hierarchy, expected_hierarchy)
def get_test_app(self):
app = Application.new_app('domain', 'New App', APP_V2)
app.version = 1
m0 = self._make_module(app, 0, 'par... |
viniciusd/DCO1008---Digital-Signal-Processing | projeto3/aiff.py | Python | mit | 913 | 0.001095 | import aifc
import sndhdr
import utils
class Aiff:
def __init__(self, filename):
assert sndhdr.what(filename).filetype == 'aiff'
x = aifc.open(filename)
data = x.readframes(x.getnframes())
self.nchannels = x.getnchannels()
self.sampwidth = x.getsampwidth()
self.f... | y.setsampwidth(self.sampwidth)
y.setframerate(self.framerate)
y.writeframes(self.sig.flatten().tobytes())
def save_channel(self, filename, channel):
y = aifc.open(filename, 'wb')
y.setnchannels(1)
y.setsampwidth(self.sampwidth)
y.setframerate(self.framerate)
... | annel].flatten().tobytes())
|
wexi/python-for-android | pythonforandroid/recipes/asn1crypto/__init__.py | Python | mit | 426 | 0.002347 | from pythonforandroid.recipe import PythonRecipe
class Asn1cryptoRecipe(PythonRecipe):
name = 'asn1crypto'
version = '0.23 | .0'
url = 'https://pypi.python.org/packages/31/53/8bca924b30cb79d6d70dbab6a99e8731d1e4dd3b090b7f3d8412a8d8ffbc/asn1crypto-0.23.0.tar.gz#md5=97d54665c397b72b165768398dfdd876'
depends = ['python2', 'setuptools']
call_hostpython | _via_targetpython = False
recipe = Asn1cryptoRecipe()
|
ESOedX/edx-platform | common/lib/xmodule/xmodule/video_module/video_module.py | Python | agpl-3.0 | 51,311 | 0.002904 | # -*- coding: utf-8 -*-
"""Video is ungraded Xmodule for support video content.
It's new improved video module, which support additional feature:
- Can play non-YouTube video sources via in-browser HTML5 video player.
- YouTube defaults to HTML5 mode from the start.
- Speed changes in both YouTube and non-YouTube video... | native_languages.get(lang, display)
for lang, display in settings.ALL_LANGUAGES
if lang in other_lang
}
if not other_lang or (other_lang and sub):
languages['en'] = 'English'
# OrderedDict for easy testing of rendered context in tests
sorted_languag... | track_url, transcript_language, sorted_languages
@property
def youtube_deprecated(self):
"""
Return True if youtube is deprecated and hls as primary playback is enabled else False
"""
# Return False if `hls` playback feature is disabled.
if not HLSPlaybackEnabledFlag.fea... |
Cinntax/home-assistant | homeassistant/components/device_tracker/__init__.py | Python | apache-2.0 | 5,372 | 0.000931 | """Provide functionality to keep track of devices."""
import asyncio
import voluptuous as vol
from homeassistant.loader import bind_hass
from homeassistant.components import group
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ... | not None
}
if attributes:
data[ATTR_ATTRIBUTES] = attri | butes
hass.services.call(DOMAIN, SERVICE_SEE, data)
async def async_setup(hass: HomeAssistantType, config: ConfigType):
"""Set up the device tracker."""
tracker = await legacy.get_tracker(hass, config)
legacy_platforms = await setup.async_extract_config(hass, config)
setup_tasks = [
lega... |
richtier/imhotep | imhotep/repomanagers.py | Python | mit | 4,477 | 0 | import logging
import os
from tempfile import mkdtemp
from .repositories import Repository, AuthenticatedRepository
log = logging.getLogger(__name__)
class RepoMana | ger(object):
"""
Manages creation and deletion of `Repository` objects.
"""
to_cleanup = {}
def __init__(self, authenticated=False, cache_directory=None,
tools=None, executor=None, shallow_clone=False):
se | lf.should_cleanup = cache_directory is None
self.authenticated = authenticated
self.cache_directory = cache_directory
self.tools = tools or []
self.executor = executor
self.shallow = shallow_clone
def get_repo_class(self):
if self.authenticated:
return Au... |
ASCIT/donut-python | donut/default_config.py | Python | mit | 472 | 0 | """Default website configur | ations, used only for testing.
"""
from donut import environment
# Public Test Database
TEST = environment.Environment(
db_hostname="localhost",
db_name="donut_test",
db_user="donut_test",
db_password="public",
debug=True,
testing=True,
secret_key="1234567890",
imgur_api={
"id"... | ": "****************************************"
},
restricted_ips=r"127\.0\.0\.1")
|
rm-hull/luma.core | luma/core/sprite_system.py | Python | mit | 8,896 | 0.000787 | # -*- coding: utf-8 -*-
# Copyright (c) 2017-2020 Richard Hull and contributors
# See LICENSE.rst for details.
"""
Simplified sprite animation framework.
.. note:: This module is an evolving "work-in-progress" and should be treated
as such until such time as this notice disappears.
"""
from time import sle... | # Reframe the sprite map in terms of the registration point (if set)
regX = self.frames.regX if hasattr(self.frames, "regX") else 0
regY = self.frames.regY if hasattr(self.frames, "regY") else 0
self.image = self.image.crop((regX, regY, self.image.width - regX, self.image.height - regY))
... | f.image.size
assert(self.width % self.frames.width == 0)
assert(self.height % self.frames.height == 0)
self.frames.size = (self.frames.width, self.frames.height)
if not hasattr(self.frames, 'count'):
self.frames.count = (self.width * self.height) // (self.frames.width * sel... |
BartoszCichecki/onlinepython | onlinepython/pypy-2.4.0-win32/lib_pypy/cffi/_pycparser/c_parser.py | Python | gpl-2.0 | 59,384 | 0.001381 | #------------------------------------------------------------------------------
# pycparser: c_parser.py
#
# CParser class: Parser and AST builder for the C language
#
# Copyright (C) 2008-2013, Eli Bendersky
# License: BSD
#------------------------------------------------------------------------------
import re
from ... | ._parse_error(
"Typedef %r previ | ously declared as non-typedef "
"in this scope" % name, coord)
self._scope_stack[-1][name] = True
def _add_identifier(self, name, coord):
""" Add a new object, function, or enum member name (ie an ID) to the
current scope
"""
if self._scope_stack[-1].get(... |
tensorflow/tensorflow | tensorflow/python/autograph/pyct/static_analysis/activity_test.py | Python | apache-2.0 | 23,693 | 0.006078 | # Copyright 2017 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... | .add(QN('foo'))
col.add(QN('bar'))
scope.merge_from(other)
self.assertReadWrite(QN('foo'), scope)
self.ass | ertReadWrite(QN('bar'), scope)
self.assertIn(QN('foo'), scope.bound)
self.assertIn(QN('bar'), scope.bound)
self.assertIn(QN('foo'), scope.deleted)
self.assertIn(QN('bar'), scope.deleted)
def test_copy_of(self):
scope = activity.Scope(None)
scope.read.add(QN('foo'))
other = activity.Scope.... |
shankari/e-mission-server | emission/net/usercache/formatters/ios/transition.py | Python | bsd-3-clause | 3,275 | 0.006107 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.transition as et
import emission... | data = ad.AttrDict()
data.curr_state = state_map[entry.data.currState].value
logging.debug("Mapped %s -> %s" % (entry.data.currState, data.curr_state))
# The iOS state diagram is significantly more complex than the android state diagram
# So there are a lot more transitions. But some of the interme... | hat requires looking at a window of
# transitions, which we don't have here. Let's focus on simply mapping here and
# deal with collapsing later
# data.transition_raw = entry.data.transition
data.transition = transition_map[entry.data.transition].value
if entry.data.transition is not None:
... |
simonluijk/aws-ecs-service-discovery | register.py | Python | mit | 6,803 | 0.001029 | #!/usr/bin/env python
"""
A toolkit for identifying and advertising service resources.
Uses a specific naming convention for the Task Definition of services. If you
name the Task Definition ending with "-service", no configuration is needed.
This also requires that you not use that naming convention for task definiti... | e(service_name, method, prefix):
"""
Update DNS to allow discovery of properly | named task definitions.
"""
info = get_service_info(service_name)
if not info:
return None
if method == 'dns':
network = get_zone_for_vpc(info["vpc_id"])
ips = [t['ip'] for t in info['tasks']]
logging.info('Registering {0}.{1} as {2}'.format(
inf... |
carlosvin/pricecalculator | data_input/__init__.py | Python | apache-2.0 | 1,020 | 0.015686 | # -*- coding: utf8 -*-
from urllib.request import Request, urlopen
import logging
import parsing
__author__ = 'carlos'
class Downloader(object):
def __init__(self, url):
self.url = url
def read(self):
request = Request( self.url )
request.add_header('Accept-encoding', 't... | pdater(object):
def __init__(self, url):
self.downloader = Downloader(url)
self.parser = parsing.StockParser()
| def update(self):
dataread = self.downloader.read()
self.parser.feed(dataread)
return self.parser.stocks
@property
def stocks(self):
return self.parser.stocks
@property
def url(self):
return self.downloader.url
|
AllanYangZhou/oppia | core/controllers/suggestion.py | Python | apache-2.0 | 5,721 | 0.001049 | # coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... | scores to review
# Will be added as part of milestone 2 of the generali | zed review system
# project.
@acl_decorators.can_edit_exploration
def put(self, exploration_id, suggestion_id):
if not constants.USE_NEW_SUGGESTION_FRAMEWORK:
raise self.PageNotFoundException
if len(suggestion_id.split('.')) != 3:
raise self.InvalidInputException('In... |
ademariag/kapitan | kapitan/validator/base.py | Python | apache-2.0 | 369 | 0.00271 | # SPDX-FileCopyrightText: 2020 The Kapitan Authors <kapitan-admins@googlegroups.com>
#
# SPDX-License-Identifier: Apache-2.0
import logging
logger = loggi | ng.getLogger(__name__)
class | Validator(object):
def __init__(self, cache_dir, **kwargs):
self.cache_dir = cache_dir
def validate(self, validate_obj, **kwargs):
raise NotImplementedError
|
mlperf/training_results_v0.5 | v0.5.0/nvidia/submission/code/translation/pytorch/fairseq/modules/grad_multiply.py | Python | apache-2.0 | 550 | 0 | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
| # the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
class GradMultiply(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale):
ctx.scale = scale
res = x.new(x)
return res
... | d * ctx.scale, None
|
kaedroho/wagtail | wagtail/tests/modeladmintest/apps.py | Python | bsd-3-clause | 251 | 0 | from django.apps import AppConfig
from django.utils | .translation import gettext_lazy as _
class WagtailTestsAppConfig(AppConfig):
name = 'wagt | ail.tests.modeladmintest'
label = 'modeladmintest'
verbose_name = _("Test Wagtail Model Admin")
|
tensorflow/tensorflow | tensorflow/python/data/kernel_tests/from_sparse_tensor_slices_test.py | Python | apache-2.0 | 8,944 | 0.007603 | # Copyright 2017 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... | t)
self.assertAllEqual(s, results.values)
expected_indices = np.array(
[[j] for j in range(len(slices[i]))]).reshape([-1, 1])
self.assertAllEqual(expected_indices, results.indices)
self.assertAllEqual(dense_shape[1:], results.dense_shape)
with self.assertRaises(errors.O... | tions.times(
combinations.combine(tf_api_version=1, mode=["graph"]),
combinations.combine(slices=[[
[1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], [], [], []
], [[1., 2.], [], [1., 2.], [1.], [1., 2.], [], [1., 2.]]])))
def testFromSparseTensorSlicesInReverse(self, slice... |
mccdaq/mcculw | mcculw/device_info/daq_device_info.py | Python | mit | 4,437 | 0 | from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... | exp_info.append(ExpInfo(self._board_num, expansion_num))
return exp_info
class ExpInfo:
def __init__(self, | board_num, expansion_num):
self._board_num = board_num
self._expansion_num = expansion_num
@property
def board_type(self):
return ul.get_config(InfoType.EXPANSIONINFO, self._board_num,
self._expansion_num, ExpansionInfo.BOARDTYPE)
@property
def mux... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.