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 |
|---|---|---|---|---|---|---|---|---|
blckshrk/Weboob | modules/mangareader/__init__.py | Python | agpl-3.0 | 806 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it unde | r the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY ... | #
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .backend import MangareaderBackend
__all__ = ['MangareaderBackend']
|
cuauv/software | vision/utils/image_ordering_test.py | Python | bsd-3-clause | 877 | 0.003421 | #!/usr/bin/env python3
import cv2
import numpy as np
from vision import camera_message_framework
import itertools
import time
shape = (500, 500, 3)
size = 1
for dim in shape:
size *= dim
def image_of(axes):
im = np.zeros(shape, dtype=np.uint8)
im[:, :, axes] = 255
return im
black = image_of([]), 'bl... | ed, green, blue, yellow, cyan, pink, white]
f = camera_message_framework.Creator('forward', size)
def main():
for im, name in itertools.cycle(images):
f.write_frame(im, int(time.time() * 1000))
print('wrote {}'.f | ormat(name))
time.sleep(1)
if __name__ == '__main__':
main()
|
xiejian1985/Test | 100_Python.py | Python | gpl-3.0 | 2,354 | 0.017819 | # coding:utf-8
def test_1():
'''
1,2,3,4组成无重复的三位数
'''
for a in range(1, 5):
for b in range(1, 5):
for c in range(1, 5):
if (a!=b) and (b!=c) and (a!=c):
print(a,b,c)
print('\n------------test_1 END---------------\n')
def test_2()... | 应发奖金总数:', bonus, '元')
elif x>1000000:
bonus = 10000+7500+10000+6000+6000+0.01*(x-1000000)
print('应发奖金总数:', bonus, '元')
print('\n------------test_2 END---------------\n')
def test_3():
'''
输入三个整数x,y,z,请把这三个数由小到大输出
'''
list1 = []
for i in range(3):
x = ... | n range(10):
a, b = b, a+b
print(a)
'''
'''
def main():
for i in range(1, 4):
func = 'test_{0}()'.format(i)
exec (func)
if __name__ == "__main__":
main()
|
ldjebran/robottelo | tests/foreman/ui/test_computeprofiles.py | Python | gpl-3.0 | 2,049 | 0.003416 | """Test class for Compute Profile UI
:Requirement: Computeprofile
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: ComputeResources
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo.decorators import tier... | (compute_resource.name) in [resource['Compute Resource'] for
resource in | compute_resource_list]
session.computeprofile.rename(name, {'name': new_name})
assert entities.ComputeProfile().search(query={'search': 'name={0}'.format(new_name)}), \
'Compute profile {0} expected to exist, but is not included in the search ' \
'results'.format(new_name)
... |
Justyer/KuaikanSpider | KuaikanSpider/KuaikanSpider/items.py | Python | mit | 537 | 0.003724 | # -*- coding: utf-8 | -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
c | lass ImgItem(scrapy.Item):
image_character = scrapy.Field()
image_titles = scrapy.Field()
image_urls = scrapy.Field()
image_paths = scrapy.Field()
class ImgSingleItem(scrapy.Item):
image_character = scrapy.Field()
image_picindex = scrapy.Field()
image_title = scrapy.Field()
image_url ... |
makinacorpus/pygal | pygal/graph/bar.py | Python | lgpl-3.0 | 5,037 | 0 | # -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2014 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version... | at it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a c | opy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Bar chart
"""
from __future__ import division
from pygal.graph.graph import Graph
from pygal.util import swap, ident, compute_scale, decorate
class Bar(Graph):
"""Bar graph"""
_series_margin = .... |
robinson96/GRAPE | test/testGrape.py | Python | bsd-3-clause | 7,398 | 0.005812 | #!/usr/bin/env python
import sys
import os
import inspect
import unittest
import StringIO
import shutil
import tempfile
curPath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
if not curPath in sys.path:
sys.path.insert(0, curPath)
grapePath = os.path.join(curPath, "..")
if grapePath n... | nch("develop")
git.push("origin develop")
os.chdir(os.path.join(self.repo, ".."))
except git.GrapeGitError:
pass
self.menu = grapeMenu.menu()
if self._debug:
self.switchToStdout()
def tearDown(self):
def onError(func,... | Windows.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
"""
import stat
... |
chrisvire/aeneas | aeneas/ttswrappers/basettswrapper.py | Python | agpl-3.0 | 34,887 | 0.00192 | #!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... | lue)`` pair to the cache.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:param file_info: the path value
:type file_info: tuple | ``(handler, path)``
:raises: ValueError if the key is already present in the cache
"""
if self.is_cached(fragment_info):
raise ValueError(u"Attempt to add text already cached")
self.cache[fragment_info] = file_info
def get(self, fragment_info):
"""
Get th... |
gas1121/JapanCinemaStatusSpider | scrapyproject/pipelines.py | Python | mit | 6,140 | 0.000489 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapyproject.models import (Cinema, Showing, ShowingBooking, Movie,
db_connect, drop_tab... | ooking.showing.start_time = old_showing.start_time
showing_booking.showing.end_time = old_show | ing.end_time
showing_booking.showing.cinema_name = old_showing.cinema_name
showing_booking.showing.cinema_site = old_showing.cinema_site
showing_booking.showing.screen = old_showing.screen
showing_booking.showing.seat_type = old_showing.seat_type
showing_booki... |
skosukhin/spack | var/spack/repos/builtin/packages/sickle/package.py | Python | lgpl-2.1 | 1,879 | 0.000532 | ##############################################################################
# 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... | sliding windows along with quality and
length thresholds to determine when quality is sufficiently low to trim
the 3'-end of reads and also determines when the quality is
sufficiently high enough to trim the 5'-end of reads."""
homepage = "https://github.com/najoshi/sickle"
url = "htt... | f install(self, spec, prefix):
mkdirp(prefix.bin)
install('sickle', prefix.bin)
|
sephalon/python-ivi | ivi/agilent/agilent8590A.py | Python | mit | 1,520 | 0.001316 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2013-2014 Alex Forencich
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... | 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 SHALL THE
AUTH... | G FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .agilentBase8590A import *
class agilent8590A(agilentBase8590A):
"Agilent 8590A IVI spectrum analyzer driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'HP85... |
frogeyedpeas/ChalupaCity | working_pa1/auto_grader.py | Python | mit | 7,382 | 0.013411 | #! /usr/bin/python
import os, sys, glob, time, subprocess, signal
import popen2
subdirectories = ['first', 'second', 'third', 'fourth', 'fifth']
formats = {'first':'line', 'second':'line', 'third':'file', 'fourth':'file', 'fifth':'file'}# if a program has single liner input and output, we put all test cases in single... | run_command("make", verbose=True)
else:
print "No Makefile found in", dirname
print "Please submit a Makefile to receive full grade."
run_command("gcc -o %s *.c *.h"%(dirname), verbose=False)
def file_grade(dirname):
print "Grading", dirname
prevdir = os.getcwd()
os.chdi | r(dirname)
make_executable(dirname)
if not os.path.isfile(dirname):
print "Executable %s missing. Please check the compilation output."%(dirname)
return
for testfile in sorted(os.listdir(".")):
if os.path.isdir(testfile) or not testfile.startswith("test"):
continue
... |
kingvuplus/boom | lib/python/Screens/RdsDisplay.py | Python | gpl-2.0 | 10,176 | 0.001671 | from enigma import iPlayableService, iRdsDecoder
from Screens.Screen import Screen
from Components.ActionMap import NumberActionMap
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Pixmap import Pixmap
from Components.Label import Label
from Components.Sources.StaticText import Stati... | 15
return mask
def countAvailSubpages(self, page, masks):
|
mask = self.getMaskForPage(page, masks)
cnt = 0
while mask:
if mask & 1:
cnt += 1
mask >>= 1
return cnt
def nextPage(self):
mask = 0
page = self.current_page
while mask == 0:
|
4Quant/tensorflow | tensorflow/python/framework/importer.py | Python | apache-2.0 | 13,843 | 0.008596 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | urn_elements` is not a list of strings.
ValueError: If `input_map`, or `return | _elements` contains names that
do not appear in `graph_def`, or `graph_def` is not well-formed (e.g.
it refers to an unknown tensor).
"""
# Type checks for inputs.
if not isinstance(graph_def, graph_pb2.GraphDef):
# `graph_def` could be a dynamically-created message, so try a duck-typed
# appr... |
nirajkvinit/python3-study | 30days/day13/templates.py | Python | mit | 691 | 0.023155 | import os
def get_template_path(path):
file_path = os.path.join(os.getcwd(), path)
if not os.path.isfile(file_path):
raise Exception("This is not a valid template path %s"%(file_path))
return file_path
def get_template(path):
file_path = get_template_path(path)
return open(file_path).read()
def render_context... | (file_)
template_html = get_template(file_html)
context = {
"name": "Niraj",
"date": None,
"total": None
}
print(render_context(template, context | ))
print(render_context(template_html, context)) |
docwalter/py3status | py3status/modules/xsel.py | Python | bsd-3-clause | 1,642 | 0.000609 | # -*- coding: utf-8 -*-
"""
Display X selection.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0.5)
command: the clipboard command to run (default 'xsel -o')
format: display format for this module (default '{selection}')
max_size: strip the selection to this value (... | elf.cache_timeout),
'full_text': self.py3.safe_format(self.format, {'selection': selection})
}
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3 | status.module_test import module_test
module_test(Py3status)
|
marcelogomess/glpi_api | glpi_api/api.py | Python | bsd-2-clause | 6,202 | 0.004353 | # -*- coding: utf-8 -*-
from requests import post, get, put, delete
class Api:
def __init__(self, base_url, user_token, app_token):
self.base_url = base_url
self.app_token = app_token
self.user_token = user_token
def initSession(self):
target_url = 'initSe | ssion/'
sessiondata = {'Content-Type': 'application/json',
'Authorization': 'user_token ' + self.user_token, 'App-Token': self.app_token}
session = get(self.base_url + target_ | url, headers=sessiondata)
self.session_token = session.json()
self.session_token = self.session_token['session_token']
def killSession(self):
target_url = 'killSession'
sessiondata = {'Content-Type': 'application/json',
'Session-Token': self.session_token, 'A... |
braincorp/robustus | robustus/tests/test_bullet.py | Python | mit | 775 | 0.00129 | # =============================================================================
# COPYRIGHT 2013 Brain Corporation.
# License under MIT license (see LICENSE fi | le)
# =============================================================================
import pytest
from robustus.detail import perform_standard_test
def test_bullet_installation(tmpdir):
tmpdir.chdir()
| bullet_versions = ['bc2']
for ver in bullet_versions:
bullet_files = ['lib/bullet-%s/lib/libBulletCollision.a' % ver,
'lib/bullet-%s/lib/libBulletDynamics.a' % ver,
'lib/bullet-%s/lib/libLinearMath.a' % ver]
perform_standard_test('bullet==%s' % ver,... |
jumpserver/jumpserver | apps/jumpserver/settings/__init__.py | Python | gpl-3.0 | 153 | 0 | # -*- coding: utf-8 -*-
#
from . | base import *
from .logging import *
from .libs import *
from .auth import *
from .custom import *
from ._xpack | import *
|
LaMi-/pmatic | pmatic/api.py | Python | gpl-2.0 | 31,401 | 0.006019 | #!/usr/bin/env python
# encoding: utf-8
#
# pmatic - Python API for Homematic. Easy to use.
# Copyright (C) 2016 Lars Michelsen <lm@larsmichelsen.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | ister this to ensures the close() method is called
on interpreter shutd | own."""
atexit.register(self.close)
# is called in locked context
def _parse_api_response(self, method_name_int, kwargs, body):
# FIXME: The ccu is performing wrong encoding at least for output of
# executed rega scripts. But maybe this is a generic problem. Let's see
# and onl... |
0xalen/opencaster_isdb-tb | libs/dvbobjects/dvbobjects/MPEG/DVBH_Descriptors.py | Python | gpl-2.0 | 10,359 | 0.029443 | #! /usr/bin/env python
#
# Copyright (C) 2004 Andreas Berger, berger@ftw.at
#
# 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 v... | elf.ISO_639_language_code,
self.text_char_bytes
)
class target_serial_number_descriptor(Descriptor):
descriptor_tag = 0x08
def bytes(self):
fmt = "!%ds" % len(serial_data_bytes)
return pack(fmt,
self.serial_data_byt... | def bytes(self):
fmt = "!I%ds" % len(self.private_data_bytes)
return pack(fmt,
self.super_CA_system_id,
self.private_data_bytes
)
class target_MAC_address_descriptor(Descriptor):
descriptor_tag = 0x07
... |
joeyac/JudgeServer | client/languages.py | Python | mit | 2,209 | 0.002263 | # coding=utf-8
from __future__ import unicode_literals
c_lang_config = {
"name": "c",
"compile": {
"group_memory": True,
"src_name": "main.c",
"exe_name": "main",
"max_cpu_time": 5.0,
"max_real_time": 10.0,
"max_memory": 512 * 1024, # 512M compile memory
... | "main",
"max_cpu_time": 5.0,
"max_real_time": 10.0,
"max_memory": 512 * 1024, # 512M compile memory
"compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -st | d=c++11 {src_path} -lm -o {exe_path}",
},
"run": {
"exe_name": "main",
"max_cpu_time": 1.0,
"max_real_time": 5.0,
"max_memory": 10 * 1024, # 10M compile memory
"command": "{exe_path}",
}
}
java_lang_config = {
"name": "java",
"compile": {
"group_memo... |
JeGoi/IPa2 | packages/java_properties.py | Python | mit | 6,870 | 0.006259 | #!/usr/bin/env python
"""
Title : Java program file
Author : JG
Date : dec 2016
Objet : script to create Propertie File Program
in : get infos from yml
out : print infos in properties file
"""
import sys,os
import yaml
import util as u
from random import randint
# =====================================... | ['Program']['website']:
out.write(yml['Program']['website'])
# Color options
color = u.get_color(yml)
out.write("\ncolorMode = "+color+""+
"\ndefaultColor = "+color+"")
# Inputs types
out.write("\n#INP | UTS TYPES")
if len(yml['Inputs']) > 0:
o = ""
s = ""
for op in yml['Inputs']:
if op['type']:
out.write("\nInput"+op['type']+"=Connector"+str(op['connector']))
if op['OneConnectorOnlyFor']:
if o == "":
o = str(op['On... |
russomi/ferris3-tutorial | app/jobposts/models.py | Python | apache-2.0 | 294 | 0 | __author__ = 'russomi'
from google.appengine.ext import ndb
from ..employers.models import Employer
from ferris3 i | mport Model
class JobPost(Model):
employer = ndb.KeyProperty(kind=Employer)
title = ndb.String | Property(required=True)
description = ndb.TextProperty(required=True)
|
jteehan/cfme_tests | utils/tests/test_metadoc.py | Python | gpl-2.0 | 364 | 0 | import pytest
pytestmark = pytest.mark.meta(from_pytest='yep')
@pytest.mark.meta(fro | m_decorator='seems to be')
def test_metadoc(meta):
"""This test function has a docstring! |
Metadata:
valid_yaml: True
"""
assert meta['from_docs']['valid_yaml']
assert meta['from_pytest'] == 'yep'
assert meta['from_decorator'] == 'seems to be'
|
imito/odin | odin/preprocessing/text.py | Python | mit | 24,225 | 0.010485 | # -*- coding: utf-8 -*-
# ===========================================================================
# Popular encoding:
# utf-8
# ISO-8859-1
# ascii
# encode: string -> string of bytes
# decode: string of bytes -> string
# ===========================================================================
from __future__ ... | ordinating conjunction
SYM : symbol
X : other
"""
def __init__(self, NOUN=True, PRON=False, PROPN=True,
ADJ=True, VERB=False, ADV=True,
ADP=False, AUX=Fals | e, DET=False, INTJ=False,
NUM=False, PART=False, PUNCT=False,
SCONJ=False, SYM=False, X=False):
super(POSfilter, self).__init__()
pos = []
if NOUN: pos.append('NOUN')
if PRON: pos.append('PRON')
if PROPN: pos.append('PROPN')
if ADJ: pos.append('ADJ')
if ADP: pos... |
FTwO-O/pyShadowsocks | pyshadowsocks/packet/packet_header.py | Python | mit | 320 | 0.003125 | #!/usr | /bin/env python
# -*- coding: utf-8 -*-
#
# Author: booopooob@gmail.com
#
# Info:
#
#
#
import abc
from util import FixedDict
clas | s PacketHeader(FixedDict, metaclass=abc.ABCMeta):
@abc.abstractmethod
def to_bytes(self):
pass
@abc.abstractmethod
def from_bytes(self, data):
pass
|
botswana-harvard/edc-dashboard | edc_dashboard/templatetags/edc_dashboard_extras.py | Python | gpl-2.0 | 3,196 | 0.000626 | from django import template
from django.urls.base import reverse
from urllib.parse import urljoin, parse_qsl, urlencode, unquote
register = template.Library()
class Number:
def __init__(self, number=None, url=None, current=None):
self.number = number
| self.url = url
self.active = 'active' if current else ''
def __str__(self):
return self.number
def __repr__(self):
return f'{self.__class__.__name__}<number={ | self.number} {self.active}>'
class UrlMaker:
def __init__(self, base=None, querystring=None):
self.base = base
self.querystring = querystring
def url(self, page):
url = urljoin(self.base, str(page)) + '/'
if self.querystring:
return '?'.join([url, self.querystring]... |
hzdg/django-google-search | googlesearch/views.py | Python | mit | 2,809 | 0.002848 | from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class SearchView(TemplateView):
template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
c... | _to_index(),
num=GOOGLE_SEARCH_RESULTS_PER_PAGE,
cx=GOOGLE_SEARCH_ENGINE_ID,
).execute()
results = SearchResults(results)
pages = self.calculate_pages()
#if googleapiclient raises an error, we need to catch it here
except:
... | s = service.cse().list(
q=self.request.GET.get('q', ''),
start=1,
num=GOOGLE_SEARCH_RESULTS_PER_PAGE,
cx=GOOGLE_SEARCH_ENGINE_ID,
).execute()
#set some default values used for the context below
page = 1
# p... |
zsdonghao/tensorlayer | tensorlayer/app/human_pose_estimation/common.py | Python | apache-2.0 | 16,077 | 0.001928 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
# Reference:
- [pose_lcn](
https://github.com/rujiewu/pose_lcn)
- [3d-pose-baseline](
https://github.com/una-dinosauria/3d-pose-baseline)
"""
import tensorflow as tf
import numpy as np
import pickle
import matplotlib.pyplot as plt
import os
import matplotlib.gr... | ') as f:
gt = pickle.load(f)
return gt
def read_2d(self, which='scale', mode='dt_ft', read_confidence=True):
if self.gt_trainset is None:
self.gt_trainset = self.real_read('train')
if self.gt_testset is None:
self.gt_testset = self.real_read('test')
... | t), 17, 2)) # [N, 17, 2]
for idx, item in enumerate(self.gt_trainset):
trainset[idx] = item['joint_3d_image'][:, :2]
for idx, item in enumerate(self.gt_testset):
testset[idx] = item['joint_3d_image'][:, :2]
if read_confidence:
train_co... |
RangerOfFire/faker-cinema | faker_cinema/screen.py | Python | mit | 1,039 | 0 | from faker.providers import BaseProvider
class ScreenProvider(BaseProvider):
formats = (
'{{screen_name}} {{screen_number}}',
'{{screen_name}} {{screen_number}} ({{screen_suffix}})',
)
screen_names = (
'Screen',
'Theatre',
'Auditorium',
)
screen_suffixes = (... | .numerify(cls.random_element(('%', '%%')))
@classmethod
def screen_suffix(cls):
return cls.random_element(cls.screen_suffixes)
@classmethod
def screen_name(cls):
return cls.random_element(cls.screen_names)
def screen(self, number=None):
"""
:param number: The scree... | mber is not None:
pattern = pattern.replace('{{screen_number}}', str(number))
return self.generator.parse(pattern)
|
minusetheartbot/minusetheartbot | lib/grove_pi_v1_2_6/grovepi.py | Python | apache-2.0 | 19,052 | 0.022412 | #!/usr/bin/env python
#
# GrovePi Python library
# v1.2.2
#
# This file provides the basic functions for using the GrovePi.
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the fo... | k(address, uRead_cmd + [pin, unused, unused])
time.sleep(.2)
read_i2c_byte(address)
number = read_i2c_block(address)
return (number[1] * 256 + number[2])
# Read the firmware version
def version():
write_i2c_block(address, version_cmd + [unused, unused, unused])
time.sleep(.1)
read_i2c_byte(address)
number = r... | f acc_xyz():
write_i2c_block(address, acc_xyz_cmd + [unused, unused, unused])
time.sleep(.1)
read_i2c_byte(address)
number = read_i2c_block(address)
if number[1] > 32:
number[1] = - (number[1] - 224)
if number[2] > 32:
number[2] = - (number[2] - 224)
if number[3] > 32:
number[3] = - (number[3] - 224)
retu... |
Bushstar/UFO-Project | test/functional/feature_block.py | Python | mit | 60,904 | 0.003235 | #!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test block processing."""
import copy
import struct
import time
from test_framework.blocktools import ... | # Try to create a fork that double-spends
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b7 (2) -> b8 (4)
# \-> b3 (1) -> b4 (2)
self.log.info("Reject a chain with a double spend, even if it is longer")
... | spend=out[4])
self.sync_blocks([b8], False, reconnect=True)
# Try to create a block that has too much fee
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b9 (4)
# \-> b3 (1) -> b4 (2)
sel... |
quattor/aquilon | tests/broker/test_del_chassis.py | Python | apache-2.0 | 3,407 | 0.000587 | #!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2012,2013,2014,2015,2016,2017,2018 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance... | tils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestDelChassis(TestBrokerCommand):
def test_100_del_ut3c5_used(self):
self.dsdb_expect_delete(self.net["unknown0"].usable[6])
command = "del chassis --chassis ut3c5.aqd-unittest.ms.com"
out | = self.badrequesttest(command.split(" "))
self.matchoutput(out, "Chassis ut3c5.aqd-unittest.ms.com is "
"still in use by 3 machines or network devices. "
"Use --clear_slots if you really want to delete it.",
command.split(" ")... |
jaywink/federation | federation/tests/hostmeta/test_parsers.py | Python | bsd-3-clause | 14,602 | 0.001233 | import json
from unittest.mock import patch
from federation.hostmeta.parsers import (
parse_nodeinfo_document, parse_nodeinfo2_document, parse_statisticsjson_document, int_or_none,
parse_mastodon_document, parse_matrix_document)
from federation.tests.fixtures.hostmeta import (
NODEINFO2_10_DOC, NODEINFO_10... | test_calls_nodeinfo_fetcher_if_pleroma(self, mock_fetch):
parse_mastodon_document(json.loads(PLEROMA_MASTODON_API_DO | C), 'example.com')
mock_fetch.assert_called_once_with('example.com')
@patch('federation.hostmeta.parsers.fetch_document')
def test_parse_mastodon_document(self, mock_fetch):
mock_fetch.return_value = MASTODON_ACTIVITY_DOC, 200, None
result = parse_mastodon_document(json.loads(MASTODON_D... |
fmpr/texttk | texttk/texttk.py | Python | gpl-3.0 | 10,887 | 0.028067 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re, os
import unicodedata
import codecs
import HTMLParser
import nltk
import csv
from nltk.corpus import stopwords
from nltk.tokenize.punkt import PunktSentenceTokenizer
from nltk.stem.snowball import SnowballStemmer
from nltk.stem import WordNetLemmatizer
from nlt... | r.nbest(bigram_measures.pmi, n) # doctest: +NORMALIZE_WHITESPACE
elif metric.lower() == "chi_sq":
best_bigrams = finder.nbest(bigram_measures.chi_sq, n) # doctest: +NORMALIZE_WHITESPACE
else:
raise Exception("Unknown metric for bigram finder")
return best_bigrams
def remove_punctuation(self, text):
if... | pattern)
tokens = self.simplerTokenizer(text)
return ' '.join(tokens)
def tag_corpus_ner(self, corpus):
if not hasattr(self, 'stanford_ner'):
self.stanford_ner = StanfordNERTagger(self.stanford_ner_path+"classifiers/english.all.3class.distsim.crf.ser.gz",
self.stanford_ner_path+"stanford-ner.jar"... |
churchlab/vdj | bin/imgt2fasta.py | Python | apache-2.0 | 1,206 | 0.004975 | #! /usr/bin/env python
# Copyright 2014 Uri Laserson
#
# 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 ... | se.OptionParser()
(options, args) = parser.parse_args()
if len(args) == 2:
inhandle = open(args[0],'r')
outhandle = open(args[1],'w')
elif len(args) == 1:
inhandle = open(args[0],'r')
outhandle = sys.stdout
elif len(args) == 0:
inhandle = sys.stdin
outhandle = sys.stdout
else:
raise Excepti... |
google/feedloader | appengine/initiator/main.py | Python | apache-2.0 | 8,653 | 0.006703 | # coding=utf-8
# Copyright 2021 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 agreed ... | ION_DELETE = 'delete'
OPERATION_EXPIRING = 'expiring'
OPERATIONS = (OPERATION_UPSERT, OPERATION_DELETE, OPERATION_EXPIRING)
_TARGET_URL_INSERT = '/insert_items'
_TARGET_URL_DELETE = '/delete_i | tems'
_TARGET_URL_PREVENT_EXPIRING = '/prevent_expiring_items'
logging_client = cloud_logging.Client()
logging_client.setup_logging(log_level=logging.DEBUG)
app = flask.Flask(__name__)
@app.route('/start', methods=['POST'])
def start() -> Tuple[str, http.HTTPStatus]:
"""Pushes tasks to Cloud Tasks when receiving ... |
onnodb/CloudBackups | trello/__init__.py | Python | unlicense | 43 | 0.023256 |
VERSION = "0.1"
| from trello.api | import *
|
DrSkippy/php_books_database | tools/bookdbtool/visualizations.py | Python | bsd-2-clause | 1,064 | 0.007519 | import logging
import pandas as pd
import matplotlib.pyplot as plt
def running_total_comparison(df1, window=15):
fig_size = [12,12]
xlim = [0,365]
ylim = [0,max(df1.Pages)]
years = df1.Year.unique()[-window:].tolist()
y = years.pop(0)
_df = df1.loc[df1.Year == y]
| ax = _df.plot("Day", "Pages", figsize=fig_size, xlim=xlim, ylim=ylim, label=y)
for y in years:
_df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Pages", figsize=fig_size, xlim=xlim, ylim=ylim, ax=ax, label=y)
def yearly_comparisons(df, cu | rrent_year=2020):
now = df.loc[df.Year == current_year]
fig_size = [12, 6]
ax = df.hist("Pages Read", bins=14, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Pages Read"]), color="red")
plt.show()
df.plot.bar(x="Rank", y="Pages Read", width=.95, color="darkblue", figsize=fig_size)
... |
movitto/snap | test/filemanagertest.py | Python | gpl-3.0 | 4,521 | 0.002212 | #!/usr/bin/python
#
# test/filemanagertest.py unit test suite for snap.filemanager
#
# (C) Copyright 2011 Mo Morsi (mo@morsi.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 3,
# as published by the Free Software Foundation
#
#... | RCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import os
import unittest
from snap.filemanager import FileManager
class FileManagerTest(unittest.TestCase):
def testRmAndExists(self):
temp_file_path = os.path.join(os.path.dirname(__file__), "data... | )
self.assertTrue(os.path.exists(temp_file_path))
self.assertTrue(os.path.isfile(temp_file_path))
self.assertTrue(FileManager.exists(temp_file_path))
FileManager.rm(temp_file_path)
self.assertFalse(os.path.exists(temp_file_path))
self.assertFalse(FileManager.exists(temp_... |
jerkos/mzOS | mzos/exp_design.py | Python | mit | 3,317 | 0.00211 | from __future__ import absolute_import
from collections import defaultdict as ddict
import os.path as op
def enum(**enums):
"""#enumeration
#backward compatible
:param enums:
"""
return type('Enum', (), enums)
IONISATION_MODE = enum(NEG=-1, POS=1)
class ExperimentalSettings(object):
"""
... | :param ionisation_mode:
:param is_dims_experiment:
"""
ADDUCTS_POS = op.abspath("mzos/ressources/POS_ADDUCTS_IMS.csv")
ADDUCTS_NEG = | op.abspath("mzos/ressources/NEG_ADDUCTS_IMS.csv")
FRAGMENTS = op.abspath("mzos/ressources/FRAGMENTS_IMS.csv")
def __init__(self, mz_tol_ppm, polarity, is_dims_exp,
frag_conf=None,
neg_adducts_conf=None,
pos_adducts_conf=None):
self.samples = set()
... |
OpusVL/odoo | addons/board/__openerp__.py | Python | agpl-3.0 | 1,697 | 0.002357 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you ca... | 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 Publ | ic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Dashboards',
'version': '1.0',
... |
mganeva/mantid | scripts/test/Muon/utilities/thread_model_test.py | Python | gpl-3.0 | 5,303 | 0.001509 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
import unittest
from mantid.py3compat import... | adData = mock.Mock()
self.thread.loadData([1, 2, 3, 4, 5])
self.assertEqual(self.model.loadData.call_count, 1)
self.assertEqual(self.model.loadData.call_args_list[0][0][0], [1, 2, 3, 4, 5])
def test_that_execute_is_called_in_model_when_thread_is_started(self):
self.model.execute =... |
self.thread._thread.wait()
self.Runner.QT_APP.processEvents()
self.assertEqual(self.model.execute.call_count, 1)
def test_that_output_is_called_if_thread_executes_successfully(self):
self.model.execute = mock.Mock()
self.model.output = mock.Mock()
self.Runner(self... |
JustJokerX/PaperCrawler | COLT/COLT2015.py | Python | gpl-3.0 | 1,083 | 0 | # coding=utf-8
"""
This file is used to make a crawl
"""
import __init__
import os
import re
import urllib
from utility import prgbar
def get_html(url):
"""Get the html """
page = urllib.urlopen(url)
html = page.read()
return html
def get_pdf(html):
""" xxx"""
reg = r'href="(.+?\.pdf)">pdf'... | if os.path.exists(filename) is True:
pbar.log('Exist')
else:
urllib.urlretrieve(
'http://jmlr.org/proceedings/papers/v40/' + pdfurl, filename)
pbar.update(index=(idx + 1))
pbar.finish()
if __name__ == '__main__':
HTML = get_html("http://jmlr.org/p... | t_pdf(HTML))
|
Gaia3D/QGIS | python/plugins/processing/core/ProcessingConfig.py | Python | gpl-2.0 | 8,398 | 0.001072 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ProcessingConfig.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | Log panel'), True))
ProcessingConfig.addSetting(Setting(
ProcessingConfig.tr('General'),
ProcessingConfig.KEEP_DIALOG_OPEN,
ProcessingConfig.tr('Keep dialog open after running an algorithm'), False))
ProcessingConfig.addSetting(Setting(
ProcessingConfig.tr... | Setting(Setting(
ProcessingConfig.tr('General'),
ProcessingConfig.USE_FILENAME_AS_LAYER_NAME,
ProcessingConfig.tr('Use filename as layer name'), False))
ProcessingConfig.addSetting(Setting(
ProcessingConfig.tr('General'),
ProcessingConfig.SHOW_RECENT_A... |
agusmakmun/Some-Examples-of-Simple-Python-Script | regex/remove-all-characters.py | Python | agpl-3.0 | 413 | 0.007264 | import re
import string
def replaceIt(file):
| out = ''
with open(file, 'r') as f:
for line in f:
repl = '[' + re.escape(''.join(string.punctuation)) + ']'
out += re.sub(repl, '', line)
return out
print (replaceIt('test.txt'))
# output
'''
cobaanu231339 91102
12120 | 86mcmnad0ca
'''
# test.txt
'''
coba*())@*&#anu;,231339 91102-$@!%!
''..,121208***&@6mcmnad0ca
'''
|
ivknv/yadisk | tests/__init__.py | Python | lgpl-3.0 | 74 | 0 | #!/usr/bin/env python
# -*- cod | ing: utf-8 -*-
from | .yadisk_test import *
|
cedadev/django-sizefield | setup.py | Python | lgpl-3.0 | 1,205 | 0.00249 | #!/usr/bin/python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-sizefield',
version='0.10.ceda',
author='Mathieu Leplatre',
author_email='contact@mathie | u-leplatre.info',
url='https://github.com/leplatrem/django-sizefield',
download_url="http://pypi.python.org/pypi/django-sizefield/",
description="A model field to store a file size, whose edition and display shows units.",
long_description=open(os.path.join(here, 'README.rst')).read() + '\n\n' +
... | (here, 'CHANGES')).read(),
license='LPGL, see LICENSE file.',
install_requires=[
'Django',
],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=['Topic :: Utilities',
'Natural Language :: English',
'Operating System ::... |
partofthething/home-assistant | homeassistant/components/ipp/config_flow.py | Python | apache-2.0 | 7,235 | 0.001382 | """Config flow to configure the IPP integration."""
import logging
from typing import Any, Dict, Optional
from pyipp import (
IPP,
IPPConnectionError,
IPPConnectionUpgradeRequired,
IPPError,
IPPParseError,
IPPResponseError,
IPPVersionNotSupportedError,
)
import voluptuous as vol
from homea... | lf._abort_if_unique_id_configured(
updates={
CONF_HOST: self.discovery_info[CONF_HOST],
CONF_NAME: self.discovery_info[CONF_NAME],
},
)
await self._async_handle_discovery_without_unique_id()
return await self.async_step... | f_confirm(
self, user_input: ConfigType = None
) -> Dict[str, Any]:
"""Handle a confirmation flow initiated by zeroconf."""
if user_input is None:
return self.async_show_form(
step_id="zeroconf_confirm",
description_placeholders={"name": self.disco... |
mwhoffman/reggie | tests/test_core_priors.py | Python | bsd-2-clause | 1,591 | 0.001257 | """
Tests for priors.
"""
# pylint: disable=missing-docstring
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import numpy.testing as nt
import scipy.optimize as spop
import reggie.core.priors as priors
### BASE TEST CLASS ###########... | ##################
class TestUniform(PriorTest):
def __init__(self):
PriorTest.__init__(self, priors.Uniform([0, 0], [1, 1]))
class TestNormal(PriorTest):
def __init__(self):
PriorTest.__init__(self, priors.Normal([0, 0 | ], [1, 1]))
class TestLogNormal(PriorTest):
def __init__(self):
PriorTest.__init__(self, priors.LogNormal([0, 0], [1, 1]))
def test_uniform():
nt.assert_raises(ValueError, priors.Uniform, 0, -1)
|
ratt-ru/PyMORESANE | tests/test_iuwt_convolution.py | Python | gpl-2.0 | 107 | 0.009346 | import pymoresane.iuwt_convolution
import | unittes | t
class TestIuwtConvolution(unittest.TestCase):
pass |
andrescollazos/sistemas-distribuidos | Taller3/cliente.py | Python | gpl-3.0 | 739 | 0.004071 | # coding=u | tf-8
#Se importa el módulo ServerProxy de xmlrpclib.
from xmlrpclib import ServerProxy
#Se conecta al equipo por el puerto 5005
s = ServerProxy('http://localhost:5005')
#Se llama a la función pasandole x y devuelve el doble de x
salir = False
while not salir:
num1 = input("Digite un numero: ")
num2 = input("Di... | La respuesta es: ", s.operacion(num1, num2, op1)
except OverflowError:
print "\nLos numeros ingresados son muy grandes! Exceden capacidad!"
salir = raw_input("\n\nDesea continuar? (Y/N): ")
if salir == "N" or salir == "n":
salir = True
else:
salir = False
|
dbarbier/privot | python/test/t_coupling_tools.py | Python | lgpl-3.0 | 21,167 | 0.005055 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from openturns import coupling_tools
import os
import time
import sys
wanted_lines = '# ooo\nE=@E\nE1=@E\nFE1=@F#oo\nZ=@Z@Z\n# ooo\n'
semi_parsed = '# ooo\nE=2\nE1=2\nFE1=@F#oo\nZ=@Z@Z\n# ooo\n'
parsed = '# ooo\nE=1.6\nE1=1.6\nFE1=5#oo\nZ=66\n# ooo\n'
# how many Mo for ... | value != result: raise Exception("! got " + str(result) + ' instead of ' +
str(value))
value = 16
result = coupling_tools.get_line_col(result_file, 1, 5)
if value != result: raise Exception("! got " + str(result) + ' inst | ead of ' +
str(value))
value = 9
result = coupling_tools.get_line_col(result_file, skip_col=-1)
if value != result: raise Exception("! got " + str(result) + ' instead of ' +
str(value))
value = 17
result = coupling_tools... |
FutureSharks/invokust | invokust/settings.py | Python | mit | 3,137 | 0.000319 | # -*- coding: utf-8 -*-
import os
from locust.main import load_locustfile
def create_settings(
from_environment=False,
locustfile=None,
classes=None,
host=None,
num_users=None,
spawn_rate=None,
reset_stats=False,
run_time="3m",
loglevel="INFO",
):
"""
Returns a settings o... | from_environment is set to True then this function will attempt to set
the attributes from environment variables. The environment variables are
named LOCUST_ + attribute name in upper case.
"""
settings | = type("", (), {})()
settings.from_environment = from_environment
settings.locustfile = locustfile
# parameters needed to create the locust Environment object
settings.classes = classes
settings.host = host
settings.tags = None
settings.exclude_tags = None
settings.reset_stats = reset_... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatterternary/marker/line/_coloraxis.py | Python | mit | 581 | 0 | import _plotly_utils.basevalidators
class ColoraxisValidator(_plotly_utils.basevalidators.SubplotidValidator):
def __init__(
self,
plotly_name="coloraxis",
parent_name="scatterternary.marker.line",
**kwargs
):
super(C | oloraxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
dflt=kwargs.pop("dflt", None),
edit_type=kwargs.pop("edit_type", "calc"),
regex=kwargs.pop("regex", "/^coloraxis([2-9]|[1-9][0-9]+)?$/" | ),
**kwargs
)
|
texta-tk/texta | account/urls.py | Python | gpl-3.0 | 1,734 | 0.006344 | from django.conf.urls import url
from . import views
from django.contrib.auth.views import PasswordResetConfirmView, PasswordResetView, PasswordResetDoneView, PasswordResetCompleteView
urlpatterns = [
url(r'^$', views.index,name="home"),
url(r'update_dataset$', vie | ws.update_dataset, name='update_dataset'),
url(r'update_model$', views.update_model, name='update_model'),
url(r'^confirm/(?P<email_auth_token>([a-z]|[0-9]){14})/$', views.confirm_email, name='confirm_email'),
url(r'create$', views.create, name="create"),
url(r'login$', views.login, name="login"),
u... | ange_pwd"),
url(r'change_password$', views.change_password, name="change_password"),
url(r'get_auth_token$', views.get_auth_token, name="get_auth_token"),
url(r'revoke_auth_token$', views.revoke_auth_token, name="revoke_auth_token"),
url(r'password_reset$', PasswordResetView.as_view(template_name='passw... |
chromakey/django-salesforce | salesforce/backend/driver.py | Python | mit | 6,090 | 0.001806 | """
Dummy Salesforce driver that simulates some parts of DB API 2
https://www.python.org/dev/peps/pep-0249/
should be independent on Django.db
and if possible should be independent on django.conf.settings
Code at lower level than DB API should be also here.
"""
from collections import namedtuple
import requests
import... | ounter
# All error types described in DB API 2 are implemented the same way as in
# | Django 1.6, otherwise some exceptions are not correctly reported in it.
class Error(Exception if PY3 else StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class Integr... |
invisiblek/python-for-android | python3-alpha/python3-src/Lib/test/test_string.py | Python | apache-2.0 | 5,578 | 0.00251 | import unittest, string
from test import support
class ModuleTest(unittest.TestCase):
def test_attrs(self):
string.whitespace
string.ascii_lowercase
string.ascii_uppercase
string.ascii_letters
string.digits
string.hexdigits
string.octdigits
string.p... | , 'Abc-def Def-ghi Ghi')
self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def')
self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
def test_formatter(self):
fmt = string.Formatter()
sel... | ertEqual(fmt.format("foo{0}", "bar"), "foobar")
self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
# override get_value ############################################
class NamespaceFormatter(string.Format... |
softak/webfaction_demo | vendor-local/lib/python/selenium/webdriver/remote/errorhandler.py | Python | bsd-3-clause | 6,176 | 0.001619 | # Copyright 2010 WebDriver committers
# 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 ap... | Y KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation | s under the License.
from selenium.common.exceptions import ElementNotSelectableException
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import InvalidCookieDomainException
from selenium.common.exceptions import InvalidElementStateException
from selenium.common.except... |
typesupply/defconAppKit | Lib/defconAppKit/controls/openTypeControlsView.py | Python | mit | 12,083 | 0.002731 | from AppKit import NSScroller, NSColor, NSAttributedString, NSMenuItem, NSShadowAttributeName, NSShadow, \
NSForegroundColorAttributeName, NSFont, NSFontAttributeName, NSSmallControlSize, NSView
import vanilla
class OpenTypeControlsView(vanilla.ScrollView):
def __init__(self, posSize, callback):
self... | font is None:
languageList = []
else:
languageList = ["Default"] + font.getLanguageList()
unsupportedLanguages = [i for i in languageTags if i not in languageList]
if unsupportedLanguages:
languageList.append(NSMenuItem.separatorItem())
languageLis... |
# teardown existing controls
for attr in self._gsubAttributes:
delattr(self._controlGroup, attr)
for attr in self._gposAttributes:
delattr(self._controlGroup, attr)
for attr in self._featureNames:
delattr(self._controlGroup, attr)
if hasattr(s... |
paninetworks/neutron | neutron/tests/unit/plugins/ml2/test_extension_driver_api.py | Python | apache-2.0 | 10,552 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | port']['id'], data)
val = res['port'].get('port_extension')
self.assertEqual('Test_Port_Extension_Update_update', val)
def test_extend_network_dict(self):
with mock.patch.object(ext_test.TestExtensionDriver,
'process_update_network') as ext_update_net,... | twork() as network:
net_id = network['network']['id']
net_data = {'network': {'id': net_id}}
self._plugin.update_network(self._ctxt, net_id, net_data)
self.assertTrue(ext_update_net.called)
self.assertTrue(ext_net_dict.called)
def test_extend_subnet_dict(... |
vivek8943/twitter-streamer | streamer/scripts/lps.py | Python | mit | 351 | 0 | #!/usr/bin/python
"""Print stats about | stdin per-line timings."""
import | signal
import sys
import time
start = time.time()
count = 0
try:
for line in sys.stdin:
count += 1
except KeyboardInterrupt:
print
pass
end = time.time()
et = end - start
lps = count / et
print "Elapsed time = %f, lines = %d, lps = %f" % (et, count, lps)
|
swtp1v07/Savu | savu/plugins/manchester_recon.py | Python | apache-2.0 | 7,508 | 0.000666 | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | .xml" % sino_start
fh = open(xml_filename, 'w')
dom.writexml(open(xml_filename, 'w'))
fh.close()
# actually call the program
log_location = '/dls/tmp/tomopy/dt64/%i${USER}test.out' % (sino_start)
| command = \
(". /etc/profile.d/modules.sh;" +
" module load i12;" +
" export CUDA_CACHE_DISABLE=1;" +
" echo BEFORE;" +
" dt64n %s &> %s;" % (xml_filename, log_location) +
" echo AFTER")
logging.debug("COMMAND CALLED'" + comman... |
CWolfRU/freedoom | lumps/colormap/colormap.py | Python | bsd-3-clause | 6,534 | 0.02112 | #!/usr/bin/env python
# Copyright (C) 2001 Colin Phipps <cphipps@doomworld.com>
# Copyright (C) 2008, 2013 Simon Howard
# Parts copyright (C) 1999 by id Software (http://www.idsoftware.com/)
#
# SPDX-License-Identifier: GPL-2.0+
#
# Takes PLAYPAL as input (filename is the only parameter)
# Produces a light graduated CO... | s(colors1, colors2, factor=0.5):
"""Blend the two given lists of colors, with 'factor' controlling
the mix between the two. factor=0 is exactly colors1, while
factor=1 is exactly colors2. Returns a list of blended colors."""
result = []
for index, c1 in enumerate(colors1):
c2 = colors | 2[index]
result.append((
c2[0] * factor + c1[0] * (1 - factor),
c2[1] * factor + c1[1] * (1 - factor),
c2[2] * factor + c1[2] * (1 - factor),
))
return result
def invert_colors(colors):
"""Given a list of colors, translate them to inverted monochrome."""
result = []
for color in colors:
average =... |
altendky/canmatrix | examples/encodeFrame.py | Python | bsd-2-clause | 2,030 | 0.003941 | #!/usr/bin/env python3
import canmatrix.formats
import sys
import optparse
# command line options...
usage = """
%prog [options] matrix
matrixX can be any of *.dbc|*.dbf|*.kcd|*.arxml
"""
parser = optparse.OptionParser(usage=usage)
parser.add_option(
"-f", "--frames",
dest="frames",
help="encode list o... | alue
a = input("Enter Value for Multiplexer " + multiplexer_signal.name + " ")
signalDict = dict()
signalDict[multiplex | er_signal.name] = int(a)
# read signals for the given multiplexer value
for signal in frame.get_signals_for_multiplexer_value(int(a)):
signalDict[signal.name] = read_signal_value_from_user(signal)
else:
# not multiplexed frame
signalDict = dict()
# go through al... |
domain51/d51.django.apps.sharing | d51/django/apps/sharing/views.py | Python | gpl-3.0 | 1,793 | 0.007808 | from d51.django.auth.decorators import auth_required
from django.contrib.sites.models import Site
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import ImproperlyConfigured
from .services import... | lidForm:
service = load_service(service_name, url)
input = [] if request.method != 'POST' else [request.POST]
form = service.get_form_class()(*input)
templates, context = [
'sharing/%s/prompt.html'%service_name,
'sharing/prompt.html'
... | 'service_name':service_name,
'form': form,
'url':url_to_share,
'SHARE_KEY':SHARE_KEY,
'next':request.GET.get('next','/')
}
response = render_to_response(templates, context, context_instance=RequestContext(request))
ex... |
sthirugn/robottelo | robottelo/ui/products.py | Python | gpl-3.0 | 2,755 | 0 | """Implements Products UI"""
from robottelo.ui.base import Base
from robottelo.ui.locators import common_locators, locators, tab_locators
from robottelo.ui.navigator import Navigator
class Products(Base):
"""Manipulates Products from UI"""
is_katello = True
def navigate_to_entity(self):
"""Navig... | rd.desc_update'], new_name)
self.click(common_locators['save'])
if new_gpg_key:
self.click(locators['prd.gpg_key_edit'])
self.select(locators['prd.gpg_key_update'], new_gpg_key)
self.click(common_locators['save'])
if new_sync_plan:
self.click(l... | self.select(locators['prd.sync_plan_update'], new_sync_plan)
self.click(common_locators['save'])
def delete(self, name, really=True):
"""Delete a product from UI"""
self.delete_entity(
name,
really,
locators['prd.remove'],
)
|
bewestphal/SeleniumAI | example/configuration.py | Python | mit | 6,202 | 0.003386 | import os
import keras.backend as K
import numpy as np
from keras.layers import Dense, Activation, Flatten, Convolution2D, Permute
from keras.layers.convolutional import Conv2D
from keras.models import Sequential
from models import AbstractConfiguration, KickoffModes
from rl.memory import SequentialMemory
from rl.poli... | w_width)
model = Sequential()
if K.image_dim_ordering() == 'tf': # Tensorflow
| # (width, height, channels)
model.add(Permute((2, 3, 1), input_shape=input_shape))
elif K.image_dim_ordering() == 'th': # Theano
# (channels, width, height)
model.add(Permute((1, 2, 3), input_shape=input_shape))
else:
raise RuntimeError('Unknown ima... |
pombredanne/bokeh | tests/plugins/phantomjs_screenshot.py | Python | bsd-3-clause | 889 | 0.004499 | import json
import pytest
import subprocess
import sys
from os.path import join, dirname
from .utils import info, fail
def pytest_addoption(parser):
parser.addoption(
"--phantomjs", type=str, default="phantomjs", help="phantomjs executable"
)
def get_phantomjs_screenshot(url, screen | shot_path, wait, width=1000, height=1000):
"""
wait is in milliseconds
"""
phantomjs = pytest.config.getoption('phantomjs')
cmd = [phantomjs, join(dirname(__file__), "phantomjs_screenshot.js"), url, screenshot_path, str(wait), str(width), str(height)]
info("Running command: %s" % " ".join(cmd))... | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.wait()
except OSError:
fail("Failed to run: %s" % " ".join(cmd))
sys.exit(1)
return json.loads(proc.stdout.read().decode("utf-8"))
|
AdrianGaudebert/socorro-crashstats | vendor-local/lib/python/pyasn1/codec/ber/encoder.py | Python | mpl-2.0 | 12,392 | 0.004438 | # BER encoder
from pyasn1.type import base, tag, univ, char, useful
from pyasn1.codec.ber import eoo
from pyasn1.compat.octets import int2oct, ints2octs, null, str2octs
from pyasn1 import error
class Error(Exception): pass
class AbstractItemEncoder:
supportIndefLenMode = 1
def encodeTag(self, t, isConstructed... | else:
substrate = null
while length:
substrate = int2oct(length&0xff) + substrate
length = length >> 8
substrateLen = len(substrate)
| if substrateLen > 126:
raise Error('Length octets overflow (%d)' % substrateLen)
return int2oct(0x80 | substrateLen) + substrate
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
raise Error('Not implemented')
def _encodeEndOfOctets(self, encodeFun, defMode)... |
GetSomeBlocks/Score_Soccer | resources/lib/tvdb_api/tvdb_api.py | Python | mit | 29,127 | 0.006111 | #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvdb_api
#repository:http://github.com/dbr/tvdb_api
#license:Creative Commons GNU GPL v2
# (http://creativecommons.org/licenses/GPL/2.0/)
"""Simple-to-use Python interface to The TVDB's API (www.thetvdb.com)
Example usage:
>>> from tvdb_api import Tvdb
>... | custom_ui = None,
language = None,
search_all_languages = False,
apikey = None,
forceCon | nect=False):
"""interactive (True/False):
When True, uses built-in console UI is used to select the correct show.
When False, the |
lindseypack/NIM | code/ap/apInv.py | Python | mit | 5,106 | 0.009009 | #!usr/bin/env python
from pysnmp.entity.rfc3413.oneliner import cmdgen
import shlex
import subprocess
import re
import os
import sys
import smtplib
from devices.models import AP as AccessPoint
## This file is used to update the access point inventory data. Use the
## updateAccessPoints function to run the update. The ... |
stdoutLines = stdoutLines[:-1] #removes last empty row
#parse stdout into list
names = []
for line in stdoutLines:
names.append(line.split("=")[1])
return names
## Send an email report on access point status.
def sendEmail(messageBody, subject, APs, email):
for ap in APs:
mes... | ip + "\t" + ap.name + "\n"
toHeaderBuild = []
for to in email["to"]:
toHeaderBuild.append("<" + to + ">")
msg = "From: <" + email["from"] + "> \nTo: " + ', '.join(toHeaderBuild) + " \nSubject: " + subject + " \n" + messageBody
s = smtplib.SMTP(email["server"])
s.sendmail(email["from"], email... |
lukaszb/django-richtemplates | example_project/urls.py | Python | bsd-3-clause | 705 | 0.002837 | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
url | patterns = patterns('',
(r'^accounts/', include('registration.urls')),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^admin/', include(admin.site.urls)),
url(r'^users/(?P<username>\w+)/$',
view='examples.views.userprofile',
name='richtemplates_examples_userprofile'),
url(r'^... | de('examples.urls')),
)
|
rosmo/ansible | lib/ansible/modules/storage/netapp/na_elementsw_backup.py | Python | gpl-3.0 | 9,175 | 0.003379 | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
Element Software Backup Manager
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | st_volume_id=dict(required=True, type='str'),
format=dict(required=False, choices=['native', 'uncompressed'], default='native'),
script=dict(required=False, type='str'),
script_parameters=dict(required=False, type='dict')
))
self.module = | AnsibleModule(
argument_spec=self.argument_spec,
required_together=[['script', 'script_parameters']],
supports_check_mode=True
)
if HAS_SF_SDK is False:
self.module.fail_json(msg="Unable to import the SolidFire Python SDK")
# If destination clust... |
elhoyos/colombiatransparente | transparencia/models.py | Python | gpl-3.0 | 2,979 | 0.004028 | from django.db import models
from django.db.models.signals import post_save
from dj | ango.contrib.auth.models import User
from sorl import thumbnail
class PerfilColumnista(models.Model):
user = models.OneToOneField(User, primary_key=True)
bio = models.TextField(blank=True, nul | l=True)
image = thumbnail.ImageField(upload_to='img/columnistas', blank=True, null=True)
def crear_perfil_columnista(sender, instance, created, **kwargs):
if created:
perfil = PerfilColumnista()
perfil.user = instance
perfil.save()
post_save.connect(crear_perfil_columnista, sender=User... |
hfp/tensorflow-xsmm | tensorflow/python/kernel_tests/list_ops_test.py | Python | apache-2.0 | 51,102 | 0.009236 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ax_num_elemen | ts):
self._testPushPop(max_num_elements)
@parameterized.named_parameters(("NoMaxNumElements", None),
("WithMaxNumElements", 2))
def testPushPopGPU(self, max_num_elements):
if not context.num_gpus():
return
with context.device("gpu:0"):
self._testPushPop(max... |
varunagrawal/ClassNotes | notes/views.py | Python | mit | 4,070 | 0.009337 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import onenote
import bitbucket
# sample repo_uuid = 3d316876-a913-4b20-b183-d57e919f96dc
BASE_URL = "https://afternoon-waters-2404.herokuapp.com"
# DEV_URL = "https://classnotes-varunagrawal.c9.io"
# Create your views h... | page_links_md, repo_uuid)
# return HttpResponse(str(pages))
return render(request, 'pages.html', context)
# return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def page(request):
repo_uuid = None
if 'repo_uuid' in request.COOKIES:
repo_uuid = request.COOKIES['repo_uu... | te.get_page_content(request.GET["id"], repo_uuid)
# context = { 'page': page }
# return render(request, 'page.html', context)
return HttpResponse(str(page))
|
lucaskanashiro/debile | debile/slave/runners/pep8.py | Python | mit | 1,811 | 0 | # Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Leo Cavaille <leo@cavaille.net>
#
# 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, inc... | .slave.wrappers.pep8 import parse_pep8
from debile.slave.utils import cd
from debile.utils.commands import run_command
def pep8(dsc, analysis):
run_command(["dpkg-source", "-x", dsc, "source-pep8"])
with cd('source-pep8'):
out, _, ret = run_command(['pep8', '.'])
failed = ret != 0
for... | = run_command(['pep8', '--version'])
if ret != 0:
raise Exception("pep8 is not installed")
return ('pep8', out.strip())
|
wiki-ai/revscoring | revscoring/scoring/models/gradient_boosting.py | Python | mit | 462 | 0 | """
A collection of Gradient Boosting type classifier models.
.. autoclass:: revscoring.scoring.models.GradientBoosting
:members:
:member-order:
"""
import logging
from sk | learn.ensemble import GradientBoostingClassifier
from .sklearn import ProbabilityClassifier
logger = logging.getLogger(__name__)
class GradientBoosting(ProbabilityClassifier):
"""
Implements a Gradient Boosting mo | del.
"""
Estimator = GradientBoostingClassifier
|
jnayak1/cs3240-s16-team16 | login/admin.py | Python | mit | 331 | 0.003021 | from django.contr | ib import admin
from login.models import Category, Page
from login.models import UserProfile
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('name',)}
admin.site.register(Category, CategoryAdmin)
admin.site.register(Page)
admin.site.register(UserProfile)
# Register your models here | .
|
justusc/Elemental | python/optimization/util.py | Python | bsd-3-clause | 18,829 | 0.038239 | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
from El.core import *
# Coherence
# =========
lib.ElCoh... | SOCDots_d.argtypes = \
[c_void_p,c_void_p,c_void_p,c_void_p,c_void_p]
lib.ElSOCDotsDist_s.argtypes = \
lib.ElSOCDotsDist_d.argtypes = \
lib.ElSOCDotsDistMultiVec_s.argtypes = \
lib.ElSOCDotsDistMultiVec_d. | argtypes = \
[c_void_p,c_void_p,c_void_p,c_void_p,c_void_p,c_int]
def SOCDots(x,y,orders,firstInds,cutoff=1000):
# TODO: Sanity checking
if type(x) is Matrix:
z = Matrix(x.tag)
args = [x.obj,y.obj,z.obj,orders.obj,firstInds.obj]
if x.tag == sTag: lib.ElSOCDots_s(*args)
elif x.tag == dTag: lib.E... |
davidwilson-85/easymap | graphic_output/Pillow-4.2.1/Tests/test_image_tobytes.py | Python | gpl-3.0 | 247 | 0.004049 | from helper import unittest, PillowTestCase, hopper
class TestImageToBytes(PillowTe | stCase):
def test_sanity(self):
data = hopper().tobytes()
self.assertIsInstance(data, bytes)
if __name__ == '__main__':
| unittest.main()
|
clouserw/olympia | apps/amo/tests/test_helpers.py | Python | bsd-3-clause | 15,825 | 0 | # -*- coding: utf-8 -*-
import mimetypes
import os
from datetime import datetime, timedelta
from urlparse import urljoin
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils import encoding
import jingo
import test_utils
from mock import Mock, patch
from nos... | ) }}', c)
eq_(s, '%s#frag' % url)
# Replacing a fragment.
s = render('{{ base_frag|urlparams(frag) }}', c)
eq_(s, '%s#frag' % url)
# Adding query and fragment.
s = render('{{ base_frag|urlparams(frag, sort=sort) }}', c)
eq_(s, '%s?sort=name#frag' % url)
# Adding query with existing pa... | '%s?sort=name&x=y#frag' % url)
# Replacing a query param.
s = render('{{ base_query|urlparams(frag, x="z") }}', c)
eq_(s, '%s?x=z#frag' % url)
# Params with value of None get dropped.
s = render('{{ base|urlparams(sort=None) }}', c)
eq_(s, url)
# Removing a query
s = render('{{ b... |
GarlandDA/bad-boids | bad_boids/test/test_boids.py | Python | mit | 5,230 | 0.039962 | import yaml
import os
from ..boids import Boids
from nose.tools import assert_equal
import random
import numpy as np
from unittest.mock import patch
import unittest.mock as mock
def test_Boids():
flock = Boids(boid_number=10,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_fly... | as mock_match:
matched = flock.match_speed('')
mock_match.assert_called_with('')
# test that move() works
with mock.patch.object(flock,'move') as mock_move:
moved = flock.move('')
mock_move.assert_called_with('')
def test_animate():
flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100... | osition_min=0,x_position_max=200,y_position_min=-5,y_position_max=5,
x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20)
# test that animate() is called correctly
with mock.patch.object(flock,'animate') as mock_animate:
animated = flock.animate('frame')
mock_animate.assert_called_with(... |
owalch/oliver | linux/config/scripts/ipblock.py | Python | bsd-2-clause | 870 | 0.006897 | #!/usr/bin/env python
import sys
def ip2str(ip):
l = [
(ip >> (3*8)) | & 0xFF,
(ip >> (2*8)) & 0xFF,
(ip >> (1*8)) & 0xFF,
(ip >> (0*8)) & 0xFF,
]
return '.'.join([str(i) for i in l])
def str2ip(line):
a, b, c, d = [int(s) for s in line.split('.')]
ip = 0
ip += (a << (3*8))
ip += (b << (2*8))
ip += (c << (1*8))
ip += (d << (0*8)... | xcept:
print 'Ignored line:', line,
continue
while (blockip & (~hostmask)) != (ip & (~hostmask)):
hostmask = (hostmask << 1) | 1
bitcount += 1
print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask)
print 'wrong way around'
|
washbz250/LearnPythonTheHardWay | Python3/Tkinter/main.py | Python | unlicense | 173 | 0.011561 | # Im | port the tkinter library
from tkinter import *
# Making a window object
root = Tk()
# Need to have window onscreen until you need to get rid of it.
root.mainlo | op()
|
erramuzpe/seattle-perceptual-learning | perclearn/scripts/fashion_mnist_cnn.py | Python | apache-2.0 | 2,248 | 0 | '''Trains a simple convnet on the Fashion MNIST dataset.
Gets to % test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
'''
from __future__ import print_function
import keras
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Dr... | m_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activatio... | le(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y... |
rnirmal/savanna | savanna/tests/integration/test_config/test_cluster_config.py | Python | apache-2.0 | 6,861 | 0 | # Copyright (c) 2013 Mirantis 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 or agreed to in writ... | t = self.get_object_id(
'node_group_template', sel | f.post_object(self.url_ngt,
master_ngt_body, 202))
worker_ngt_body = self.make_node_group_template(
'worker-ngt', 'qa probe', 'TT+DN')
_add_config(worker_ngt_body, param.DATANODE_CONFIG)
_add_config(worker_ngt_b... |
BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/contrib/contenttypes/migrations/0002_remove_content_type_name.py | Python | mit | 1,168 | 0.000856 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def add_legacy_name(apps, schema_editor):
ContentType = apps.get_model('contenttypes', 'ContentType')
for ct in Conte | ntType.object | s.all():
try:
ct.name = apps.get_model(ct.app_label, ct.model)._meta.object_name
except LookupError:
ct.name = ct.model
ct.save()
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
mig... |
johnmgregoire/JCAPdatavis | echem_paperplots.py | Python | bsd-3-clause | 3,052 | 0.020315 |
import time, copy
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scipy import optimize
from echem_plate_ui import *
from echem_plate_math import *
import pickle
p1='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9_FeCoNiT... | :]
v1up=d1['Ewe(V)'][segd1up['inds']][4:]+vshift
i1dn=d1['I(A)'][segd1dn['inds']]
v1dn=d1['Ewe(V)'][segd1dn['inds']]+vshift
i1up*=imult
i1dn*=imult
lin1up*=imult
segd2up, segd2dn=d2['segprops_dlist']
i2up=d2['I(A)'][segd2up['inds']][4:]
lin2up=i2up-d2['I(A)_LinSub'][segd2up['inds']][4:]
v2up=d2['Ewe(V)'][segd2up['ind... | ]+vshift
i2dn=d2['I(A)'][segd2dn['inds']]
v2dn=d2['Ewe(V)'][segd2dn['inds']]+vshift
i2up*=imult
i2dn*=imult
lin2up*=imult
ica=dill['I(A)_SG'][cai0:cai1]*imult
icadiff=dill['Idiff_time'][cai0:cai1]*imult
tca=dill['t(s)'][cai0:cai1]
tca_cycs=dill['till_cycs']
cycinds=numpy.where((tca_cycs>=tca.min())&(tca_cycs<=tca.max(... |
geraldarthur/PrismJr | twitter.py | Python | mit | 5,815 | 0.003955 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from csv import DictReader, DictWriter
from datetime import datetime
from os import environ
from sys import argv
from time import sleep
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
# (command, argument, input, output) = argv[1:]
# ... | via identifier."""
# Request token
oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)
r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secre... | raw_input('Please input the verifier: ')
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier)
# Finally, Obtain the Access Token
r = requests.post(url=ACCESS_TOKEN_URL,... |
haginara/csvkit | csvkit/utilities/csvlook.py | Python | mit | 2,305 | 0.004338 | #!/usr/bin/env python
import itertools
import six
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility
from csvkit.headers import make_default_headers
class CSVLook(CSVKitUtility):
description = 'Render a CSV file in the console as a fixed-width table.'
def add_arguments(self)... | def main(self):
rows = CSVKitReader(self.input_file, **self.reader_kwargs)
# Make a default header row if none exists
if self.args.no_header_row:
row = next(rows)
column_names = make_default_headers(len(row))
# Put the row back on top
| rows = itertools.chain([row], rows)
else:
column_names = next(rows)
column_names = list(column_names)
# prepend 'line_number' column with line numbers if --linenumbers option
if self.args.line_numbers:
column_names.insert(0, 'line_number')
... |
veskopos/VMWare | api/requests_api.py | Python | gpl-2.0 | 1,010 | 0.036634 | import requests
import yaml
class RequestsApi:
def __init__(self):
'init'
self.config = yaml.load(open("config/request_settings.yml", "r"))
def get_objects(self, sector):
'request to get objects'
objects_points = []
url = self.config['host'] + self.config['object_path'] % sector
response = requests.get... | = self.config['host'] + self.config['root_path'] % sector
response = requests.get(url)
if not response. | status_code == 200 : return []
for line in response.text.splitlines():
roots.append(int(line))
return roots
def send_trajectory(self, sector, paths):
'requets to send trajectory'
url = self.config['host'] + self.config['trajectory_path'] % sector
requests.post(url, params = {'trajectory' : paths})
|
telminov/sw-django-utils | djutils/forms.py | Python | mit | 604 | 0 | # coding: utf-8
def transform_form_error(form, verb | ose=True):
"""
transform form errors to list like
["field1: error1", "field2: error2"]
"""
errors = []
for field, err_msg in form.errors.items():
if field == '__all__': # general errors
errors.append(', '.join(err_msg))
else: # field errors
... | eld_name = form.fields[field].label or field
errors.append('%s: %s' % (field_name, ', '.join(err_msg)))
return errors
|
3dfxsoftware/cbss-addons | account_voucher_move_id/__openerp__.py | Python | gpl-2.0 | 1,448 | 0.002762 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public ... | 'account_voucher'],
'data': [
"account_voucher.xml",
],
'auto_install': False,
'installable': True,
}
| |
woolfson-group/isambard | unit_tests/random_isambard_objects.py | Python | mit | 2,186 | 0.005489 | import random
import numpy
import isambard
def random_angles(n=1, min_val=0, max_val=180, radians=False):
angles = [(random.random() * random.choice(range(abs(max_val - min_val)))) + min_val for _ in range(n)]
if radians:
angles = [numpy.rad2deg(x) for x in angles]
return angles
def random_vect... | max_val=180)
orientations = [random.choice([-1, 1]) for _ in range(n)]
# minor_repeat can't be set to zero - must be set to None.
minor_repeats = random_floats(n=n, min_val=0, max_val=100)
zero_indices = [i for i, x in enumerate(minor_repea | ts) if x == 0.0]
for i in zero_indices:
minor_repeats[i] = None
minor_helix_types = [random.choice(['alpha', 'pi', 'PPII', 'collagen']) for _ in range(n)]
major_handedness = [random.choice(['l', 'r']) for _ in range(n)]
hhs = [isambard.ampal.specifications.polymer_specs.helix.HelicalHelix(aa=aas... |
snakeleon/YouCompleteMe-x64 | python/ycm/youcompleteme.py | Python | gpl-3.0 | 31,916 | 0.027259 | # Copyright (C) 2011-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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 opt... | HANDLE_FLAG_INHERIT,
0 )
self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
handler = logging.FileHandler( self._client_logfile )
# On Windows an | d Python prior to 3.4, file handles are inherited by child
# processes started with at least one replaced standard stream, which is the
# case when we start the ycmd server (we are redirecting all standard
# outputs into a pipe). These files cannot be removed while the child
# processes are still up. Th... |
openstack/doc8 | src/doc8/__main__.py | Python | apache-2.0 | 641 | 0 | # Copyright (C) 2019 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Lice | nse"); 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
# WA... | KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
from doc8 import main
sys.exit(main.main())
|
CamFlawless/python_projects | crm/src/podio_2.py | Python | mit | 18,252 | 0.01808 |
# Build out a means of storing this data into a DB and preserving it for archival and analysis
client_id = "crmdatagettest"
client_secret = "I88RXVb9y1Am0AXauUSdOr8Pux9zAwNHDRSLX0UKmI6SbtTI0u4inxGa8i6cwVqi"
username = "camjcollins@gmail.com"
password = "Padthai123*"
from pypodio2 import api
import pygsheets
impor... | if any(word in str(record) for word in search_str):
# print(record)
for entry in record:
# print(entry)
# print(field[2])
# quit()
if entry['field_id'] == field[2] and entry['type'] == "app":
# print(entr... | ''' what do we want to do if the field we are on is the field we are searching for?
** we would want to extract the corresponding value from the object '''
if entry['type'] == "date": # what to grab when we see a date
print(entry['values'][0]['sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.