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 |
|---|---|---|---|---|---|---|---|---|
SCM-NV/qmworks-namd | test/test_coupling.py | Python | mit | 3,774 | 0.00106 | """Test the derivative coupling calculation."""
import os
import shutil
from typing import Sequence
import numpy as np
from assertionlib import assertion
from nanoqm.common import DictConfig, is_data_in_hdf5, retrieve_hdf5_data
from nanoqm.workflows.input_validation import process_input
from nanoqm.workflows.workflow... | kflow_derivative_couplings(config)
| check_couplings(config, tmp_hdf5, "alphas")
check_couplings(config, tmp_hdf5, "betas")
check_hamiltonians(result_alphas[0])
check_hamiltonians(result_betas[0])
def check_couplings(config: DictConfig, tmp_hdf5: str, orbitals_type: str) -> None:
"""Check that the couplings have meaning... |
GomSpace/libcsp | examples/python_bindings_example_client.py | Python | lgpl-2.1 | 1,900 | 0.003158 | #!/usr/bin/python | 3
# Build required code:
# $ ./examples/buildall.py
#
# Start zmqproxy (only one instance)
# $ ./build/zmqproxy
#
# Run client against server using ZMQ:
# $ LD_LIBRARY_PATH=build PYTHONPATH=build python3 examples/python_bindings_example_client.py -z localhost
#
import os
import time
import sys
import argparse
import... | .")
parser.add_argument("-a", "--address", type=int, default=10, help="Local CSP address")
parser.add_argument("-c", "--can", help="Add CAN interface")
parser.add_argument("-z", "--zmq", help="Add ZMQ interface")
parser.add_argument("-s", "--server-address", type=int, default=27, help="Server address")
... |
stormi/tsunami | src/primaires/objet/types/assiette.py | Python | bsd-3-clause | 1,930 | 0.004145 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# l... | NG NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le type Assiette."""
from .conteneur_nourriture import ConteneurNourriture
class Assiette(ConteneurNourriture):
"""Type d'objet: assiette
"""
... | def __init__(self, cle=""):
"""Constructeur de l'objet"""
ConteneurNourriture.__init__(self, cle)
self.poids_max = 12
|
uwosh/uwosh.thememain | uwosh/thememain/interfaces.py | Python | gpl-2.0 | 176 | 0.017045 | from zope.interface import Interface
class ISectionNavigation(Interface):
"""
A Folder can impleme | nt this to specify that it | is a section navigation
folder
""" |
PetePriority/home-assistant | homeassistant/components/keyboard/__init__.py | Python | apache-2.0 | 2,078 | 0 | """
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
... | keyboard | .tap_key(keyboard.volume_down_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key),
schema=TAP_KEY_SCHEMA)
hass.ser... |
anhstudios/swganh | data/scripts/templates/object/static/structure/general/shared_streetlamp_medium_style_01.py | Python | mit | 464 | 0.047414 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
resu | lt = Static()
result.template = "object/static/structure/general/shared_streetlamp_medium_style_01.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return re | sult |
KirtoXX/Security_Camera | ssd_mobilenet/object_detection/trainer.py | Python | apache-2.0 | 12,596 | 0.004843 | # 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... | import ops as util_ops
from object_detection.utils import variables_helper
from d | eployment import model_deploy
slim = tf.contrib.slim
def _create_input_queue(batch_size_per_clone, create_tensor_dict_fn,
batch_queue_capacity, num_batch_queue_threads,
prefetch_queue_capacity, data_augmentation_options):
"""Sets up reader, prefetcher and returns inp... |
tensorflow/gan | tensorflow_gan/examples/progressive_gan/networks.py | Python | apache-2.0 | 15,202 | 0.005328 | # coding=utf-8
# Copyright 2022 The TensorFlow GAN Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | mages - 1 (which means we
# are already at the highest resolution), we want to keep progress constant.
# Therefore, cap current_image_id here.
capped_current_image_id = tf.minimum(
current_image_id,
min_total_num_images(stable_stage_num_images, transition_stage_num_images,
| num_blocks) - 1)
stage_num_images = stable_stage_num_images + transition_stage_num_images
progress_integer = tf.math.floordiv(capped_current_image_id, stage_num_images)
progress_fraction = tf.maximum(
0.0,
tf.cast(
tf.math.mod(capped_current_image_id, stage_num_images) -
... |
reanahub/reana-client | tests/test_version.py | Python | mit | 444 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2017, 2018, 2020, 2021 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the | MIT License; see LICENSE file for more details.
"""REANA client tests."""
from __future__ import absolute_import, print_function
def test_version():
"""Test version import."""
from reana_client import __version | __
assert __version__
|
MiracleWong/PythonBasic | LiaoXueFeng/buildin/use_urllib.py | Python | mit | 340 | 0.002941 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'MiracleWong'
from urllib import request
with request.urlopen('http://news-at.zh | ihu.com/api/4/news/latest') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', data.decode('utf- | 8')) |
aidin36/beneath-a-binary-sky | src/world/square_iterator.py | Python | gpl-3.0 | 3,416 | 0.001464 | # This file is part of Beneath a Binary Sky.
# Copyright (C) 2016, Aidin Gharibnavaz <[email protected]>
#
# Beneath a Binary Sky 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
# Lice... | LAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with B | eneath a Binary Sky. If not, see
# <http://www.gnu.org/licenses/>.
import math
class SquareInterator:
'''Iterates squares around a point.
Note that first returning point is the center point itself.
example usage:
for x, y in SquareIterator((4, 3), (100, 100))
'''
ITERATION_DIRECTIONS =... |
Qwlouse/Findeco | node_storage/tests/test_nodepath_cache.py | Python | gpl-3.0 | 3,574 | 0.002518 | #!/usr/bin/python
# coding=utf-8
# region License
# Findeco is dually licensed under GPLv3 or later and MPLv2.
#
################################################################################
# Copyright (c) 2012 Klaus Greff <[email protected]>
# This file is part of Findeco.
#
# Findeco is free software; you can r... | ode_storage.path_helpers import get_root_node
class NodePathCacheTest(TestCase):
def setUp(self):
self.root = get_root_node()
def test_root_node_has_path(self):
r = PathCache.objects.get(path='').node
self.assertEqual(r, self.root)
p = PathCache.objects.get(node=self.root).pa... | Equal(p, '')
def test_append_child_slot_adds_to_path_cache(self):
slot = create_slot('Foo')
self.root.append_child(slot)
self.assertEqual(slot, PathCache.objects.get(path='Foo').node)
self.assertEqual('Foo', PathCache.objects.get(node=slot).path)
def test_append_child_structure... |
vlebedynskyi/Automator | test/test_tools/test_http_utils.py | Python | apache-2.0 | 4,938 | 0.000203 | """
Copyright 2014 Vitalii Lebedynskyi
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, soft... | final_url = "https://google.com/Some/test/Path?key=value&key_int=12"
final_url2 = "https://google.com/Some/test/Path?key_int=12&key=value"
result = builder.build()
try:
self.assertEqual(result, final_url)
except AssertionError:
self.assertEqual(result, final_u... | der = UrlBuilder(url)
builder.append_path(path)
builder.scheme("https://")
final_url = "https://google.com/Some/test/Path"
self.assertEqual(builder.build(), final_url)
def test_build_without_path(self):
url = "http://google.com"
args = {"key": "value", "key_int": 12... |
Darthkpo/xtt | openpyxl/cell/read_only.py | Python | mit | 3,850 | 0.001818 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from openpyxl.compat import unicode
from openpyxl.cell import Cell
from openpyxl.utils.datetime import from_excel
from openpyxl.styles import is_date_format, Style
from openpyxl.styles.numbers import BUILTIN_FORMATS
from openpyxl.styles.style... | raise AttributeError("Cell is read only")
if value is None:
self.data_type = 'n'
elif self.data_type == 'n':
try:
value = int(value)
except ValueError:
value = float(value)
self._value = value
@property
def st... | protection=self.protection)
EMPTY_CELL = ReadOnlyCell(None, None, None, None)
|
brainwane/zulip | zilencer/management/commands/print_initial_password.py | Python | apache-2.0 | 1,088 | 0.002757 | from argparse import ArgumentParser
from typing import Any
from zerver.lib.init | ial_password import initial_password
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.users import get_api_key
class Command(ZulipBaseComm | and):
help = "Print the initial password and API key for accounts as created by populate_db"
fmt = '%-30s %-16s %-32s'
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument('emails', metavar='<email>', type=str, nargs='*',
help="email of user to ... |
rbessick5/PrairieLearn | exampleCourse/questions/examplePLDrawingSimpleTutorial/server.py | Python | agpl-3.0 | 4,964 | 0.006245 | import random
import math
import numpy as np
def generate(data):
canvas_width = 300
canvas_height = 300
data["params"]["canvas_width"] = canvas_width
data["params"]["canvas_height"] = canvas_height
# Creating all variables, even knowing that just a few would be used in this Ex... | true"
arc_orientation_text = "clockwise"
else:
dat | a["params"]["arc_orientation"] = "false"
arc_orientation_text = "counter-clockwise"
# ------------------------------------------
# distributed load
# ------------------------------------------
wmin = 20
wmax = 60
angle = random.choice([0,180])
if rand... |
oleg-cherednik/hackerrank | Python/Introduction/Python - Division/solution.py | Python | apache-2.0 | 120 | 0.008333 | #!/bin/pytho | n3
if __name__ == '__main__':
a = int(input())
b = i | nt(input())
print(a // b)
print(a / b) |
lifulong/account-manager | src/core/file_store.py | Python | gpl-2.0 | 4,172 | 0.040029 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
"""
from exception import *
class base_storage:
def __init__(self, usr=None, usr_key=None):
self.usr_key = None
self.usr = None
self.records = []
if usr is None:
return
self.load_info_from_file()
if self.usr != usr:
raise UsrError
if self.usr_ke... | cord(self, record):
"""
append one record to record file
"""
with open("passwd", "a+") as f:
f.write("{0}:{1}:{2}:{3}:{4}:{5}\n".format(record[0], record[1], record[2], record[3], record[4], record[5]))
def flush_all(self):
"""
flus | h usr&passwd and account record info to record file
"""
with open("passwd", "w+") as f:
if self.usr is not None:
f.write("usr:{0}\n".format(self.usr))
if self.usr_key is not None:
f.write("key:{0}\n".format(self.usr_key))
f.write("#{0}\t:\t{1}\t:\t{2}\t:\t{3}\t:\t{4}\t:\t{5}\n".
format("Ower",... |
HaebinShin/tensorflow | tensorflow/python/kernel_tests/sparse_ops_test.py | Python | apache-2.0 | 27,450 | 0.00969 | # 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... | se_ops.sparse_to_indicator(sp_input, 50).eval()
expected_output = np.zeros((5, 50), dtype=np.bool)
expected_trues = ((0, 0), (1, 10), (1, 13), (1, 14), (3, 32), (3, 33))
for expected_true in expected_trues:
expected_output[expected_true] = True
self.assertAllEqual(output, expected_outp... | self.test_session(use_gpu=False):
sp_input = self._SparseTensor_5x6(dtypes.int64)
output = sparse_ops.sparse_to_indicator(sp_input, 50).eval()
expected_output = np.zeros((5, 50), dtype=np.bool)
expected_trues = [(0, 0), (1, 10), (1, 13), (1, 14), (3, 32), (3, 33)]
for expected_true in exp... |
orione7/plugin.video.streamondemand-pureita | core/cloudflare(old).py | Python | gpl-3.0 | 6,228 | 0.013327 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta 4
# Copyright 2015 [email protected]
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#
# Distributed under the terms of GNU General Public License v3 (GPLv3)
# http://www.gnu.org/licenses/gpl-3.0.html
# --... | return response
def decode(self, data):
t = time.time()
timeout = False
while not timeout:
data = re.sub("\[\]", "''", data)
data = re.sub("!\+''", "+1", data)
data = re.sub("!''", "0", data)
data = re.sub("!0", "1", | data)
if "(" in data:
x, y = data.rfind("("), data.find(")", data.rfind("(")) +1
part = data[x+1:y-1]
else:
x=0
y = len(data)
part = data
val = ""
if not... |
jhesketh/zookeepr | zkpylons/tests/functional/test_template.py | Python | gpl-2.0 | 2,064 | 0.002907 | from zkpylons.tests.functional import *
class TestTemplateController(ControllerTest):
"""Tests the Template controller and wiki integration."""
# Implementation
def setUp(self):
super(TestTemplateController, self).setUp()
self.logged_in = False
# create a user
self.p = m... | self.assertEquals(1, resp.body.count('<html'))
self.assertEquals(1, resp.body.count('<body'))
self.assertEquals(1, resp.body.count | ('<head'))
|
luoguizhou/gooderp_addons | app_odoo_customize/models/ir_ui_view.py | Python | agpl-3.0 | 576 | 0.006944 | # -*- coding: utf-8 -*-
import logging
from openerp import api, fields, models, _
_logger = logging.getLogger(__name__)
class View(models.Model):
_inherit = 'ir.ui.view'
@api.model
def render_ | template(self, template, values=None, engine='ir.qweb'):
if template in ['web.login', 'web.webclient_bootstrap']: |
if not values:
values = {}
values["title"] = self.env['ir.config_parameter'].get_param("app_system_name", "odooApp")
return super(View, self).render_template(template, values=values, engine=engine) |
jelly/calibre | src/calibre/gui2/convert/lrf_output.py | Python | gpl-3.0 | 1,262 | 0.006339 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.convert.lrf_output_ui import Ui_Form
from calibre.gui2.convert imp... | et
font_family_model = None
class PluginWidget(Widget, Ui_Form):
TITLE = _('LRF output')
HELP = _('Options specific to')+' LRF '+_('output')
COMMIT_NAME = 'lrf_output'
ICON = I('mimetypes/lrf.png')
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(... | space', 'header', 'header_format',
'minimum_indent', 'serif_family',
'render_tables_as_images', 'sans_family', 'mono_family',
'text_size_multiplier_for_rendered_tables', 'autorotation',
'header_separation', 'minimum_indent']
)
self.... |
JoeyAndres/moodle-parallel-phpunit | utility.py | Python | gpl-2.0 | 7,806 | 0.005124 | """
utility.py
This is where functions that belongs to a reasonably size module.
This is also the place for functions that uses "os.system" which are
inherently UGLY.
"""
import time
import os
import subprocess
import re
import xml.etree.ElementTree as ET
# Local
import config
import const
"""
@type function|l... |
def build_container(container_name, docker_file, docker_file_directory):
cmd = "{0}/build-container.sh {1} {2} {3}".format(
config.bash_files,
container_name,
docker_file,
docker_file_directory)
os.system(cmd)
"""
Starts the docker container.
@type string
@param containe... | ainer(container_name):
cmd = "{0}/start-container.sh {1}".format(
config.bash_files,
container_name)
os.system(cmd)
"""
Remove docker container if it exist. Nothing happens otherwise.
@type string
@param container_name Name of the container to remove.
"""
def remove_container(container_name):
... |
hugovk/congress-legislators | scripts/sweep.py | Python | cc0-1.0 | 1,432 | 0.007682 | #!/usr/bin/env python
from utils import load_data, save_data
def run():
# load in members, orient by bioguide ID
print("Loading current legislators...")
current = load_data("legislators-current.yaml")
current_bioguide = { }
for m in current:
if "bioguide" in m["id"]:
current_bioguid... | nt.keys()):
for member in membership_current[committee_id]:
if member["bioguide"] not in current_bioguide:
print("\ | t[%s] Ding ding ding! (%s)" % (member["bioguide"], member["name"]))
membership_current[committee_id].remove(member)
save_data(membership_current, "committee-membership-current.yaml")
# remove out-of-office people from social media info
print("Sweeping social media accounts...")
socialmedia_cu... |
hes19073/hesweewx | bin/weewx/reportengine.py | Python | gpl-3.0 | 33,225 | 0.001625 | #
# Copyright (c) 2009-2020 Tom Keffer <[email protected]>
#
# See the file LICENSE.txt for your full rights.
#
"""Engine for generating reports"""
from __future__ import absolute_import
# System imports:
import datetime
import ftplib
import glob
import logging
import os.path
import threading
import time
import... | lf._build_skin_dict(report)
except SyntaxError as e:
log.error("Syntax error: %s", e)
log.error(" **** Report ignored")
continue
# Default action is to run the report. Only reason to not run it is
# if we have a valid report re... | timing_line = skin_dict.get('report_timing')
if timing_line:
# Get a ReportTiming object.
timing = ReportTiming(timing_line)
if timing.is_valid:
# Get timestamp and interval so we can check if the
... |
CAMI-challenge/evaluation | binning/igregor/algbioi/eval/cami.py | Python | mit | 3,516 | 0.001138 | #!/usr/bin/env python
"""
Copyright (C) 2014 Ivan Gregor
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 version.
... | gnmen | tFile)
else:
return csv.predToDict(assignmentFile)
def readCami(camiAssignFile):
"""
Reads a file in the cami format
@rtype: dict
"""
ret = {}
for line in open(camiAssignFile):
line = line.strip()
if not (line.startswith('#') or line.startswith('@') or len(... |
zsoltdudas/lis-tempest | tempest/api/network/admin/test_agent_management.py | Python | apache-2.0 | 3,750 | 0 | # Copyright 2013 IBM Corp.
#
# 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 t... | = self.admin_agents_client.list_agents()
agents = body['agents']
# Hearthbeats must be excluded from comparison
self.agent.pop('heartbeat_timestamp', None)
self.agent.pop('configurations', None)
for agent in agents:
agent.pop('heartbeat_timestamp', None)
a... | est_list_agents_non_admin(self):
body = self.agents_client.list_agents()
self.assertEqual(len(body["agents"]), 0)
@test.idempotent_id('869bc8e8-0fda-4a30-9b71-f8a7cf58ca9f')
def test_show_agent(self):
body = self.admin_agents_client.show_agent(self.agent['id'])
agent = body['age... |
ankit318/appengine-mapreduce | python/test/mapreduce/model_test.py | Python | apache-2.0 | 13,422 | 0.00447 | #!/usr/bin/env python
#
# Copyright 2010 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... | rgs as a ha | ndler."""
mapper_spec = self.specForHandler(
__name__ + "." + TestHandlerWithArgs.__name__)
self.assertRaises(TypeError, mapper_spec.get_handler)
def testMethodHandlerWithConstructorArgs(self):
"""Test method from a class with constructor args as a handler."""
mapper_spec = self.specForHandle... |
Homegateway/SDTTool | sdtv3/SDT3PrintPlain.py | Python | apache-2.0 | 8,166 | 0.038207 | # SDT3PrintPlain.py
#
# Print SDT3 to Plain text
from .SDT3Classes import *
hideDetails = False
# tabulator level
tab = 0
def incTab():
global tab
tab += 1
def decTab():
global tab
if (tab > 0):
tab -= 1
def newLine():
global tab
result = '\n'
for i in range(tab):
result += '\t'
return result
#
# Pr... | newLine() + printProperty(prop)
for module in device.modules:
result += newLine() + printModule(module)
for subDevice in device.subDevices:
result += newLine() + printSubDevice(subDevice)
decTab()
return result
def printSubDevice(subDevice):
global hideDetails
result = 'SubDevice [id="' + subDevice.id + '... | Device.properties:
result += newLine() + printProperty(prop)
for module in subDevice.modules:
result += newLine() + printModule(module)
decTab()
return result
#
# Property
#
def printProperty(prop):
result = 'Property ['
incTab()
if (prop.name != None):
result += 'name="' + prop.name + '"'
if (prop.val... |
wojtask/CormenPy | test/test_chapter05/test_textbook5_3.py | Python | gpl-3.0 | 589 | 0 | from unittest import TestCase
from hamcrest import *
from array_util impor | t get_random_array
from chapter05.textbook5_3 import permute_by_sorting, randomize_in_place
class TestTextbook5_3(TestCase):
def test_permute_by_sorting(self):
array, elements = get_random_array()
array = permute_by_sorting(array)
assert_that(array.elements, contains_inanyorder(*element... | anyorder(*elements))
|
penoud/GrovePi | Software/Python/grove_barometer_sensors/barometric_sensor_bmp085/grove_barometer_example_BMP085.py | Python | mit | 1,813 | 0.00717 | #!/usr/bin/env python
#
# GrovePi Example for using the Grove Barometer module (http://www.seeedstudio.com/depot/Grove-Barometer-HighAccuracy-p-1865.html)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question abo... | re is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO T | HE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 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... |
kappataumu/cookiecutter-django | hooks/pre_gen_project.py | Python | bsd-3-clause | 184 | 0.01087 | project_slug = '{{ cookiecutter.project_slug }}'
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifie | r(), 'Project slug should be valid P | ython identifier!'
|
iand/pynappl | old/contentbox_add.py | Python | gpl-2.0 | 936 | 0.03312 | """contentbox_add.py
Supports adding to the contentbox"""
import httplib2
from errors import *
class ContentboxAddCommand(object):
h = httplib2.Http()
def __init__(self, store_uri=None, data=None, type="application/x-unknown"):
| self.store_uri = (store_uri is not None and store_uri.endswith("/")) and store_uri[:-1] or store_uri
self.data = data
self.type = type
def set_store_uri( | self, store_uri):
self.store_uri = store_uri.endswith("/") and store_uri[:-1] or store_uri
def set_data(self, data):
self.data = data
def set_type(self, type):
self.type = type
def login(self, un, pw):
self.h.add_credentials(un, pw)
def execute(self):
uri = self.store_uri + "/items"
headers, data = self... |
googleads/google-ads-python | google/ads/googleads/v8/services/services/merchant_center_link_service/client.py | Python | apache-2.0 | 26,385 | 0.001251 | # -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ["credentials"] = credentials
return cls(*args, **kwargs)
@classmeth | od
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments t... |
jberci/resolwe | resolwe/flow/serializers/contributor.py | Python | apache-2.0 | 1,499 | 0.000667 | """Resolwe contributor serializer."""
from django.contrib import auth
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.fields import empty
from resolwe.rest.serializers import SelectiveFieldMixin
class ContributorSerializer(SelectiveFieldMixin, seriali... | as the applications may not yet be ready at this point.
model = None
fields = (
'f | irst_name',
'id',
'last_name',
'username',
)
def __init__(self, instance=None, data=empty, **kwargs):
"""Initialize attributes."""
# Use the correct User model.
if self.Meta.model is None:
self.Meta.model = auth.get_user_model()
... |
Sokrates80/air-py | aplink/messages/ap_imu.py | Python | mit | 2,582 | 0.001936 | """
airPy is a flight controller based on pyboard and written in micropython.
The MIT License (MIT)
Copyright (c) 2016 Fabrizio Scimia, [email protected]
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... | otice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT ... | AGES OR 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 struct
# TODO split this message into two: IMU and MOTORS
class ImuStatus:
def __init__(self, h_builder, attitude):
... |
dkdeconti/PAINS-train | training_methods/clustering/dbscan_PAINS_pca.py | Python | mit | 1,174 | 0 | __author__ = 'ddeconti'
import FileHandler
import numpy
import sys
from bokeh.plotting import figure, output_file, show, VBox, HBox
from rdkit import DataStructs
from sklearn.cluster import DBSCAN
from sklearn.decomposition.pca import PCA
def train_pca(pains_fps, num_components=3):
'''
Dimensional reductio... | ts
:param pains_fps:
:return: pca reduced fingerprints bit vectors
'''
np_fps = []
for fp in pains_fps:
arr = numpy.zeros((1,))
DataStructs.ConvertToNumpyArray(fp, arr)
np_fps.append(arr)
pca = PCA(n_components=num_components)
pca.fit(np_fps)
fps_reduced = pca | .transform(np_fps)
return fps_reduced
def train_dbscan(pains_fps):
db = DBSCAN(eps=1, min_samples=10).fit(pains_fps)
print db.labels_
pass
def main(sa):
pains_filename = sa[0]
pains_fps = FileHandler.SlnFile(pains_filename).get_fingerprint_list()
reduced_pains_fps = train_pca(pains_fps, ... |
nka11/KaraCos-Desktop | py/utils/client/ssh.py | Python | gpl-3.0 | 4,477 | 0.006478 | """
KaraCos-Desktop - web platform engine client for desktop users - http://karacos.org/
Copyright (C) 2009-2010 Nicolas Karageuzian
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 Fou... | proxy_connexion.establish()
sock = proxy_connexion.socket
if sock == None:
raise Exception("Erreur RESEAU")
#self.sock = ssl.wrap_socket(sock)
#sock = ssl.wrap_socket(proxy_connexion.socket,do_handshake_on_connect=False)
#sock = proxy_con... | elf._transport = Transport(sock)
t.banner_timeout = 180
if self._log_channel is not None:
t.set_log_channel(self._log_channel)
t.start_client()
ResourceManager.register(self, t)
server_key = t.get_remote_server_key()
keytype = server_key.get_name()
... |
zhangg/trove | trove/tests/unittests/secgroups/test_security_group.py | Python | apache-2.0 | 6,773 | 0 | # Copyright 2012 OpenStack Foundation
#
# 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... | .nova.LOG')
def test_failed_to_delete_security_group_rule(self, mock_logging):
self.assertRaises(exception.SecurityGroupRuleDeletionError,
| sec_mod.RemoteSecurityGroup.delete_rule,
1, self.context,
region_name=CONF.os_region_name)
class fake_RemoteSecGr(object):
def data(self):
self.id = uuid.uuid4()
return {'id': self.id}
def delete(self, context, region_name)... |
wwright2/dcim3-angstrom1 | sources/bitbake/lib/bb/data.py | Python | mit | 15,316 | 0.006399 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
"""
BitBake 'Data' implementations
Functions for interacting with the data structure used by the
BitBake build tools.
The expandKeys and update_data are the most expensive
operations. At night the cookie monster came by and
sugge... | return _dict_type()
def init_db(parent = None):
"""Return a new object representing the Bitbake data,
optionally based on an existing object"""
if parent is not None:
return parent.createCopy()
else:
return _dict_type()
def createCopy(source):
"""Link the source set to the dest... | urce are copy-on-write. i.e. any try to
modify one of them will end up putting the modified value
in the destination set.
"""
return source.createCopy()
def initVar(var, d):
"""Non-destructive var init for data structure"""
d.initVar(var)
def setVar(var, value, d):
"""Set a variable to a ... |
escattone/kuma | kuma/users/tests/test_auth.py | Python | mpl-2.0 | 720 | 0 | from django.test import RequestFactory
from kuma.users.auth import logout_url
# TODO: Check which new tests are needed.
def test_logout_url(settings):
| request = RequestFactory().get("/some/path")
request.session = {}
url = logout_url(request)
assert url == "/"
request = Requ | estFactory().get("/some/path?next=/docs")
request.session = {}
url = logout_url(request)
assert url == "/docs"
settings.LOGOUT_REDIRECT_URL = "/loggedout"
request = RequestFactory().get("/some/path")
request.session = {}
url = logout_url(request)
assert url == "/loggedout"
request.... |
ahaberlie/MetPy | src/metpy/_vendor/xarray.py | Python | bsd-3-clause | 2,816 | 0.001065 | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Vendor core functionality used from xarray.
This code has been reproduced with modification under the terms of the Apache License, Version
2.0 (notice included below).
Copyr... |
"""
if not isinstance(key, tuple):
# numpy treats non-tuple keys equivalent to tuples of length 1
key = (key,)
new_key = []
# handling Ellipsis right is a little tricky, see:
# http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
found_ellipsis = Fals... | found_ellipsis = True
else:
new_key.append(slice(None))
else:
new_key.append(k)
if len(new_key) > ndim:
raise IndexError('too many indices')
new_key.extend((ndim - len(new_key)) * [slice(None)])
return tuple(new_key)
def is_dict_like(value):
... |
jokey2k/sentry | src/sentry/features/__init__.py | Python | bsd-3-clause | 510 | 0 | from __futu | re__ import absolute_import
|
from .base import * # NOQA
from .handler import * # NOQA
from .manager import * # NOQA
default_manager = FeatureManager()
default_manager.add('auth:register')
default_manager.add('social-auth:register')
default_manager.add('organizations:create')
default_manager.add('organizations:sso', OrganizationFeature)
defau... |
armadill-odyssey/aima-python | submissions/Dickenson/myCSPs.py | Python | mit | 1,998 | 0.026527 | import csp
rgb = ['R', 'G', 'B']
domains = {
'Aosta Valley': rgb,
'Piedmont': rgb,
'Liguria': rgb,
'Lombardy': rgb,
'Trentino': rgb,
'South Tyrol': rgb,
'Veneto': rgb,
'Friuli-Venezia Giulia': rgb,
'Emilia-Romagna': rgb,
'Tuscany': rgb,
'Umbria': rgb,
'Marche': rgb,
... | Lombardy','Emilia-Romagna'],
'Liguria': ['Piedmont','Emilia-Romagna','Tuscany'],
'Lombardy': ['Piedmont','Emilia-Romagna','Veneto','Trentino','South Tyrol'],
'Trentino': ['South Tyrol','Veneto','Lombardy'],
'South Tyrol': ['Lombardy','Trentino','Veneto'],
| 'Veneto': ['Friuli-Venezia Giulia','Trentino','South Tyrol','Lombardy','Emilia-Romagna'],
'Friuli-Venezia Giulia': ['Veneto'],
'Emilia-Romagna': ['Veneto','Lombardy','Tuscany','Liguria','Marche','Piedmont'],
'Tuscany': ['Liguria','Emilia-Romagna','Marche','Umbria','Lazio'],
'Umbria': ['Tuscany','Lazio',... |
mmktomato/zenmai-bts | web/models/state.py | Python | mit | 690 | 0.001449 | """State c | lass definition."""
from . import get_db
db = get_db()
class State(db.Model):
"""State class.
Extends Model of 'Flask-SQLAlchemy'.
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), nullable=Fal | se)
value = db.Column(db.Integer, unique=True, nullable=False)
def __init__(self, name, value):
"""Creates a instance of this class."""
self.name = name
self.value = value
def __repr(self):
return '{}([])'.format(self.name, self.value)
@classmethod
def all(cls):
... |
gaocegege/treadmill | treadmill/cli/admin/checkout/ldap.py | Python | apache-2.0 | 551 | 0 | """Checkout LDAP infrastructure."""
import click
from treadmill import cli
from tr | eadmill import context
from treadmill.checkout import ldap as ldap_test
def init():
"""Top level command handler."""
@click.command('ldap')
@click.option('--ldap-list', required=True, envvar='TREADMILL_LDAP_LIST',
type=cli.LIST)
def check_ldap(ldap_list):
"""Checkout LDAP in... | turn lambda: ldap_test.test(ldap_list, ldap_suffix)
return check_ldap
|
kidaa/entropy | lib/tests/core.py | Python | gpl-2.0 | 1,396 | 0.004298 | # -*- coding: utf-8 -*-
import sys
sys.path.insert(0, 'client')
sys.path.insert(0, '../../client')
sys.path.insert(0, '.')
sys.path.insert(0, '../')
import unittest
from entropy.core import EntropyPluginStore, Singleton
from entropy.core.settings.base import SystemSettings
import tests._misc as _misc
class CoreTest(un... | f.assertTrue(files) # not empty
def test_core_singleton(self):
class myself(Singleton):
def init_singleton(self):
| pass
obj = myself()
obj2 = myself()
self.assertTrue(obj is obj2)
if __name__ == '__main__':
unittest.main()
raise SystemExit(0)
|
NicovincX2/Python-3.5 | Physique/Mouvement/Dynamique/Systèmes oscillants/Pendule/animate_a_pendulum_pygame.py | Python | gpl-3.0 | 2,683 | 0.001118 | # -*- coding: utf-8 -*-
import os
import pygame
import sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")
screen = pygame.display.get_surface... | Dtheta = -sin(radians(lasttheta)) * scaling
lastDtheta = midDtheta + (midDDtheta + lastDDtheta) / 2.0
lasttheta = midtheta + (midDtheta + lastDtheta) / 2.0
self.dtheta = lastDtheta
self.theta = lasttheta
self.rect = pygame.Rect(PIVOT[0] -
SWINGLEN... | def draw(self):
pygame.draw.circle(screen, (0, 0, 0), PIVOT, 5, 0)
pygame.draw.circle(screen, (0, 0, 0), self.rect.center, BOBSIZE, 0)
pygame.draw.aaline(screen, (0, 0, 0), PIVOT, self.rect.center)
pygame.draw.line(screen, (0, 0, 0),
(0, PIVOT[1]), (WINDOWSIZ... |
yfpeng/pengyifan-leetcode | src/main/python/pyleetcode/fizz_buzz.py | Python | bsd-3-clause | 999 | 0.003003 | """
Write a program that outputs the string representation of | numbers from 1 to n.
But for multiples of three it should output "Fizz" instead of the number and for the multiples of five output "Buzz".
For numbers which are multiples of both three and five output "FizzBuzz".
"""
def fizz_buzz(n):
"""
:type n: int
:rtype: List[str]
"""
output = []
for i ... | t.append('Buzz')
else:
output.append(str(i))
return output
def test_fizz_buzz():
expected = [
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
... |
ninchat/offhand | python/offhand/__init__.py | Python | bsd-2-clause | 1,817 | 0.00055 | __all__ = [
"CorruptedMessage",
"Stats",
"UnexpectedCommand",
"UnexpectedEOF",
"UnknownCommand",
"log",
]
import logging
import struct
log = logging.getLogger("offhand")
class UnexpectedEOF(Exception):
def __init__(self):
Exception.__init__(self, "Connection closed unexpectedly"... |
part_size, = struct.unpack("<I", data[offset: offset + 4])
offset += 4
| if remain < 4 + part_size:
raise CorruptedMessage()
message.append(data[offset: offset + part_size])
offset += part_size
return message
|
shrimpboyho/herblore | pyglet-1.1.4/examples/programming_guide/events.py | Python | gpl-2.0 | 2,441 | 0.002868 | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... | '''
__docformat__ = 'restructuredtext'
__version__ = '$Id: events.py 1966 2008-03-23 07:01:26Z Alex.Holkner $'
import pyglet
from pyglet.window import key
from pyglet.window import mouse
window = pyglet.window.Window()
@window.event
def on_key_press(symbol, modifiers):
if symbol == key.A:
print 'The "A"... | The enter key was pressed.'
@window.event
def on_mouse_press(x, y, button, modifiers):
if button == mouse.LEFT:
print 'The left mouse button was pressed.'
@window.event
def on_draw():
window.clear()
pyglet.app.run()
|
itsmeolivia/language-learner | translate.py | Python | mit | 241 | 0.029046 | from textblob import TextBlob
def to_english(message, original_language=None):
blob = TextBlob(text)
if original_language is not None:
return blob.translate(from_lang=orig | inal_language, to="en")
el | se:
return blob.translate(to="en") |
quixey/python-aliyun | tests/unit/aliyun/slb/model_test.py | Python | apache-2.0 | 7,883 | 0.000761 | # -*- coding:utf-8 -*-
# Copyright 2014, Quixey 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 l... | atus 1 at '))
class TCPListenerTest(unittest.TestCase):
def testEqual(self):
l1 = TCPListener('id', 1, 1)
l2 = TCPListener('id', 1, 1)
self.assertEqual(l1, l2)
def testNotEqual(self):
l1 = TCPListener('id', 1, 1)
l2 = TCPListener('id', 1, 2)
self.assertNotEqua... | ener = TCPListener('id', 1, 1)
self.assertTrue(repr(listener).startswith(u'<TCPListener on 1 for id'))
class HTTPListenerTest(unittest.TestCase):
def testEqual(self):
l1 = HTTPListener('id', 1, 1)
l2 = HTTPListener('id', 1, 1)
self.assertEqual(l1, l2)
def testNotEqual(self):
... |
EthanBlackburn/sync-engine | tests/general/test_tags_updates.py | Python | agpl-3.0 | 4,145 | 0.000483 | import pytest
import datetime
from inbox.models.account import Account
from inbox.models.thread import Thread
from inbox.models.folder import Folder, FolderItem
from inbox.models.message import Message
from inbox.models.backends.imap import ImapUid
from inbox.mailsync.backends.imap.common import (recompute_thread_label... | puid | .is_seen = True
update_unread_status(imapuid)
assert message.is_read is True, "message should be read"
tag_names = [tag.name for tag in thread.tags]
assert 'unread' not in tag_names, "thread should be read"
|
alexfalcucc/anaconda | anaconda_lib/linting/anaconda_pyflakes.py | Python | gpl-3.0 | 5,568 | 0.003592 | # -*- coding: utf8 -*-
# Copyright (C) 2013 - Oscar Campos <[email protected]>
# This program is Free Software see LICENSE file for details
import re
import _ast
from linting import linter
import pyflakes.checker as pyflakes
pyflakes.messages.Message.__str__ = (
lambda self: self.message % self.messa... | re.escape(error.message_args[0])
)
error_data['regex'] = regex
error_list.append(error_data)
elif (isinstance(
error, (
pyflakes.messages.UnusedImport,
pyflakes.messages.ImportStarUsed)) and
... | portStarUsed):
word = '*'
else:
word = error.message_args[0]
linematch = '(from\s+[\w_\.]+\s+)?import\s+(?P<match>[^#;]+)'
r = '(^|\s+|,\s*|as\s+)(?P<underline>[\w]*{0}[\w]*)'.format(
re.escape(word)
... |
gista/django-selectfilter | selectfilter/utils.py | Python | mit | 1,579 | 0.034832 | # -*- coding: utf-8 -*-
# request helpers
def _cleanValue(value):
mapping = {
"True": True,
"False": False,
"None": None,
}
return mapping.get(value, value)
def lookupToString(lookup_dict):
"""
Convert the lookup dict into a string.
e.g.:
{"field1": "a", "field2": "b"} -> "field1=a,field2=b"
"""
ret... | ce.
Return it as a list.
"""
return list(lookups() if callable(lookups) else lookups)
def _getManager(model, select_related):
if select_related is not None:
return model.objects.select_related(*select_related.split(","))
return model.objects
def getObjects(model, lookup_dict, select_related):
"""
Return the... | anager(model, select_related)
return manager.filter(**lookup_dict)
def getObject(model, lookup_dict, select_related):
"""
Return the model instance given the model, the lookup dict and
the select_related part of the queryset (ignored if None).
"""
manager = _getManager(model, select_related)
return manager.get... |
hfutsuchao/Python2.6 | SEOKeywordsAnalysis/KWComp.py | Python | gpl-2.0 | 3,699 | 0.0092 | #coding:utf-8
import urllib
import sys
file2014 = open('2014Kresult.txt','r').readlines()
file2015 = open('2015Kresult.txt','r').readlines()
result = open('2015result.txt','w')
dic2014 = {}
dic2015 = {}
dic = {}
uvCount = 0
pvCount = 0
ec = 0
c = 0
pv2014 = 0
pv2015 = 0
#2014关键字去重汇总
for line i... | dic2015[kw] = dic2015[kw] + int(pv[:-1])
else:
dic2015[kw] = int(pv[:-1])
pv2015 = pv2015 + int(pv[:-1])
except:
pri | nt line
print pv2014, pv2015
#计算二者之间的交集和差集
dif2015 = list(set(dic2015) - set(dic2014))
dif2014 = list(set(dic2014) - set(dic2015))
same = list(set(dic2014)&set(dic2015))
print '2015 and 2014:', len(dic2015), len(dic2014)
print 'same:',len(same), 'dif2014:', len(dif2014), 'dif2015:',len(dif2015)
citys = op... |
joopert/home-assistant | tests/components/deconz/test_scene.py | Python | apache-2.0 | 2,229 | 0.000897 | """deCONZ scene platform tests."""
from copy import deepcopy
from asynctest import patch
from homeassistant.components import deconz
from homeassistant.setup import async_setup_component
import homeassistant.components.scene as scene
from .test_gateway import ENTRY_CONFIG, DECONZ_WEB_REQUEST, setup_deconz_integrati... | assert len(gateway.deconz_ids) == 0
assert len(hass.states.async_all()) == 0
async def test_scenes(hass):
"""Test that scenes works."""
data = deepcopy(DECONZ_WEB_REQUEST)
data["groups"] = deepcopy(GROUPS)
gateway = await setu | p_deconz_integration(
hass, ENTRY_CONFIG, options={}, get_state_response=data
)
assert "scene.light_group_scene" in gateway.deconz_ids
assert len(hass.states.async_all()) == 1
light_group_scene = hass.states.get("scene.light_group_scene")
assert light_group_scene
group_scene = gateway... |
DONIKAN/django | django/contrib/auth/management/commands/changepassword.py | Python | bsd-3-clause | 2,610 | 0.002682 | from __future__ import unicode_literals
import getpass
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT... | ass("Password (again): ")
if p1 != p2:
self.stdout.write("Passwords do not match. Please try again.\n")
co | unt += 1
# Don't validate passwords that don't match.
continue
try:
validate_password(p2, u)
except ValidationError as err:
self.stdout.write(', '.join(err.messages))
count += 1
else:
pass... |
yamstudio/Codeforces | 100/118A - String Task.py | Python | gpl-3.0 | 109 | 0.018349 | word = raw_input().lower()
v = | 'aeiouy' |
n = ''
for c in word:
if not c in v:
n += '.' + c
print n |
jvicu2001/alexis-bot | bot/modules/guildlist.py | Python | mit | 1,174 | 0.002555 | from discord import Embed
from bot import Command, categories
class GuildList(Command):
def __init__(self, bot):
super().__init__(bot)
self.name = 'guildlist'
self.aliases = ['guilds']
self.category = categories.SETTINGS
self.bot_owner_only = True
async def handle(sel... | wait cmd.answer('$[guildlist-msg]', locales={'amount': len(self.bot.guilds)}, to_author=True)
resp_list = ''
for guild in self.bot.guilds:
item = '- {} ({})'.format(guild.name, guild.id)
if len('{}\n{}'.format(resp_list, item)) > 2000:
await cmd | .answer(Embed(description=resp_list), withname=False, to_author=True)
resp_list = ''
else:
resp_list = '{}\n{}'.format(resp_list, item)
# Send remaining list
if resp_list != '':
await cmd.answer(Embed(description=resp_list), withname=False, to_aut... |
rafaeltg/pydl | pydl/models/linear/__init__.py | Python | mit | 50 | 0 | from . | lasso import Lasso
from .ridge | import Ridge
|
otadmor/Open-Knesset | simple/management/commands/parse_government_bill_pdf/textutil.py | Python | bsd-3-clause | 2,023 | 0.008403 | from itertools import chain
import re
from hashlib import md5
superscript = u'\u200F'
digits = set([str(i) for i in xrange(10)])
def fix_superscripts(txt):
""" Note: call this before reverse_numbers!!
Here's what happens:
We have the following input to pdftotext
AAAAA XS DBBB
What we get is
... | s(s):
ret = []
start = 0
for match in re.finditer('[0-9\.]+', s):
sl = slice(*match.span())
ret.append(s[start:sl.start])
ret.append(reversed(s[sl]))
start = sl.stop
ret.append(s[start:])
return ''.join(chain(*ret))
def sanitize(lines):
""" remove non text unicod... | place(u'\u202b','').replace(u'\u202c','').replace(u'\x0c','')
for line in lines]
def text_block_iter(lines):
block = []
for line in lines:
if line.strip() == '':
if len(block) > 0:
yield block
block = []
continue
block.append(l... |
donkawechico/arguman.org | web/profiles/models.py | Python | mit | 5,320 | 0.000564 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Count
from django.dispatch import receiver
from django.template.loader import render_to_string
fro... | no | tification_type=NOTIFICATION_REPORTED_AS_FALLACY,
target_object_id=report.id
)
@receiver(added_premise_for_premise)
def create_premise_answer_notification(sender, premise, *args, **kwargs):
if premise.user != premise.parent.user:
Notification.objects.create(
sender=premise.user,
... |
cc-archive/commoner | src/commoner/profiles/tests/__init__.py | Python | agpl-3.0 | 76 | 0 | from test_delete import *
from test_openid i | mport *
from test_edit import *
| |
jimboca/ISYHelperHABridge | ihab/ISY.py | Python | apache-2.0 | 11,333 | 0.0105 |
try:
# python 2.7
from urllib import quote
from urllib import urlencode
except ImportError:
# python 3.4
from urllib.parse import quote
from urllib.parse import urlencode
import sys
import re
import PyISY
class isy():
def __init__(self,config,logger,status,bridge):
s... | orce as string | to make habridge happy?
self.name = str(name)
self.main = main
self.scene = scene
self.map_id = str("isy:%s" % (self.main._id))
self.parent.logger.info('isy:node:.__init__: name=%s node=%s scene=%s' % (self.name, self.main, self.scene))
# Subscribe to cha... |
saketkc/open-ehr-django | open-ehr-django-src/report_manager/forms.py | Python | lgpl-3.0 | 1,714 | 0.012252 | from django import forms
from open-ehr.report_manager.models import *
class NewReportTypeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.report_belongs_to_lab = kwargs.pop('report_belongs_to_lab', None)
super(NewReportTypeForm, self).__init__(*args, **kwargs)
def save(self, com... | ReportResults
exclude =('lab_owner','report_type')
def report_result_form(test_name_fields):
fields = {'user_mobile' : forms.CharField(max_length=11),"user_dob":forms.CharField(),}
for test_id in test_name_fields:
fields[test_name_fields[test_id]] = forms.CharField(max_length=100)
return t... | .BaseForm,), { 'base_fields': fields })
|
plouto5/Python | phone_sms/send_message.py | Python | gpl-3.0 | 255 | 0.031373 | from clockwork import | clockwork
api = clockwork.API('e22468d6b972f1425f77827f6f279d11b4b2c183')
message = clockwork.SMS(from_name = "The Dark Master", to = "6129102910", mes | sage = "I am watching you.....")
response = api.send(message)
print(response)
|
rohitranjan1991/home-assistant | tests/components/mqtt/test_cover.py | Python | mit | 102,124 | 0.000793 | """The tests for the MQTT cover platform."""
from unittest.mock import patch
import pytest
from homeassistant.components import cover
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_CURRENT_TILT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
)
from homeassistant.components.mqtt ... | payload_close": "CLOSE",
"payload_stop": "STOP",
"state_opening": "34",
"state_closing": "--43",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.a... | sync_fire_mqtt_message(hass, "state-topic", "34")
state = hass.states.get("cover.test")
assert state.state == STATE_OPENING
async_fire_mqtt_message(hass, "state-topic", "--43")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSING
async_fire_mqtt_message(hass, "state-topi... |
twiest/openshift-tools | ansible/roles/lib_openshift_3.2/library/oc_pvc.py | Python | apache-2.0 | 40,439 | 0.002646 | #!/usr/bin/env python # pylint: disable=too-many-lines
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
# | |) | (_) ... | ctor)
if self.all_namespaces:
cmd.extend(['--all-namespaces'])
elif self.namespace:
cmd.exten | d(['-n', self.namespace])
cmd.extend(['-o', 'json'])
if rname:
cmd.append(rname)
rval = self.openshift_cmd(cmd, output=True)
# Ensure results are retuned in an array
if rval.has_key('items'):
rval['results'] = rval['items']
elif not isinstance(... |
armstrong/armstrong.apps.images | armstrong/apps/images/migrations/0001_initial.py | Python | apache-2.0 | 8,342 | 0.008032 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Image'
db.create_table('images_image', (
('content_ptr', self.gf('django.db.mo... | 'pub_status': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'sections': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'content_content_alternates | '", 'null': 'True', 'symmetrical': 'False', 'to': "orm['arm_sections.Section']"}),
'sites': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sites.Site']", 'symmetrical': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
... |
abishara/athena_meta | athena/stages/check_reads.py | Python | mit | 5,478 | 0.011318 | import os
import sys
import pysam
import random
from collections import Counter
from .step import StepChunk
from ..mlib import util
from ..mlib.fq_idx import FastqIndex
MIN_SEED_SIZE = 400
MIN_COV = 10.
class CheckReadsStep(StepChunk):
@staticmethod
def get_steps(options):
assert os.path.isfile(options.inpu... | specified (for debugging)
if self.options.cheat_seeds:
self.logger.broadcast('using cheat seeds file: {}'.format(self.options.cheat_seeds))
seeds = set()
with open(self.options.cheat_seeds) as fin:
for line in fin:
seed = line.strip()
seeds.add(seed)
self.logger.b... | ad mappings from *bam to select seeds without high enough input
# coverage
else:
self.logger.broadcast('get seed contigs from input assembly')
ctg_covs, bam_num_se_bcoded = self.get_bam_stats()
if bam_num_se_bcoded < 0.8 * fq_num_se_bcoded:
print \
'''lower than expected amount (~{:2.2... |
macky360/Bitcoin-Related_Addresses | lib/marketquery/exceptions.py | Python | gpl-2.0 | 148 | 0.013514 | class DateNotFoundError(Exception):
def __init__(self, value):
self.value = valu | e
def __str__(self):
return re | pr(self.value) |
laosiaudi/tensorflow | tensorflow/python/kernel_tests/decode_raw_op_test.py | Python | apache-2.0 | 2,806 | 0.009622 | # 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... | ss or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for DecodeRaw op from parsing_ops."""
from __future__ import absolute_import
from __future__ import division
f... | ensorflow as tf
class DecodeRawOpTest(tf.test.TestCase):
def testToUint8(self):
with self.test_session():
in_bytes = tf.placeholder(tf.string, shape=[2])
decode = tf.decode_raw(in_bytes, out_type=tf.uint8)
self.assertEqual([2, None], decode.get_shape().as_list())
result = decode.eval(f... |
sestrella/ansible | lib/ansible/module_utils/network/nxos/argspec/interfaces/interfaces.py | Python | gpl-3.0 | 2,238 | 0 | #
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by ... | ue,
'type': 'str'
},
'speed': {
'type': 'str'
}
},
'type': 'list'
},
'state': {
'choices': ['merged', 'replaced', 'overridden', 'deleted'],
'default': 'merged',
... | # pylint: disable=C0301
|
drepetto/chiplotle | chiplotle/geometry/core/test/test_path_add.py | Python | gpl-3.0 | 1,814 | 0.007166 | from chiplotle.geometry.core.path import Path
from chiplotle.ge | ometry.core.coordinate import Coordinate
from chiplotle.core import errors
from py.test import raises
def test_path_add_01( ):
'''A Path and an int cannot be added.'''
assert raises(TypeError, 'Path([(1, 2), (3, 4)]) + 3')
def test_path_add_02( ):
'''A Path and a float cannot be added.'''
assert rais... | ed.'''
assert raises(TypeError, '3.2 + Path([(1, 2), (3, 4)])')
def test_path_add_03( ):
'''A Path and a Coordinate can be added.'''
a = Path([(1, 2), (3, 4)])
t = a + Coordinate(1, 2)
assert t is not a
assert isinstance(t, Path)
assert t == Path([(2, 4), (4, 6)])
def test_path_radd_03( ... |
anhstudios/swganh | data/scripts/templates/object/tangible/lair/base/shared_objective_data_terminal.py | Python | mit | 457 | 0.04814 | #### NOTICE: THIS FILE IS AUTOGENER | ATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/lair/base/shared_objective_data_termi | nal.iff"
result.attribute_template_id = -1
result.stfName("lair_n","data_terminal")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
REGOVAR/Regovar | regovar/core/managers/__init__.py | Python | agpl-3.0 | 954 | 0.001048 | #!env/python3
# coding: utf-8
from core.managers.containers import *
from core.managers.imports import *
from core.managers.analysis_manager import AnalysisManage | r
from core.managers.annotation_manager import AnnotationManager
from core.managers.file_manager import FileManager
from core.managers.filter_manager import FilterEngine
from core.managers.job_manager import JobManager
from core.managers.pipeline_manager import PipelineManager
from core.managers.project_manager i... | anagers.user_manager import UserManager
from core.managers.search_manager import SearchManager
from core.managers.event_manager import EventManager
from core.managers.subject_manager import SubjectManager
from core.managers.admin_manager import AdminManager
from core.managers.phenotype_manager import PhenotypeMana... |
eustislab/horton | horton/cache.py | Python | gpl-3.0 | 14,592 | 0.001234 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2015 T | he HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON 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.
#
# HORTON is di... | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
#--
'''Avoid recomputation of earlier results and reallocation of existing arrays
In principle, the ``JustOnceClass`` and the `... |
eSDK/esdk_uc_control_js | open_src/firebreath/fbgen.py | Python | apache-2.0 | 7,056 | 0.009212 | #!/usr/bin/env python
# encoding: utf-8
"""
Utility script to generate/modify Firebreath plug-in projects.
Original Author(s): Ben Loveridge, Richard Bateman
Created: 14 December 2009
License: Dual license model; choose one of two:
New BSD License
http://www.opensource.org/licenses/bsd-li... | kdir(dirName)
else:
createDir(parentDir)
createDir(dirName)
def Main():
"""
Parse the commandline and execute the appropriate actions.
"""
# Define the command-line interface via OptionParser
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_opti... | est = "pluginName")
parser.add_option("-i", "--plugin-identifier", dest = "pluginIdent",
help = "3 or more alphanumeric characters (underscores allowed after first position)")
parser.add_option("-c", "--company-name", dest = "companyName")
parser.add_option("-d", "--company-domain", dest = "companyD... |
DarioGT/OMS-PluginXML | org.modelsphere.sms/lib/jython-2.2.1/Lib/email/MIMEImage.py | Python | gpl-3.0 | 1,794 | 0.001115 | # Copyright (C) 2001,2002 Python Software Foundation
# Author: [email protected] (Barry Warsaw)
"""Class representing image/* type MIME documents.
"""
import imghdr
from email import Errors
from email import Encoders
from email.MIMENonMultipart import MIMENonMultipart
class MIMEImage(MIMENonMultipart)... | data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify t | he specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload t... |
SalesforceFoundation/CumulusCI | cumulusci/core/template_utils.py | Python | bsd-3-clause | 1,409 | 0 | from functools import lru_cache
from faker import Faker
from jinja2 import Template
class StringGenerator:
"""Sometimes in templates you want a reference to a variable to
call a function.
For example:
>>> x = template_utils.StringGenerator(datetime.today().isoformat)
>>> print(f"{x}")
2019-... | les or {}
if isinstance(value, str) and "{" in value:
value = Template(value).render(fake=fake, **variab | les)
return value
|
gov-cjwaszczuk/notifications-admin | app/main/views/new_password.py | Python | mit | 2,038 | 0.003925 | from datetime import datetime
import json
from flask import (render_template, url_for, redirect, flash, session, current_app)
from itsdangerous import SignatureExpired
from notifications_utils.url_safe_token import check_token
from app import user_api_client
from app.main import main
from app.main.forms import NewPas... | ed_at and datetime.strptime(user.password_changed_at, '%Y-%m-%d %H:%M:%S.%f') > \
datetime.strptime(json.loads(token_data)['created_at'], '%Y-%m-%d %H:%M:%S.%f'):
flash('The link in the email has already been used')
return redirect(url_for('main.index'))
form = NewPasswordF | orm()
if form.validate_on_submit():
user_api_client.reset_failed_login_count(user.id)
session['user_details'] = {
'id': user.id,
'email': user.email_address,
'password': form.new_password.data}
if user.auth_type == 'email_auth':
# they've just... |
CodieCodemonkey/PyCog | examples/eight_queens.py | Python | lgpl-3.0 | 5,809 | 0.001549 | """Backtracking example: 8-queens problem."""
if __name__ == "__main__":
import sys
import os.path as op
sys.path.append(op.abspath(op.join('..', 'packages')))
from pycog.statemachine import *
from pycog.exceptions import *
from pycog.backtrack import *
from pycog.utility.diagram import diagram
# Strateg... | ded so that we have something to backtrack to | in order
to choose a different first column queen. It isn't absolutely
necessary since we know there is a solution with a queen in the first
row of the first column.
"""
pass
@state("final", accepting=True)
def final(self):
"""A solution is found, draw the boar... |
gillett-hernandez/project-euler | Python/problem_14.py | Python | mit | 954 | 0.019916 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: Gillett Hernandez
# @ | Date: | 2016-07-14 17:06:40
# @Last Modified by: Gillett Hernandez
# @Last Modified time: 2016-09-03 00:19:08
def Collatz(n, seen={}):
steps_list = [n]
if n in seen:
return seen[n]
steps=1
i=n
while i>1:
steps+=1
if i%2==0:
i=i/2
else:
i=3*i+1
... |
nephantes/dolphin-tools | docs/conf.py | Python | mit | 9,231 | 0.006067 | # -*- coding: utf-8 -*-
#
# dolphintools documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 12 22:39:14 2015.
#
# 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.
... | itle.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favico | n of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will ove... |
webmasterraj/FogOrNot | flask/lib/python2.7/site-packages/pandas/core/internals.py | Python | gpl-2.0 | 150,471 | 0.000764 | import copy
import itertools
import re
import operator
from datetime import datetime, timedelta
from collections import defaultdict
import numpy as np
from pandas.core.base import PandasObject
from pandas.core.common import (_possibly_downcast_to_dtype, isnull,
_NS_DTYPE, _TD_DTYPE, AB... |
-------
None
"""
self.values[locs] = values
def delete(self, loc):
"""
Delete given loc(-s) from block in-place.
"""
self.values = np.delete(self.values, loc, 0)
self.mgr_locs = self.m | gr_ |
greenoaktree/gr-burst | python/qa_synchronizer_v2.py | Python | gpl-3.0 | 1,453 | 0.009635 | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest
from ... | self.burst1 = x['burst1'].transpose().astype(dt)
self.burst2 = x['burst2'].transpose().astyp | e(dt)
self.burst3 = x['burst3'].transpose().astype(dt)
self.burst4 = x['burst4'].transpose().astype(dt)
self.burst5 = x['burst5'].transpose().astype(dt)
def tearDown (self):
None
def test_001_t (self):
print 'Running Synchronizer Test 1'
pmt... |
Happyholic1203/VNF-Deployment | lib/utils.py | Python | mit | 5,154 | 0.002134 | from solver import *
from ds import *
import random
import time
class TestCase(object):
def __init__(self, name, flowSettings=None,
depth=3, fanout=2, minFlowAmount=0, maxFlowAmount=1,
minNumFlowsPerHost=2, maxNumFlowsPerHost=5):
if not self.checkFlowSettings(flowSettings):
rais... | (flowAmounts),
'max': max(flowAmounts),
| 'avg': (totalFlowAmount / float(numFlows))
},
'totalFlowAmount': totalFlowAmount
}
records = []
for solver in solvers:
startTime = time.time()
solver.solve(self.tree)
print '** Runtime [%s]: %.2f seconds' % \
... |
msfrank/Higgins | higgins/server.py | Python | lgpl-2.1 | 8,312 | 0.003128 | # Higgins - A multi-media server
# Copyright (c) 2007-2009 Michael Frank <[email protected]>
#
# This program is free software; for license information see
# the COPYING file.
import sys, pwd, grp, os, signal
from django.core.management import call_command as django_admin_command
from twisted.internet import r... | """
Initialize the application
"""
# check runtime dependencies
try:
import twisted
import django
import xml.etree.ElementTree
import mutagen
import setuptools
except ImportError, e:
raise ServerException("%... | try:
os.makedirs(env, 0755)
os.makedirs(os.path.join(env, 'logs'), 0755)
os.makedirs(os.path.join(env, 'plugins'), 0755)
os.makedirs(os.path.join(env, 'media'), 0755)
except Exception, e:
raise ServerException("Startup fa... |
gale320/newfies-dialer | newfies/apirest/view_contenttype.py | Python | mpl-2.0 | 1,134 | 0.000882 | # -*- coding: utf-8 -*-
#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the te | rms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <[email protected]>
#
from rest_framework import... | types.models import ContentType
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from permissions import CustomObjectPermissions
class ContentTypeViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint that allows cont... |
WillisXChen/django-oscar | oscar/lib/python2.7/site-packages/django_extensions/management/commands/graph_models.py | Python | bsd-3-clause | 7,278 | 0.00371 | import six
import sys
from optparse import make_option, NO_DEFAULT
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_extensions.management.modelviz import generate_dot
try:
import pygraphviz
HAS_PYGRAPHVIZ = True
except ImportError:
HAS_PYGRAPHV... | PYGRAPHVIZ:
raise CommandError("You need to install pygraphviz python module")
version = pygraphviz.__version__.rstrip("-svn")
try:
if tuple(int(v) for v in version.split('.')) < (0, 36):
# HACK around old/broken AGraph before version 0.36 (ubuntu ships with this... | tmpfile = tempfile.NamedTemporaryFile()
tmpfile.write(dotdata)
tmpfile.seek(0)
dotdata = tmpfile.name
except ValueError:
pass
graph = pygraphviz.AGraph(dotdata)
graph.layout(prog=kwargs['layout'])
graph.draw(kwargs['out... |
cherry-wb/SideTools | examples/graphicsview/collidingmice/collidingmice.py | Python | apache-2.0 | 7,219 | 0.004156 | #!/usr/bin/env python
############################################################################
##
## Copyright (C) 2006-2006 Trolltech ASA. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## Licensees holding a valid Qt License Agreement may use this file in
## ac... | 8, 8)
painter.drawEllipse(2, -17, 8, 8)
# Nose.
painter.setBrush(QtCore.Qt.black)
painter.drawEllipse(QtCore.QRectF(-2, -22, 4, 4))
# Pupils.
painter.drawEllipse(QtCore.QRectF(-8.0 + self.mouseEyeDirection, -17, 4, 4))
paint | er.drawEllipse(QtCore.QRectF(4.0 + self.mouseEyeDirection, -17, 4, 4))
# Ears.
if self.scene().collidingItems(self):
painter.setBrush(QtCore.Qt.red)
else:
painter.setBrush(QtCore.Qt.darkYellow)
painter.drawEllipse(-17, -12, 16, 16)
painter.drawE... |
sdickreuter/python-andor | test.py | Python | gpl-3.0 | 660 | 0.009091 |
import numpy as np |
import time
import matplotlib.pyplot as plt
from AndorSpectrometer import Spectrometer
spec = Spectrometer(start_cooler=False,init_shutter=True)
#time.sleep(30)
spec.SetCentreWavelength(650)
spec.SetSlitWidth(100)
# spec.SetImageofSlit()
# slit = spec.TakeImageofSlit()
#
#
spec.SetSingleTrack()
spec | .SetExposureTime(5.0)
d = spec.TakeSingleTrack()
spec.SetExposureTime(1)
d2 = spec.TakeSingleTrack()
#
# spec.SetFullImage()
# img = spec.TakeFullImage()
#
#
# print(d.shape)
plt.plot(spec.GetWavelength(),d)
plt.show()
plt.plot(spec.GetWavelength(),d2)
plt.show()
# plt.imshow(img)
# plt.show()
#
# plt.imshow(slit... |
red-hood/calendarserver | contrib/performance/loadtest/trafficlogger.py | Python | apache-2.0 | 3,436 | 0.001746 | ##
# Copyright (c) 2011-2015 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... | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex | press or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
"""
This module implements a reactor wrapper which will cause all traffic on
connections set up using that reactor to be logged.
"""
__all__ = ['loggedReactor']
from weakref import ref
from S... |
timesqueezer/portfolio | run.py | Python | mit | 417 | 0.002398 | #!env/bin/python
import sys
from portfolio import create_app
class ProductionConfig(object):
DEBUG = False
TESTING = False
app = cre | ate_app(config=ProductionConfig)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '-p':
print(' * Ru | nning in production mode')
app = create_app(config=ProductionConfig)
else:
app = create_app()
app.run(host='0.0.0.0')
|
CloudBoltSoftware/cloudbolt-forge | blueprints/citrix/citrix_itm_predictive_dns_record/management/edit_record.py | Python | apache-2.0 | 4,201 | 0.001904 | from common.methods import set_progress
from utilities.models import ConnectionInfo
from servicecatalog.models import ServiceBlueprint
from infrastructure.models import CustomField
import json
from ast import literal_eval
import requests
API_CLIENT_CI = "Citrix API"
def create_custom_fields_as_needed():
CustomF... | tokens expires after a short while and has to be regenerated.
ci = ConnectionInfo.objects.get(name=API_CLIENT_CI)
url = get_citrix_url()
response = requests.get(
"{url}/api/oauth/token?client_id={client_id}&client_secret={client_secret}&grant_type=client_credentials".format(
url=url, cl... | oken = response.json().get('access_token')
return token
def generate_options_for_recordType(**kwargs):
return ["A", "AAAA", "MX"]
def generate_options_for_editRecordType(**kwargs):
return [(True, "Yes"), (False, "No")]
def generate_options_for_editRecordValue(**kwargs):
return [(True, "Yes"), (Fa... |
Widukind/dlstats | dlstats/tests/fetchers/test_bea.py | Python | agpl-3.0 | 6,159 | 0.00552 | # -*- coding: utf-8 -*-
import io
import os
from dlstats.fetchers.bea import BEA as Fetcher
import httpretty
from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR
from dlstats.tests.fetchers.base import BaseFetcherTestCase
import unittest
from unittest import mock
RESOURCES_DIR = os.path.abspath(os.p... | @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings)
def test_upsert_dataset_10101(self):
# nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101
dataset_code = "nipa-section1-10101-a"
self._load_fi... | aset = self.assertDataset(dataset_code)
names = {
'a191rl1': 'Gross domestic product',
'dpcerl1': 'Personal consumption expenditures',
'dgdsrl1': 'Personal consumption expenditures - Goods',
'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods',
'dn... |
catapult-project/catapult | dashboard/dashboard/edit_anomalies_test.py | Python | bsd-3-clause | 6,510 | 0.002304 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
import unittest
import mock
import... | tCurrentUser('[email protected]')
self.testapp.post(
'/edit_anomalies', {
'keys': json.dumps([anomaly_keys[0].urlsafe()]),
'bug_id': 31337,
'xsrf_token': xsrf.GenerateToken(users.get_current_user()),
},
status=403)
self.assertIsNone(anomaly_keys[0].get().bug... | def testPost_LoggedIntoValidSheriffAccount_ChangesBugID(self):
anomaly_keys = self._AddAnomaliesToDataStore()
self.SetCurrentUser('[email protected]')
self.testapp.post(
'/edit_anomalies', {
'keys': json.dumps([anomaly_keys[0].urlsafe()]),
'bug_id': 31337,
'x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.