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 |
|---|---|---|---|---|---|---|---|---|
shannpersand/cooper-type | workshops/Python Workshop/Just/2016-06-21 Cooper workshop day 2/14 circle function.py | Python | cc0-1.0 | 416 | 0.004808 | def circle(cx, cy, diameter):
radius = diameter / 2
oval(cx - radius, | cy - radius, diameter, diameter)
# diameter = 254
# radius = diameter / 2
# cx, cy = (420, 532)
# oval(cx - radius, cy - radius, diameter, diameter)
circle(420, 532, 254)
# diameter = 154
# rad | ius = diameter / 2
# cx, cy = (728, 414)
# oval(cx - radius, cy - radius, diameter, diameter)
circle(728, 414, 154)
circle(510, 258, 306)
|
levlaz/braindump | app/model/base.py | Python | mit | 304 | 0 | from datetime import datetime
from app import db
class Base(db.Model):
__abstract | __ = True
id = db.Column(db.Integer, primary_key=True)
created_date = db.Column(db.DateTime, index=True, default=datetime.utcnow)
updated_date = db.Column(db.DateTime | , index=True, default=datetime.utcnow)
|
certsocietegenerale/FIR | fir_artifacts_enrichment/tasks.py | Python | gpl-3.0 | 832 | 0.001202 | from abuse_finder import domain_abuse, ip_abuse, email_abuse, url_abuse
from fir_artifacts.models import Artifact
from fir_celery.celeryconf import celery_app
ENRICHMENT_FUNCTIONS = {
'hostname': domain_abuse,
'ip': ip_abuse,
'email': email_abuse,
'url': url_abuse
}
@celery_app.task
def enrich_arti... | _id)
print("Enrichment for {}".format(artifact.value))
if artifact.type in ENRICHMENT_FUNCTIONS:
results = ENRICHMENT_FUNCTIONS[artifact.type](artifact.value)
enrichment = ArtifactEnrichment(
artifact=artifact,
name='\n'.join(results['names']),
email='; '.join(results['abus... | ts['raw']
)
enrichment.save()
from fir_artifacts_enrichment.models import ArtifactEnrichment
|
ktsstudio/tornkts | tornkts/mixins/validate_mixin.py | Python | mit | 578 | 0.00173 | from mongoengine import ValidationError
from tornkts.base.server_response import ServerError
class ValidateMixin(object):
def validate_model(self, prefix=None):
if prefix is not None:
p | refix += '.'
else:
prefix = ''
try:
self.valida | te()
except ValidationError as e:
field = e.errors.keys().pop()
raise ServerError(ServerError.INVALID_PARAMETER,
field=prefix + str(field),
field_problem=ServerError.FIELD_INVALID_FORMAT) |
theopencorps/theopencorps | theopencorps/endpoints/github.py | Python | agpl-3.0 | 8,932 | 0.003583 | """
Lightweight wrapper around the GitHub API for use in GAE
"""
__copyright__ = """
Copyright (C) 2016 Potential Ventures Ltd
This file is part of theopencorps
<https://github.com/theopencorps/theopencorps/>
"""
__license__ = """
This program is free software: you can redistribute it and/or modify
it under the terms... | (str) path to file
content (str) file contents
message (str) commit message
"""
# Find the SHA1 of the existing f | ile, if it exists
response = self.request("/repos/%s/%s/contents/%s" % (user, repo, path),
payload=json.dumps({
"path" : path,
"ref" : branch}))
if response.status_code == 404:
... |
reinout/django | tests/migrations/test_optimizer.py | Python | bsd-3-clause | 24,806 | 0.002177 | from django.db import migrations, models
from django.db.migrations import operations
from django.db.migrations.optimizer import MigrationOptimizer
from django.test import SimpleTestCase
from .models import EmptyManager, UnicodeModel
class OptimizerTests(SimpleTestCase):
"""
Tests the migration autodetector.
... | ptimizer.optimize | (operations, app_label), optimizer._iterations
def assertOptimizesTo(self, operations, expected, exact=None, less_than=None, app_label=None):
result, iterations = self.optimize(operations, app_label)
result = [repr(f.deconstruct()) for f in result]
expected = [repr(f.deconstruct()) for f in... |
ken0-1n/mutation_util | tests/test_mutation_filter.py | Python | gpl-3.0 | 9,110 | 0.014709 | #! /usr/bin/env python
import sys
import unittest
import os, tempfile, shutil, filecmp
import subprocess
from mutation_util import mutation_filter as mf
from mutation_util import genomon_header_info
class TestMutationFilter(unittest.TestCase):
######################################
# Tumor/Normal Pair, Annof... | t_answer_test3_1.txt"
self.assertTrue(filecmp.cmp(output, answer_file, shallow=False))
def test3_2(self):
cur_dir = os.path.dirname(os.path.abspath(__file__))
| "--fish_pval 1.0 --realign_pval 1.0 --eb_pval 4.0 --tcount 4 --ncount 2"
ghi = genomon_header_info.Genomon_header_info()
input = cur_dir + "/../data/5929_small_realignment_result_test3.2.txt"
output = cur_dir + "/../data/5929_small_result_test3_2.txt"
ebpval = 4.0
fishpval = 1... |
melkamar/gitbot | tests/test_fetch_issues.py | Python | mit | 569 | 0 | from gitbot import github_issues_bot
fetch_issues_ur | l = 'https://api.github.com/repos/{}/issues?sta | te={}'
repository = "melkamar/mi-pyt-test-issues"
def test_fetch_issues(auth_session):
"""
Test if number of issues obtained directly from GitHub API (as JSON)
is equal to the number of parsed Issue objects.
:param auth_session:
:return:
"""
response = auth_session.get(fetch_issues_url.for... |
meirwah/st2contrib | packs/softlayer/actions/create_instance.py | Python | apache-2.0 | 1,208 | 0.000828 | from lib.softlayer import SoftlayerBaseAction
class SoftlayerCreateInstance(SoftlayerBaseAction):
def run(self, | name, datacenter, os="DEBIAN_LATEST", domain="example.com", cpus=1, ram=2048,
disk=100, bandwidth=10, local_disk=True, keyname=None):
driver = self._get_driver()
# build the params list to pass to create_node with the proper kwargs
create_params = {"name": name, "ex_datacenter": data... | self.st2_to_libcloud['domain']: domain,
self.st2_to_libcloud['cpus']: cpus,
self.st2_to_libcloud['disk']: disk,
self.st2_to_libcloud['ram']: ram,
self.st2_to_libcloud['bandwidth']: bandwidth,
... |
facebook/fbthrift | thrift/lib/py/protocol/exceptions.py | Python | apache-2.0 | 1,433 | 0.000698 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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... | def __init__(self, encoding, object, start, end, reason, field_name):
super(ThriftUnicodeDec | odeError, self).__init__(
encoding, object, start, end, reason
)
self.field_names = [field_name]
def __str__(self):
return "{error} when decoding field '{field}'".format(
error=super(ThriftUnicodeDecodeError, self).__str__(),
field="->".join(reversed(self... |
ybenitezf/nstock | controllers/org.py | Python | mit | 4,822 | 0 | # -*- coding: utf-8 -*-
if False:
from gluon import current, URL, SQLFORM, redirect
from gluon import IS_NOT_EMPTY, Field, IS_EMAIL
from gluon import IS_NOT_IN_DB
request = current.request
response = current.response
session = current.session
cache = current.cache
T = current.T
from ... | e list of desks in this org
"""
org = db.organization(request.args(0))
session.org_id = org.id
return locals()
@auth.requires(auth.has_permission('update', db.organization, request.args(0)))
def edit():
org = db.organization(request.args(0))
tbl = db.organization
tbl.users.readable = False... | ires = [IS_NOT_EMPTY()]
# edit form
form = SQLFORM(db.organization, record=org, showid=False)
if form.process().accepted:
redirect(URL('view', args=[org.id]))
return locals()
@auth.requires(auth.has_permission('update', db.organization, request.args(0)))
def members():
org = db.organizat... |
marcellarius/webargscontrib.utils | webargscontrib/utils/validate.py | Python | mit | 2,307 | 0.0013 | __author__ = 'sam'
import webargs
from .string import lowercase, strip
def not_null(value):
"""A validation function that checks that a value isn't None."""
return True if value is not None else False
def not_empty(value):
"""
Check if a value is not empty.
This is a simple check that blocks n... | if value in valid_choices:
return True
else:
raise webargs.ValidationError(
"Invalid value %s. | Valid choices are %s" %
(repr(value), repr(valid_choices)))
return validate_choices
def within(min=None, max=None):
"""
Create a validation function to check whether an argument value is within
a specified range (inclusive).
`min` and `max` cannot both be None.
:param min: A ... |
hueyyeng/AssetsBrowser | ui/window/ui_applications_list.py | Python | mit | 7,328 | 0.003412 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\applications_list.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_AppListDialog(obj... | ayout.addWidget(self.btnDialogBox)
self.tableAppList.raise_()
self.btnDialogBox.raise_()
self.label.raise_()
self.retranslateUi(AppListDialog)
self.btnDialogBox.accepte | d.connect(AppListDialog.accept)
self.btnDialogBox.rejected.connect(AppListDialog.reject)
QtCore.QMetaObject.connectSlotsByName(AppListDialog)
def retranslateUi(self, AppListDialog):
_translate = QtCore.QCoreApplication.translate
AppListDialog.setWindowTitle(_translate("AppListDialog... |
hetica/webeni | main/forms.py | Python | lgpl-3.0 | 531 | 0.039623 | # -*- coding: utf-8 -*-
from django import forms
class StagiaireForms(for | ms.Form):
_choix = ( (1, 'Stagiaire'), (2, 'Classe'),)
choisir = forms.ChoiceField(choices =_choix, widget = forms.RadioSelect, required = True, initial = '1', label = '')
chercher = forms.CharField(max_length=100, required=False, label = '')
def __init__(self, *args, **kwargs):
super(StagiaireForms, self).__ini... | sse'})
|
pdyban/dicombrowser | dicomviewer/streamview.py | Python | apache-2.0 | 1,408 | 0.002131 | from .iview import IView
from .iview import IViewModel
from .model import Model
class StreamView(IView):
def __init__(self, stream):
super(StreamView, self).__init__()
self.stream = stream
self.separator = '\t'
def update(self):
if self.viewmodel is None:
raise At... | rs = ['Filename'] + [tag for tag in self.model.select_tags]
self.items.append(headers)
# for each file
for fname in self.model.items:
line = [fname] + [self.model.items[fname][tag] for tag in self | .model.select_tags]
self.items.append(line)
|
squeaky-pl/pystacia | doc/source/image/desaturate.py | Python | mit | 216 | 0 | from os.path import dirname, join
from pystacia import lena
dest = join(dirname(__file__), ' | ../_static/generated')
image = lena(256)
image.desaturate()
image.write(join(dest, 'lena_desa | turate.jpg'))
image.close()
|
xombiemp/CouchPotatoServer | couchpotato/core/downloaders/nzbget.py | Python | gpl-3.0 | 12,455 | 0.005781 | from base64 import standard_b64encode
from datetime import timedelta
import re
import shutil
import socket
import traceback
import xmlrpclib
from couchpotato.core._base.downloader.main import DownloaderBase, ReleaseDownloadList
from couchpotato.core.helpers.encoding import ss, sp
from couchpotato.core.helpers.variable... | if nzb['NZBID'] in ids:
log.debug('Found %s in NZBGet postprocessing queue', nzb['NZBFilename'])
release_downloads.append({
'id': nzb['NZB | ID'],
'name': nzb['NZBFilename'],
'original_status': nzb['Stage'],
'timeleft': str(timedelta(seconds = 0)) if not status['PostPaused'] else -1,
})
for nzb in history:
try:
nzb_id = [param['Value'] for param ... |
vvoland/py3status | py3status/modules/kdeconnector.py | Python | bsd-3-clause | 7,909 | 0.000253 | # -*- coding: utf-8 -*-
"""
Display information about your smartphone with KDEConnector.
Configuration parameters:
cache_timeout: how often we refresh this module in seconds (default 30)
device: the device name, you need this if you have more than one device
connected to your PC (default None)
devi... | = u'⬇'
status_chr = u'⬆'
status | _full = u'☻'
status_no_notif = ''
status_notif = u' ✉'
def post_config_hook(self):
self._dev = None
def _init_dbus(self):
"""
Get the device id
"""
_bus = SessionBus()
if self.device_id is None:
self.device_id = self._get_device_id(_bus)
... |
tonyseek/simple-rbac | rbac/acl.py | Python | mit | 5,469 | 0 | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... | r role in self._roles
assert not resource or resource in self._resources
roles = set(get_family(self._roles, role))
operations = {None, operation}
resources = set(get_family(self._resources, resource))
def DefaultAssertion(*args, **kwargs):
return True
is_a... | resources):
if permission in self._denied:
assertion = self._denied[permission] or default_assertion
if assertion(self, role, operation, resource,
**assertion_kwargs):
return False # denied by rule immediately
if ... |
leemac/JellyfishRss | rss/settings/development.py | Python | mit | 947 | 0.00528 | from rss.settings.base import *
DEBUG = True
ALLOWED_HOSTS = [
]
DATABASES = {
'default': {
| 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'jellyfish', # leafreader path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'postgres',
... | kets or '127.0.0.1' for localhost through TCP.
'PORT': '5432', # Set to empty string for default.
}
}
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = 'http://local... |
yu-peng/english-pddl-translator | getElement.py | Python | mit | 11,844 | 0.01773 | '''
Created on Dec 7, 2012
@author: yupeng
'''
class ActionGroup:
def __init__(self):
self.Actions = []
self.PPs = []
self.NPs = []
def addAction(self,actionString):
self.Actions.append(actionString)
def addActions(self,actionList):
self.Acti... | PPs: '
for PP in self.PPs:
AGString = AGString + PP.getString() + '; '
return AGString
def getActionString(self):
ActionString = ''
for action in self.Actions:
ActionString = ActionString + action
retu... |
PPString = PPString + '-' + PP.getOriginalString()
return PPString[1:]
def getTargetString(self):
TargetString = ''
for NP in self.NPs:
TargetString = TargetString + '-' + NP.getNounString()
return TargetString[1:]
... |
idlesign/makeapp | makeapp/app_templates/pytestplugin/makeappconf.py | Python | bsd-3-clause | 145 | 0 | from makeapp.appconfig import Config
class PytestPluginConfig(Conf | ig):
parent_template | = ['pytest']
makeapp_config = PytestPluginConfig
|
Vitiate/ShellScripts | ElastAlert/elastalert_modules/servicenow_alert.py | Python | gpl-2.0 | 1,758 | 0.008532 | from alerts import Alerter, BasicMatchString
import requests
import json
class ServiceNowAlerter(Alerter):
required_options = set(['username', 'password', 'servicenow_rest_url', 'short_description', 'comments', 'assignment_group', 'category', 'subcategory', 'cmdb_ci', 'caller_id'])
# Alert is called
def a... | # Parse everything into description.
description = str(BasicMatchString(self.rule, match))
# Set proper headers
headers = {
"Content-Type":"application/json",
"Accept":"application/json;charset=utf-8"
}
data = {
"description": de... | self.rule['assignment_group'],
"category": self.rule['category'],
"subcategory": self.rule['subcategory'],
"cmdb_ci": self.rule['cmdb_ci'],
"caller_id": self.rule["caller_id"]
}
response = requests.post(self.rule['servicenow_rest_url'], auth=(self.rule[... |
tjm-1990/blueking | blueking/component/apis/job.py | Python | gpl-3.0 | 1,608 | 0.004717 | # -*- coding: utf-8 -*-
from ..base import ComponentAPI
class CollectionsJOB(object):
"""Collections of JOB APIS"""
def __init__(self, client):
self.client = client
self.execute_task = ComponentAPI(
client=self.client, method='POST', path='/api/c/compapi/job/execute_task/',
... | ='/api/c/compapi/job/get_agent_sta | tus/',
description=u'查询Agent状态',
)
self.get_task_detail = ComponentAPI(
client=self.client, method='GET', path='/api/c/compapi/job/get_task_detail/',
description=u'查询作业模板详情',
)
self.get_task_ip_log = ComponentAPI(
client=self.client, method... |
uyaly/test | utils/location.py | Python | gpl-2.0 | 1,635 | 0.005758 | # coding:utf-8
import csv,xlrd
from selenium import webdriver
import time
file_name = r'D:\PycharmProjects\test_hpk2017\data\testdata.xlsx'
def getCsv(file_name):
rows=[]
with open(file_name, 'rb') as f:
readers = csv.reader(f, delimiter=',', quotechar='|')
next(readers, None)
for row ... | ue:表格的列
:param file_name:excel文件
:return:
'''
book = xlrd.open_workbook(file_name)
sheet = book.sheet_by_index(0)
return sheet.cell_value(rowValue, colValue)
def getDdExcel(File_name):
rows = []
book = xlrd.open_workbook(File_name)
sheet = book.sheet_by_index(0)
for row in range... | es(row, 0, sheet.ncols)))
return rows
def getData(rowValue, colname):
'''
:param File_name: excel文件
:param rowValue: 表格的行
:param element: 表格的列
:return:
'''
book = xlrd.open_workbook(file_name)
sheet = book.sheet_by_index(0)
for colValue in range(0, sheet.ncols):
if s... |
SwissTPH/odk_planner | docs/_static/get_gonts.py | Python | gpl-2.0 | 408 | 0.007353 |
import sys, re
x = re.compile(r"^(?P<before>.*local\('(?P<name>.*?)'\), url\()(?P<u | rl>.*?)(?P<after>\).*)$")
css = ''
sh = ''
for line in sys.stdin.readlines():
m = x.match(line)
if m:
gd = m.groupdict()
css += gd['before'] + gd['name'] + '.woff' + gd['after']
sh += 'wget -O %s.woff %s' % (gd['name'], gd['url']) + '\n'
else:
css += line
|
print(css)
print(sh)
|
romanlv/trml2pdf | trml2pdf.py | Python | lgpl-2.1 | 672 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# trml2pdf - An RML to PDF converter
# Copyright (C) 2003, Fabien Pinckaers, UCL, FSA
# Contributors
# Richard Waid <richard@iopen.net>
# Klaas Freitag <freitag@kde.org>
import os
import sys
import trml2pdf
__help = \
"Usage: tr | ml2pdf input.rml >output.pdf\n\
Render the standard input (RML) and output a PDF file"
def main():
if len(sys.argv) == 1 or sys.argv[1] == '--help':
print(__help)
sys.exit(0)
else:
| # print(parseString(open(sys.argv[1], 'r').read()))
os.write(1, trml2pdf.parseString(open(sys.argv[1], 'rt').read()))
if __name__ == "__main__":
main()
|
kytos/kytos | tests/unit/test_core/test_switch.py | Python | mit | 12,374 | 0 | """Test kytos.core.switch module."""
import asyncio
import json
from datetime import datetime
from unittest import TestCase
from unittest.mock import MagicMock, Mock, patch
from kytos.core import Controller
from kytos.core.config import KytosConfig
from kytos.core.constants import FLOOD_TIMEOUT
from kytos.core.interfa... | sc'
desc.hw_desc.value = 'hw_desc'
desc.sw_desc.value = 'sw_desc'
desc.serial_num.value = 'serial_num'
desc.dp_desc.value = 'dp_desc'
self.switch.update_description(desc)
self.assertEqual(self.switch.description['manufacturer'], 'mfr_desc')
self.assertEqual(self... | ['software'], 'sw_desc')
self.assertEqual(self.switch.description['serial'], 'serial_num')
self.assertEqual(self.switch.description['data_path'], 'dp_desc')
def test_disable(self):
"""Test disable method."""
interface = MagicMock()
self.switch.interfaces = {"1": interface}
... |
TalLinzen/russian-preps | code/python/yandex_capped.py | Python | bsd-3-clause | 2,238 | 0.002241 | # -*- coding: utf-8 -*-
# Author: Tal Linzen <linzen@nyu.edu>
# License: BSD (3-clause)
# Linzen, Kasyanenko, & Gouskova (2013). (Lexical and phonological
# variation in Russian prepositions, Phonology 30(3).)
import re
import random
import time
import sys
import urllib
import urllib2
from gzip import GzipFile
fro... | This is the code used in 2013 paper; it no longer works as of January 2014,
due to some changes in HTML documents generated by the search engine,
though it looks like it would require only minimal adjustments to work.
Usage example:
>>> y = YandexCapped()
>>> y.run('ответов')
'''
results_p... | def __init__(self, delay=0, just_count=True):
self.item_number_re = re.compile(
'<b class="b-serp-item__number">(\d+)</b>')
self.no_results = 'Sorry, there are no results for this search query.'
self.delay = delay
self.just_count = just_count
def run(self, que... |
slashdd/sos | sos/cleaner/archives/generic.py | Python | gpl-2.0 | 1,463 | 0 | # Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General ... | return os.path.isdir(arc_path)
def set_archive_root(self):
return os.path.abspath(self.archive_path)
class TarballArchive(SoSObfuscationArchive):
"""A generic tar archive that is not associated with any known or supported
collection utility
"""
type_name = 'tarball'
description = '... | tarfile(arc_path)
except Exception:
return False
def set_archive_root(self):
if self.tarobj.firstmember.isdir():
return self.tarobj.firstmember.name
return ''
|
jvrana/Pillowtalk | tests/test_with_larger_examples/test_sequence_example/test_examples.py | Python | mit | 5,684 | 0.010204 | import pytest
from pillowtalk import *
# TODO: test when where returns [] or None or [None]
# TODO: test update() (or autoupdate?)
@pytest.fixture
def folder_json():
return {'count' : 59,
'created_at' ... | AL1-AVNY'},
{'id': 'seq_VazadBJw', 'name': 'pGPT4-pGAL1-GAVNY'}, {'id': 'seq_Qc6f2Kii', 'name': 'pMOD4G-NLS_dCas9_VP64'},
{'id': 'seq_SGfG2YeB', 'name': 'pMODU6-pGALZ4-HygMX'} | , {'id': 'seq_i0Yl6uzk', 'name': 'pMODH8-pGPD-TIR1_DM'},
{'id': 'seq_ri07UntS', 'name': 'pMODU6-pGPD-EYFP'}, {'id': 'seq_F4tEc0XU', 'name': 'pMODU6-pGALZ4-STE5(-)RING'},
{'id': 'seq_qihkmlW4', 'name': 'pMODU6-pGAL1-AlphaFactor'},
{'id': 'seq_2MFFshfl', 'name': 'pYMOD2Kmx_pGAL1-HYG_ZEV4-cassette'},
{... |
lonetwin/botosh | botosh/aws_admin.py | Python | bsd-2-clause | 3,229 | 0.004336 | #!/usr/bin/python
import os
import sys
import cmd
import boto
from utils import info, error, prompt
from utils import green
_context_cache = {}
class AWSAdmin(object, cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.context = None
@property
def _ready(self):
return os.e... | to not configured') if not self._ready
else self.context or error('context not set'))
)
def do_set_context(self, context):
""" Set/Switc | h to a different context """
from botosh import available_contexts
available_contexts_str = green(', '.join(available_contexts.keys()))
if not self._ready:
print error("boto has not been configured with sufficient credentials. "
"Please configure boto first")... |
trunglq7/horizon | openstack_dashboard/dashboards/admin/users/views.py | Python | apache-2.0 | 4,417 | 0.00317 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | _("Unable to retrieve user roles."),
| redirect=redirect)
roles.sort(key=operator.attrgetter("id"))
kwargs['roles'] = roles
return kwargs
def get_initial(self):
default_role = api.keystone.get_default_role(self.request)
return {'role_id': getattr(default_role, "id", None)}
|
MichalKononenko/python-qinfer | src/qinfer/ipy.py | Python | agpl-3.0 | 3,141 | 0.004459 | #!/usr/bin/python
# -*- coding: utf-8 -*-
##
# ipy.py: Interaction with IPython and Jupyter.
##
# © 2016 Chris Ferrie (csferrie@gmail.com) and
# Christopher E. Granade (cgranade@gmail.com)
#
# This file is a part of the Qinfer project.
# Licensed under the AGPL version 3.
##
# This program is free software:... | absolute_import
from __future__ import division
## EXPORTS ###################################################################
__all__ = ['IPythonProgressBar']
## IMPORTS ################################################################ | ####
try:
from IPython.display import display
import ipywidgets as ipw
except:
display = None
ipw = None
## CLASSES ###################################################################
class IPythonProgressBar(object):
"""
Represents a progress bar as an IPython widget. If the widget
is cl... |
diego0020/PySurfer | surfer/_commandline.py | Python | bsd-3-clause | 3,496 | 0 | """
This module defines the command-line interface for PySurfer.
It is defined here instead of in either the top level or
intermediate start-up scripts, as it is used in both.
There should be no reason to import this module in an
interpreter session.
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatte... | osed through methods on th | e `brain'
variable that will exist in IPython namespace when the program finishes
loading. Please see the PySurfer documentation for more information
about how to interact with the Brain object.
"""
parser = ArgumentParser(prog='pysurfer',
usage='%(prog)s subject_id hemisphere surface '
... |
SublimeHaskell/SublimeHaskell | fly_check.py | Python | mit | 7,654 | 0.003266 | import threading
import time
import sublime
import sublime_plugin
import SublimeHaskell.autocomplete as Autocomplete
import SublimeHaskell.event_common as EventCommon
import SublimeHaskell.internals.backend_mgr as BackendManager
import SublimeHaskell.internals.settings as Settings
import SublimeHaskell.internals.util... | a_t = {0}'.format(delta_t))
if delta_t <= 0:
done_inspect = threading.Event()
done_inspect.clear()
Utils.run_async('fly-inspect' | , self.do_inspect, done_inspect)
# Timeout shouldn't be needed... but paranoia is a good thing.
done_inspect.wait(WAIT_TIMEOUT)
delta_t = None
self.inspect_flag.clear()
def fly_check(self):
tmo_event = threading.Event()
tm... |
erikr/weerapi | weerapi/config.py | Python | mit | 157 | 0 | MEMCACHE_KEY = 'weerapi-cache'
MEMCACHE_EXPIRY = 120
MEMCACHE_SERVERS = ['127.0.0.1:11211']
URL = 'http://m.knmi.nl/inde | x.php?i=Actueel&s=tabel_10min_da | ta'
|
wavefront-mike/python-client | wavefront_client/api_client.py | Python | apache-2.0 | 20,266 | 0.000444 | # coding: utf-8
"""
Copyright 2016 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable l... |
try:
# for python3
from urllib.parse import quote
except ImportError:
# for python2
| from urllib import quote
from .configuration import Configuration
class ApiClient(object):
"""
Generic API client for Swagger client library builds.
Swagger generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the method... |
nitin-cherian/Webapps | TalkPython/P4E/my_web_app/my_web_app/static_cache.py | Python | mit | 1,889 | 0.000529 | """
Use this cache utility to compute the hash of files server as static resources
on your website. As written, it must be in your '/' home folder, but you can
adjust the computation of *fullname* to allow you to put it in subfolders.
Set recompute_caches_every_request based on use case / deployment:
recompute_ca... | oin(
__full_path, relative_file_url.lstrip('/')))
if not os.path.exists(fullname):
return "ERROR_MISSING_FILE"
digest_value = __get_file_hash(fullname)
__hash_lookup[key] = digest_value
__trace("Computed digest for {} -> {}".format(key, __hash_lookup[key]))
return digest_value
d... | .update(data)
return md5.hexdigest()
def __trace(text):
# This is really for just seeing things in action.
# You might want real logging...
if not enable_tracing:
return
print(text)
|
Antiun/odoo | openerp/fields.py | Python | agpl-3.0 | 75,603 | 0.001958 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-2014 OpenERP (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... |
slots.update(attrs.get('_slots', ()))
attrs['__slots__'] = set(slots) - set(base_ | slots)
attrs['_slots'] = slots
return type.__new__(meta, name, bases, attrs)
def __init__(cls, name, bases, attrs):
super(MetaField, cls).__init__(name, bases, attrs)
if cls.type and cls.type not in MetaField.by_type:
MetaField.by_type[cls.type] = cls
# compute ... |
codingforentrepreneurs/ecommerce-2-api | src/ecommerce2/api_tests.py | Python | mit | 3,349 | 0.023589 | import requests
import json
cart_url = 'http://127.0.0.1:8000/api/cart/'
def create_cart():
# create cart
cart_r = requests.get(cart_url)
# get cart token
cart_token = cart_r.json()["token"]
return cart_token
def do_api_test(email=None, user_auth=None):
cart_token = create_cart()
# add items to cart
new_car... | xMzkzJywgJ3VzZXJfY2hlY2tvdXRfaWQnOiAxMSwgJ3N1Y2Nlc3MnOiBUcnVlfQ=="
addresses_r = requests.get(addresses)
addresses_r_data = addresses_r.json()
if addresses_r_data["count"] >= 2:
b_id = addresses_r_data["results"][0]["id"]
s_id = addresses_r_data["results"][1]["id"]
else:
addresses_create = "http://127.... |
data = {
"user": user_id,
"type": "billing",
"street": "12423 Test",
"city": "Newport Beach",
"zipcode": 92304,
}
addresses_create_r = requests.post(addresses_create, data=data)
b_id = addresses_create_r.json().get("id")
data = {
"user": user_id,
"type": "shipping",
"stre... |
simonsfoundation/CaImAn | caiman/utils/stats.py | Python | gpl-2.0 | 9,843 | 0.002845 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 20 13:49:57 2016
@author: agiovann
"""
from builtins import range
from past.utils import old_div
import logging
import numpy as np
import scipy
try:
import numba
except:
pass
from scipy.linalg.lapack import dpotrf, dpotrs
from scipy impor... | a = np.sort(data)
# Find the mode
dataMode = _hsm(data)
return dataMode
#%%
#@numba.jit("void | (f4[:])")
def _hsm(data):
if data.size == 1:
return data[0]
elif data.size == 2:
return data.mean()
elif data.size == 3:
i1 = data[1] - data[0]
i2 = data[2] - data[1]
if i1 < i2:
return data[:2].mean()
elif i2 > i1:
return data[1:].me... |
trupty/aerospike-client-python | examples/client/get_key_digest.py | Python | apache-2.0 | 4,371 | 0.00366 | # -*- coding: utf-8 -*-
################################################################################
# Copyright 2013-2015 Aerospike, 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
... | print()
sys.exit(1)
if len(args) != 1:
optparse | r.print_help()
print()
sys.exit(1)
################################################################################
# Client Configuration
################################################################################
config = {
'hosts': [ (options.host, options.port) ],
'policies': {
'timeo... |
GNS3/gns3-legacy | src/GNS3/Link/PipeCapture.py | Python | gpl-2.0 | 3,431 | 0.004372 | # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8:
#
# Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team).
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
#... | dle(self.pipe)
debug("Wireshark has been closed, deleting pipe ...")
self.exit()
return
else:
time.sleep(0.5) #FIXME: find a better way to wake-up the thread only when there is | data to read
if __name__ == '__main__':
capture_cmd = "C:\Program Files (x86)\Wireshark\wireshark.exe -k -i %p"
pipe = r'\\.\pipe\GNS3\R1_to_R2'
capture_file = "capture.pcap"
path = unicode(capture_cmd.replace("%p", "%s") % pipe)
t = PipeCapture(capture_file, path, pipe)
t.setDaemon(True)
... |
cessor/gameoflife | config.py | Python | mit | 2,820 | 0.013121 | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class Resolutions(object):
resolutions = [
(1920, 1200),
(1920, 1080),
(1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
... | = (0.15, 0.15, 0.13, 1.0)
black = (0.0, 0.0, 0.0, 1.0)
white = (1.0, 1.0, 1.0, 1.0)
red = (1.0, 0.2, 0.0, 1.0)
orange = (1.0, 0.4, 0.0, 1.0)
yellow = (1.0, 0.9, 0.0, 1.0)
light_green = (0.4, 1.0, 0.0, 1.0)
green = (0.0, 1.0, 0.2, 1.0)
... | , 1.0)
@classmethod
def __colors(self):
return [key for key in self.__dict__.keys() if not key.startswith('_') and key != 'named']
@classmethod
def named(self, name):
if not hasattr(self, name):
colors = ', '.join(self.__colors())
raise Exception('Unknown ... |
vasnake/fb2tools | fb2tools/fb2desc.py | Python | gpl-3.0 | 24,174 | 0.0069 | #!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
# (c) Con Radchenko mailto:lankier@gmail.com
#
# $Id: fb2desc.py,v 1.10 2008/09/15 04:18:45 con Exp con $
#
import sys, os
import locale
import getopt
import codecs
import zipfile
from cStringIO import StringIO
import xml.sax
import shutil
import traceback
... | ятой - название"
4 - тоже, но преобразованное в транслит и с заменой пробелов
5 - "первая буква автора в нижнем регистре/авторы, разделенные запятой, в нижнем регистре/авторы, разделенные запятой - название (серия #номер)"
6 - тоже, но преобразованное в транслит и с заменой пробелов
'''
format = op... | t:
if a[0]:
authors.append(a[0])
fa = ' '.join(i for i in a if i)
if fa:
full_authors.append(fa)
authors = ', '.join(authors)
if not authors:
authors = 'unknown'
full_authors = ', '.join(full_authors)
if not full_authors:
full_authors = 'un... |
lotusronin/KronosEngine | editor/mapentity.py | Python | mit | 592 | 0.045608 | #!/usr/bin/python
# File: mapentity.py
# import pygtk
# pygtk.require('2.0')
from gi.repository import Gtk, Gdk
class MapEntity:
# self.x = None
# self.y = None
# self.name = None
# self.texture = None
def getCoords(self):
return self.x,self.y
def getx(self): |
return self.x
def gety(self):
return self.y
def setCoords(self,xcoord,ycoord):
self.x = xcoord
self.y = ycoord
def getName(self):
return self.name
def setName(self, strname):
self.name = strname
def __init__(self, xarg, yarg, namearg):
self.x = xarg
self.y = yarg
self.name = nam | earg
return |
nickburlett/feincms_gallery | gallery/admin.py | Python | bsd-3-clause | 5,892 | 0.004073 | #coding=utf-8
import json
from django import forms
from django.contrib import admin
from django.core.exceptions import FieldError, ObjectDoesNotExist
from django.http import (HttpResponse, HttpResponseRedirect,
HttpResponseBadRequest, HttpResponseForbidden)
from django.shortcuts import render_to_response
from djan... | adRequest(form.errors)
data = form.cleaned_data
obj = data['id']
dimensions = '%sx%s' % (data['width'], data['height'])
if obj.type == 'image':
image = None
try:
image | = feincms_thumbnail.thumbnail(obj.file.name, dimensions)
except:
pass
if image:
content = json.dumps({
'url': image.url,
'name': escapejs(obj.translation.caption)
})
return HttpResponse(content, ... |
joelsmith/openshift-tools | ansible/roles/lib_openshift_3.2/library/oc_pvc.py | Python | apache-2.0 | 39,870 | 0.002558 | #!/usr/bin/env python # pylint: disable=too-many-lines
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
# | |) | (_) ... | cmd(cmd)
def _process(self, template_name, create=False, params=None, template_data=None):
'''return all pods '''
cmd = ['process', '-n', self.namespace]
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
... | arams.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if results['returncode'] != 0 or not create:
return results
fname = '/tmp/%s' % template_name
yed = Yedit(fname, results['... |
eduNEXT/edunext-platform | import_shims/lms/discussion/tests/test_views.py | Python | agpl-3.0 | 404 | 0.009901 | """Deprecated | import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('discussion.tests.test_views', 'lms.djangoapps.discussion.tes | ts.test_views')
from lms.djangoapps.discussion.tests.test_views import *
|
cmusatyalab/opendiamond | opendiamond/scopeserver/gigapan/views.py | Python | epl-1.0 | 4,425 | 0.002486 | #
# The OpenDiamond Platform for Interactive Search
#
# Copyright (c) 2009-2019 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUTION OF T... | e(ids):
def full_url(gigapan):
return 'http://%s:5873%s' % (settings.GIGAPAN_SERVER, gigapan)
gigapans = ["/gigapan/%d" % int(gigap | an_id) for gigapan_id in ids]
proxies = settings.GIGAPAN_PROXIES
blaster = getattr(settings, 'GIGAPAN_BLASTER', None)
if len(proxies) > len(gigapans):
mapping = {} # gigapan -> [proxy]
gigapan_index = 0
for proxy in proxies:
mapping.setdefault(gigapans[gigapan_index], []... |
20tab/upy | upy/contrib/rosetta/views.py | Python | bsd-3-clause | 18,100 | 0.003812 | from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template i... | viron.get('mod_wsgi.script_reloading', '0')):
try:
os.utime(request.environ.get('SCRIPT_FILENAME'), None)
except OSError:
pass
# Try auto-reloading via uwsgi daemon reload mechanis... | ght?
uwsgi.reload()
except:
# we may not be running under uwsgi :P
pass
except:
storage.set('rosetta_i18n_write', False)
storage.set('rosetta_i18n_pofile', ros... |
CroceRossaItaliana/jorvik | social/models.py | Python | gpl-3.0 | 4,591 | 0.001307 | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti im | port ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
Rappresenta un giudizio sociale ad un oggetto generico.
Utilizzare tramite il tratto ConGiudizio ed i suoi metodi.
"""
class Meta:
verbose_name_plural = "Giudizi"
permissions = (
("view_giud... | dizi", on_delete=models.CASCADE)
positivo = models.BooleanField("Positivo", db_index=True, default=True)
oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True)
oggetto_id = models.PositiveIntegerField(db_index=True)
oggetto = GenericForeignKey('oggetto_tipo', ... |
rosscdh/django-paymill-redux | dj_paymill/tests/__init__.py | Python | mit | 590 | 0.011864 | # -*- coding: utf-8 -*-
TRANSLATED_WEBHOOK_DATA = {"stamp": {"serial": "DEV-STAMP"}, "receipt": "2DJ2fkRJQdGhaLwLjIZL9Zpz/84=", "secure": False, "created": "2014-04-26 14:35:43.543350"}
WEBHOOK_POSTED_DATA = {'data': u'W1syODAsMjgxXSxbMjY3LDExMF0sWzkzLDU3XSxbMjAzLDUxXSxbMTAzLDI5MV1d' | }
VALID_VIEW_RESPONSE | = {u'serial': u'DEV-STAMP', u'data': {u'stamp': {}, u'receipt': u'2DJ2fkRJQdGhaLwLjIZL9Zpz/84=', u'secure': False, u'created': u'2014-04-26 14:35:43.543350'}, u'detail': u'Paymill Callback recieved'}
from .test_views import *
from .test_services import *
from .test_signals import * |
ApolloAuto/apollo | modules/tools/record_play/rtk_recorder.py | Python | apache-2.0 | 7,449 | 0.000671 | #!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo 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... | self.chassis.CopyFrom(data)
#self.chassis = data
if math.isnan(self.chassis.speed_mps):
self.logger.warning("find nan speed_mps: %s" % str(self.chassis))
if math.isnan(self.chassis.steering_percentage):
self.logger.warning(
"find na | n steering_percentage: %s" % str(self.chassis))
self.chassis_received = True
def localization_callback(self, data):
"""
New message received
"""
if self.terminating is True:
self.logger.info("terminating when receive localization msg")
return
... |
janusnic/py-21v | lambda/3.py | Python | mit | 90 | 0.011111 | # -*- codin | g:utf-8 -*-
print sorted([[3, 4], [3, 5], [1, 2], [7, 3]], key=lambda x: | x[1]) |
AKSW/QuitStore | quit/core.py | Python | gpl-3.0 | 24,569 | 0.001709 | import pygit2
import logging
from copy import copy
from pygit2 import GIT_MERGE_ANALYSIS_UP_TO_DATE
from pygit2 import GIT_MERGE_ANALYSIS_FASTFORWARD
from pygit2 import GIT_MERGE_ANALYSIS_NORMAL
from pygit2 import GIT_SORT_REVERSE, GIT_RESET_HARD, GIT_STATUS_CURRENT
from rdflib import Graph, ConjunctiveGraph, BNode... | not self.config.hasFeature(Feature.Persistence)
) and (
not self.config.hasFeature(Feature.Provenance)
):
return
g = self.store.store
if self.config.hasFeature(Feature.Provenance):
| role_author_uri = QUIT['Author']
role_committer_uri = QUIT['Committer']
g.add((role_author_uri, is_a, PROV['Role']))
g.add((role_committer_uri, is_a, PROV['Role']))
# Create the commit
i1, commitid = self.instance(commit.id, True)
commit_uri = QUIT['... |
kreuks/liven | nlp/persistor.py | Python | apache-2.0 | 1,267 | 0.001579 | import boto3
import botocore
import tarfile
import os
import shutil
class Persistor(object):
def __init__(self, data_dir, aws_region, bucket_name):
self.data_dir = data_dir
self.s3 = boto3.resource('s3', region_name=aws_region)
self.bucket_name = bucket_name
try:
self.s... | _bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': aws_region})
except botocore.exceptions.ClientError, e:
pass # bucket already exists
self.bucket = self.s3.Bucket(bucket_name)
def send_tar_to_s3(self, target_dir):
if not os.path.isdir(target_dir):
... | asename(target_dir)
base_dir = os.path.dirname(target_dir)
tarname = shutil.make_archive(base_name, 'gztar', root_dir=base_dir, base_dir=base_name)
filekey = os.path.basename(tarname)
self.s3.Object(self.bucket_name, filekey).put(Body=open(tarname, 'rb'))
def fetch_and_extract(self,... |
rockerBOO/aquaticore | aquaticore/references/models.py | Python | mit | 542 | 0.020295 | from django.db import models
from aquati | core.databases.models import Database
from aquaticore.authors.models import Author
class Reference(models.Model):
title = models.CharField(max_length=200)
source = models.CharField(max_length=200)
year = models.IntegerField(4)
author = models.ForeignKey('authors.Author')
database = models.ForeignKey('databases.Da... | published')
modified = models.DateTimeField(auto_now=True, default='0000-00-00 00:00:00')
def __unicode__(self):
return self.title |
CertainlyUncertain/Kinetic-Gunner-Gunner-of-Angst | inputMgr.py | Python | gpl-3.0 | 8,769 | 0.007527 | # ========================== Start Copyright Notice ========================== #
# #
# Copyright 2014 F.D.I.S. #
# This file is part of Kinetic Gunner: Gunner of Angst ... | lf.engine = engine
OIS.KeyListener.__init__(self)
OIS.MouseListener.__init__(self)
OIS.JoyStickListener.__init__(self)
self.move = 1000
self.rotate = 25
self.selectionRadius = 100
self.MB_Left_Down = False
self.MB_Right_Down = False
print "Input Ma... | t(self):
''' Sets the Window and Creates Input System and Objects. '''
windowHandle = 0
renderWindow = self.engine.gfxMgr.root.getAutoCreatedWindow()
windowHandle = renderWindow.getCustomAttributeUnsignedLong("WINDOW")
paramList = [("WINDOW", str(windowHandle))]
if os.na... |
grahamhayes/designate | designate/api/v2/controllers/zones/tasks/exports.py | Python | apache-2.0 | 4,055 | 0 | # Copyright 2015 Rackspace Inc.
#
# Author: Tim Simmons <tim.simmons@rackspae.com>
#
# 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
#
# Unle... | i.find_zone_exports(
context, criterion, marker, limit, sort_key, sort_dir),
request=request)
@pecan.expose(template='json:', content_type='application/json')
@utils.validate_uuid('zone_export_id')
def delete_one(self, zone_export_id):
"""Delete Zone | Export"""
request = pecan.request
response = pecan.response
context = request.environ['context']
self.central_api.delete_zone_export(context, zone_export_id)
response.status_int = 204
return ''
|
oocran/vbbu | monitor.py | Python | agpl-3.0 | 1,235 | 0.006478 | # monitor compute resources. Called from 'lib/oocran/oocran.c' with dependencies already imported and variables defined previously
cpu = 'cpu_' + NVF + ' value=%s' % psutil.cpu_percent()
dis | k = 'disk_' + NVF + ' value=%s' % psutil.disk_usage('/').percent
ram = 'ram_' + NVF + ' value=%s' % round(psutil.virtual_memory().used, 2)
last_up_down = up_down
upload = psutil | .net_io_counters(pernic=True)[interface][0]
download = psutil.net_io_counters(pernic=True)[interface][1]
t1 = time.time()
up_down = (upload, download)
try:
ul, dl = [(now - last) / (t1 - t0) / 1024.0
for now, last in zip(up_down, last_up_down)]
t0 = time.time()
except:
pass
network_in = 'netw... |
bcoca/ansible-modules-extras | cloud/amazon/lambda_facts.py | Python | gpl-3.0 | 13,282 | 0.003012 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | :param client: AWS API client reference (bo | to3)
:param module: Ansible module reference
:return dict:
"""
lambda_facts = dict()
function_name = module.params.get('function_name')
if function_name:
params = dict()
if module.params.get('max_items'):
params['MaxItems'] = module.params.get('max_items')
... |
tailhook/pyzza | examples/pacman/main.py | Python | mit | 5,622 | 0.002134 | from layout import TopLevel, RoundRect, Widget, Layout, State, Rel, Constraint
from string import repr
from flash.display import Shape
from game import Frame, Keys
level = """
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Xg....................................gX
X.XX.XXXXX.XX.XXX.XXXX.XXX.XX.XXXXX.XX.X
X.XX.XXXXX.XX.XXX.XX... | ight*5/8)
g.lineTo(width*3/4, height*3/4)
g.lineTo(width/4, height*3/4)
class Meal( | Shape):
__slots__ = ('fx', 'fy', 'amount')
def __init__(self, x, y, amount=10):
self.fx = x
self.fy = y
self.amount = amount
def draw(self, width, height):
g = self.graphics
g.clear()
g.beginFill(0xFF0000)
g.drawCircle(width/2, height/2, min(width, hei... |
wrboyce/autolat | autolat/mobileme.py | Python | bsd-3-clause | 8,757 | 0.002626 | from datetime import datetime
import re
import time
import urllib
import simplejson as json
from actions import Action
from webservice import WebService
class MobileMe(WebService):
loginform_url = 'https://auth.me.com/authenticate'
loginform_data = {
'service': 'account',
'ssoNamespace': 'pr... | el(k), v)
self.datetime = datetime.strptime('%s %s' % (data['date'], data['time']), '%B %d, | %Y %I:%M %p')
self.timestamp = int(time.mktime(self.datetime.timetuple()))
def __str__(self):
return '(%s, %s) ~%sm @ %s' % (self.latitude, self.longitude, self.accuracy, self.datetime.strftime('%d/%m/%y %H:%M:%S'))
def _uncamel(self, str):
return ''.join('_%s' % c.lower() if c.isu... |
ingadhoc/odoo-saas-manager | addons/saas_product_base/__openerp__.py | Python | agpl-3.0 | 1,644 | 0.002433 | # -*- coding: utf-8 -*-
##############################################################################
#
# Saas Manager
# Copyright (C) 2013 Sistemas ADHOC
# No email
#
# This program is fre | e software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licen... |
nirmeshk/oh-mainline | vendor/packages/sphinx/sphinx/domains/javascript.py | Python | agpl-3.0 | 7,996 | 0.00025 | # -*- coding: utf-8 -*-
"""
sphinx.domains.javascript
~~~~~~~~~~~~~~~~~~~~~~~~~
The JavaScript domain.
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinx import addnodes
from sphinx.domains import Domain, ObjType
from sphinx.lo... | if '(' in sig and sig[-1:] == ')':
prefix, arglist = sig.split('(', 1)
prefix = prefix.strip()
arglist = arglist[:-1].strip()
else:
prefix = sig
arglist = None
if '.' in prefix:
nameprefix, name = prefix.rsplit('.', 1)
... | None
name = prefix
objectname = self.env.temp_data.get('js:object')
if nameprefix:
if objectname:
# someone documenting the method of an attribute of the current
# object? shouldn't happen but who knows...
nameprefix = objectname +... |
hehongliang/tensorflow | tensorflow/contrib/distribute/python/parameter_server_strategy_test.py | Python | apache-2.0 | 29,905 | 0.006688 | # 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... | tion, 'grpc://' + self._cluster_spec[WORKER][task_id],
sess_config)
def _test_device_assignment_distributed(self, task_type, task_id, num_gpus):
worker_device = '/job:%s/replica:0/task:%d' % (task_type, task_id)
d, _, sess_config = self._get_test_objects(task_type, task_id, num_gpus)
with ops... | tside the call_for_each_replica scope.
n = variable_scope.get_variable('n', initializer=10.0)
self.assertEqual(n.device, '/job:ps/task:0')
def model_fn():
if num_gpus == 0:
last_part_device = 'device:CPU:0'
else:
replica_id = _get_replica_id_integer()
las... |
patricklodder/dogecoin | qa/rpc-tests/prioritise_transaction.py | Python | mit | 6,684 | 0.003291 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 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 PrioritiseTransaction code
#
from test_framework.test_framework import BitcoinTestFramework
fro... | ool = self.nodes[0].getrawmempool(True)
sizes = [0, 0, 0]
for i | in range(3):
for j in txids[i]:
assert(j in mempool)
sizes[i] += mempool[j]['size']
assert(sizes[i] > MAX_BLOCK_BASE_SIZE) # Fail => raise utxo_count
# add a fee delta to something in the cheapest bucket and make sure it gets mined
# also check th... |
TaiSakuma/AlphaTwirl | alphatwirl/selection/factories/LambdaStrFactory.py | Python | bsd-3-clause | 330 | 0.024242 | # Tai Sakuma <tai.sakuma@cern.ch>
##__________________________________________________________________||
def LambdaStrFactory(lambda_str, LambdaStrClass, name = N | one, **kargs):
return LambdaStrClass(lambda_str = lambda_str.format(**kargs), name = name)
##_________________ | _________________________________________________||
|
infobloxopen/infoblox-netmri | infoblox_netmri/api/remote/models/access_provisioning_alerts_rules_grid_remote.py | Python | apache-2.0 | 1,565 | 0.004473 | from ..remote import RemoteModel
class AccessProvisioningAlertsRulesGridRemote(RemoteModel):
"""
list of alerts
| ``id:`` The internal NetMRI identifier for this alert view.
| ``attribute type:`` number
| ``issue_meta_type_id:`` The name of the meta type of this alert. One of 'WhiteList', 'B... | entifier of the workbook of rule lists on which the searches for this alert should applied.
| ``attribute type:`` number
"""
properties = ("id",
"issue_meta_type_id",
"name",
"sources",
"destinations",
"source_ports... | "access",
"workbook_id",
)
|
intelligent-agent/redeem | tests/gcode/test_G33.py | Python | gpl-3.0 | 2,397 | 0.007092 | from __future__ import absolute_import
import mock
import numpy as np
from .MockPrinter import MockPrinter
from redeem.Gcode import Gcode
class G33_Tests(MockPrinter):
def setUp(self):
pass
def test_G33_properties(self):
self.assertGcodeProperties("G33", is_buffered=True, is_async=True)
@mock.patch("... | al triangle, 30mm off the deck
{0.080, 0.0, 0.030}, {-0.040, 0.070, 0.030}, {-0.040, -0.070, 0.030}
]
self.printer.probe_heights = [0.031, 0.032, 0.033] # imoderate (arbitrary) build plate angle
self.printer.processor.execute = mock.Mock() # prevent macro command execution
self.printer.pa... | compare to expected """
autocal_call_args = self.printer.path_planner.autocalibrate_delta_printer.call_args[0]
self.assertEqual(autocal_call_args[0], 3)
self.assertEqual(autocal_call_args[1], False)
np.testing.assert_array_equal(
autocal_call_args[2],
np.array([set([0.0, 0.03, 0.08]),
... |
hzhao/gensim | gensim/models/wrappers/ldamallet.py | Python | gpl-3.0 | 10,772 | 0.00557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Python wrapper for Latent Dirichlet Allocation (LDA) from MALLET, the Java topic modelling
toolkit [1]_.
This module allows both L... | if retval != 0:
raise RuntimeError("MALLET failed with error %s on return" % retval)
result = list(read_doctopics(self.fdoctopics() + '.infer'))
return result if is_corpus else result[0]
def load_word_topics(self):
logger.info("loading assigned topics from %s" % self.fst... |
with utils.smart_open(self.fstate()) as fin:
_ = next(fin) # header
self.alpha = numpy.array([float(val) for val in next(fin).split()[2:]])
assert len(self.alpha) == self.num_topics, "mismatch between MALLET vs. reques |
google-research/mint | mint/ctl/single_task_trainer.py | Python | apache-2.0 | 8,299 | 0.003735 | # 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 to in writing... | trics.Metric | ` object, or a list of
`tf.keras.metrics.Metric` objects.
trainer_options: An optional `orbit.utils.StandardTrainerOptions` object.
summary_fn: A function that adds tf.summary on model input and output
tensors.
grad_clip_norm: A float to clip the gradients by global norm.
"""
s... |
Astroua/plndist | pln_distrib.py | Python | gpl-2.0 | 1,319 | 0.001516 |
'''
Implementation in scipy form of the Double Pareto-Lognormal Distribution
'''
import numpy as np
from scipy.stats import rv_continuous, norm
def _pln_pdf(x, alpha, nu, tau2):
A1 = np.exp(alpha * nu + alpha ** 2 * tau2 / 2)
fofx = alpha * A1 * x ** (-alpha - 1) *\
norm.cdf((np.log(x) - nu - alpha ... | g(x) - nu - alpha * tau2) / np.sqrt(tau2))
def _pln_rawmoments(r, alpha, nu, tau2):
if alpha > r:
return alpha / (alpha - r) * np.exp(r*nu + r**2.*tau2/2)
else:
return np.NaN
class pln_gen(rv_continuous):
def _pdf(self, x, alpha, nu, tau2):
| return _pln_pdf(x, alpha, nu, tau2)
def _logpdf(self, x, alpha, nu, tau2):
return _pln_logpdf(x, alpha, nu, tau2)
def _cdf(self, x, alpha, nu, tau2):
return _pln_cdf(x, alpha, nu, tau2)
pln = pln_gen(name="pln", a=0.0)
|
thomas-hori/Repuge-NG | TeddyMapB.py | Python | mpl-2.0 | 864 | 0.016204 | from TeddyMapBase import TeddyMapBase
from TfGun import TfGun
class TeddyMapB(TeddyMapBase):
#Raw string (r""") because backslashes
# Lab "Other room"
coded_grid=r"""
/------------T-T----------------\
|............>-<................|
|............|%|................|
|............|.|................|
... |
|...............................|
|...............................|
|...............................|
`--------------^----------------'
"""
starting_pt=(14,6)
title_window="The Verres' Basement"
def handle_staircase(self,playerobj):
self.game.level_advance(playerobj)
def initialise | (self):
#Place TF-gun
self.gun=TfGun(self.game)
x,y=self.get_new_point()
self.gun.place(x,y,self)
|
woolfson-group/isambard | isambard/ampal/specifications/assembly_specs/coiledcoil.py | Python | mit | 8,988 | 0.000779 | """Contains code for modelling coiled coils and collagens."""
import numpy
from ampal.specifications.polymer_specs.helix import HelicalHelix, _helix_parameters
from ampal.protein import Assembly
basis_set_parameters = {
2: {'name': 'CC-Di', 'pitch': 225.8, 'radius': 5.07, 'interface_angle': 283.56,
'sequ... | minor helices relative to the super-helical
axis.
major_pitches : [float]
Pitch values of the minor helices relative to the super-helical
axis.
phi_c_alphas :
Relative rotation values of the minor helices relative to
the super-helical axis.
minor_helix_types : [str]
... | ss : str
Handedness of the super helix.
orientations :
Orientation of helices relative to the super-helical axis. 1
is parallel, -1 is anti-parallel.
minor_repeats : [float]
Hydrophobic repeats of the minor helices.
rotational_offsets :
Rotation of the minor helices r... |
nipunagarwala/cs224s_final_project | run.py | Python | mit | 26,610 | 0.007967 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import math
import random
import time
import argparse
import pickle
import shutil
import autocorrect
import scipy
import warnings
from collections import defaultdict
import numpy as np
im... | e_to_print`: its input shape,
active timesteps, target text, and the beam results and their
probabilities as well as their auto-corrected versions.
Inputs:
example_to_print: integer indicating which example from batch
to drill down on
split: a string indicating which split ... | (batch_size,) in which each
element reflects the number of active timesteps in the
corresponding example in `samples`
transcripts: a sparse 3-tuple; the first element is an array
of indices, the second element is an array of values,
and the third element is an ar... |
Orav/kbengine | kbe/src/lib/python/Lib/ctypes/test/test_pep3118.py | Python | lgpl-3.0 | 8,041 | 0.006964 | import unittest
from ctypes import *
import re, struct, sys
if sys.byteorder == "little":
THIS_ENDIAN = "<"
OTHER_ENDIAN = ">"
else:
THIS_ENDIAN = ">"
OTHER_ENDIAN = "<"
def normalize(format):
# Remove current endian specifier and white space from a format
# string
if format ... | x", c_long), ("y", c_long)]
cl | ass EmptyStruct(Structure):
_fields_ = []
class aUnion(Union):
_fields_ = [("a", c_int)]
class StructWithArrays(Structure):
_fields_ = [("x", c_long * 3 * 2), ("y", Point * 4)]
class Incomplete(Structure):
pass
class Complete(Structure):
pass
PComplete = POINTER(Complete)
Complete... |
mihaip/NewsBlur | apps/profile/urls.py | Python | mit | 2,216 | 0.006769 | from django.conf.urls import *
from apps.profile import views
urlpatterns = patterns('',
url(r'^get_preferences?/?', views.get_preference),
url(r'^set_preference/?', views.set_preference),
url(r'^set_account_settings/?', views.set_account_settings),
url(r'^get_view_setting/?', views.get_view_setting),
... | e-update-payment-history'),
url(r'^delete_account/?', views.delete_account, name='profile-delete-account'),
url(r'^forgot_password_ret | urn/?', views.forgot_password_return, name='profile-forgot-password-return'),
url(r'^forgot_password/?', views.forgot_password, name='profile-forgot-password'),
url(r'^delete_starred_stories/?', views.delete_starred_stories, name='profile-delete-starred-stories'),
url(r'^delete_all_sites/?', views.delete_al... |
emddudley/advent-of-code-solutions | 2015/day-6/advent-day-6-2.py | Python | unlicense | 914 | 0.015317 | # Advent of Code Solutions: Day 6, part 2
# https://github.com/emddudley/advent-of-code-solutions
import re
def twinkle_lights(instruction, lights):
tokens = re.split(r'(\d+)', instruction)
operation = tokens[0].strip()
if operation == 'turn on':
twinkle = lambda x: x + 1
elif operation == 't... | ] * 1000 for | n in range(1000) ]
with open('input', 'r') as input:
for instruction in input:
twinkle_lights(instruction, lights)
print(sum(map(sum, lights)))
|
pressel/mpi4py | test/test_attributes.py | Python | bsd-2-clause | 6,481 | 0.002314 | from mpi4py import MPI
import mpiunittest as unittest
class BaseTestCommAttr(object):
keyval = MPI.KEYVAL_INVALID
def tearDown(self):
self.comm.Free()
if self.keyval != MPI.KEYVAL_INVALID:
self.keyval = MPI.Comm.Free_keyval(self.keyval)
self.assertEqual(self.keyval, MP... | Equal(self.keyval, MPI.KEYVAL_INVALID)
attrval = [1,2,3]
self.win.Set_attr | (self.keyval, attrval)
o = self.win.Get_attr(self.keyval)
self.assertTrue(o is attrval)
self.win.Delete_attr(self.keyval)
o = self.win.Get_attr(self.keyval)
self.assertTrue(o is None)
def testAttrCopyDelete(self):
self.keyval = MPI.Win.Create_keyval(
dele... |
google/mirandum | alerts/ytsubs/migrations/0003_auto_20160418_0455.py | Python | apache-2.0 | 2,254 | 0.002662 | # -*- coding: utf-8 -*-
# Copyright 2016 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permi | ssions and
# limitations under the License.
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0006_updater_updaterevent'),
('ytsubs', '0002_auto_20160414_0317'),
]
operations = [
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/PIL/XpmImagePlugin.py | Python | bsd-2-clause | 3,101 | 0.000322 | #
# The Python Imaging Library.
# $Id$
#
# XPM File handling
#
# History:
# 1996-12-29 fl Created
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
#
# Copyright (c) Secret Labs AB 1997-2001.
# Copyright (c) Fredrik Lundh 1996-2001.
#
# See the README file for information on usage and redistribution.
#... | gb = int(rgb[1:], 16)
palette[c] = (o8((rgb >> 16) & 255) +
o8((rgb >> 8) & 255) +
o8(rgb & 255))
else:
# unknown colour
raise ValueE | rror("cannot read this XPM file")
break
else:
# missing colour key
raise ValueError("cannot read this XPM file")
self.mode = "P"
self.palette = ImagePalette.raw("RGB", b"".join(palette))
self.tile = [("raw", (0, 0)+self.size, se... |
tomaaron/raiden | raiden/tasks.py | Python | mit | 50,038 | 0.000959 | # -*- coding: utf-8 -*-
# pylint: disable=too-many-lines
import logging
import random
import time
import gevent
from gevent.event import AsyncResult
from gevent.queue import Empty, Queue
from gevent.timeout import Timeout
from random import randint
from ethereum import slogging
from ethereum.utils import sha3
from ... | K:
remove.append(callback)
for callback in remove:
self.callbacks.remove(callback)
# we want this task to iterate i | n the tick of `wait_time`, so take
# into account how long we spent executing one tick.
work_time = time.time() - last_loop
if work_time > self.wait_time:
log.warning(
'alarm loop is taking longer than the wait time',
work_time=... |
operasoftware/presto-testo | wpt/websockets/websock_handlers/after_handshake_raw_wsh.py | Python | bsd-3-clause | 264 | 0.015152 | #!/usr/bin/python
from mod_pywebsocket import msgutil
import urllib
def web_socket_do_extra_handshake(reque | st):
pass
def web_socket_transfer_data(request):
msgutil._write(request, urllib.unquote(request.ws_location.split('?', | 1)[1]).decode("string-escape"))
|
miketheman/opencomparison | package/models.py | Python | mit | 11,990 | 0.002252 | from datetime import datetime, timedelta
import json
import re
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.translation import ugettext_lazy as _
fro... | gnal_fetch_latest_metadata
from package.utils import get_version, get_pypi_version
repo_url_help_text = settings.PACKAGINATOR_HELP_TEXT['REPO_URL']
pypi_url_help_te | xt = settings.PACKAGINATOR_HELP_TEXT['PYPI_URL']
class NoPyPiVersionFound(Exception):
pass
class Category(BaseModel):
title = models.CharField(_("Title"), max_length="50")
slug = models.SlugField(_("slug"))
description = models.TextField(_("description"), blank=True)
title_plural = models.CharF... |
relayr/python-sdk | demos/relayr_inventory.py | Python | mit | 4,257 | 0.003054 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Scan all relayr resources of a given user via the | relayr API.
This should be useful for finding out IDs for all devices of your
account, see which devices are connected to which apps, or which
channels are open on a d | evice, etc.
All that is needed is a relayr access token from the relayr developer
dashboard to be provided on the command-line:
https://developer.relayr.io/dashboard/apps/myApps
Output can be in JSON or YAML (the latter wasn't much tested).
To-do:
- remove some redundancy w.r.t. device models
Sample usage:
rel... |
papedaniel/oioioi | oioioi/disqualification/views.py | Python | gpl-3.0 | 755 | 0 | from oioioi.contests.models import Submission
from oioioi.dashboard.registry import dashboard_registry
from oioioi.disqualification.controllers import \
DisqualificationContestControllerMixin
@dashboard_registry.register_decorator(order=10)
def disqualification_fragment(request):
if not request.user.is_authe... | missions = Submission.objects \
.filter(problem_instance__contest=request.contest) \
| .order_by('-date').select_related()
submissions = cc.filter_my_visible_submissions(request, submissions)
return cc.render_disqualifications(request, submissions)
|
marcusmueller/gnuradio | gr-utils/python/modtool/core/disable.py | Python | gpl-3.0 | 7,940 | 0.003023 | #
# Copyright 2013, 2018, 2019 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later ... | License
# along with GNU Radio; see the file COPYING. If not, | write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
""" Disable blocks module """
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import re
import sys
import logging
from ..tools import CMak... |
Kuniwak/vint | vint/utils/array.py | Python | mit | 349 | 0.008596 | from typing import Ty | peVar, List, Callable # noqa: F401
from functools import reduce
from operator import add
T = TypeVar('T')
S = TypeVar('S')
def flatten(l):
# type: (List[List[T]]) -> List[T]
return reduce(add, l, [])
def flat_map(f, l):
# type: (Callable[[S], List[T] | ], List[S]) -> List[T]
return flatten([f(x) for x in l]) |
tensorflow/moonlight | moonlight/training/generation/generation.py | Python | apache-2.0 | 11,447 | 0.005154 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | or_command is relative, it is relative to the pipeline
# binary.
vexflow_generator_command[0] = _normalize_path(vexflow_generator_command[0]) |
seeds = ','.join(map(str, seeds))
return json.loads(
subprocess.check_output(vexflow_generator_command +
['--random_seeds=' + seeds]))
def _svg_to_png(self, svg):
svg_to_png_command = list(self.svg_to_png_command)
svg_to_png_command[0] = _normalize_path(svg_t... |
City-of-Helsinki/linkedevents | helevents/migrations/0004_auto_20180109_1727.py | Python | mit | 639 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-01-09 15:27
from __future__ import unicode_literals |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('helusers', '0001_add_ad_groups'),
('helevents', '0003_auto_20170915_1529'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={'ordering'... | e, to='helusers.ADGroup'),
),
]
|
ColumbiaCMB/kid_readout | kid_readout/measurement/acquire.py | Python | bsd-2-clause | 9,283 | 0.003878 | """
Basic framework for acquiring a roach measurement that includes both sweep(s) and stream(s).
Acquire
-Initialize equipment.
-Initialize roach: preload frequencies, if necessary.
-Create state dictionary containing state from all equipment, including temperatures, if possible.
-Run a coarse sweep, if necessary: cre... | ment.
verbose : bool
If true, print progress messages.
wait_for_sync : float
Sleep for this time in seconds to let the ROACH sync finish.
kwargs
Keyword arguments passed to ri.get_measurement().
Returns
-------
SweepArray
"""
stream_arrays = core.MeasurementList(... | for n, tone_bank in enumerate(tone_banks):
if verbose:
print n,
sys.stdout.flush()
ri.set_tone_freqs(tone_bank, nsamp=num_tone_samples)
ri.select_fft_bins(np.arange(tone_bank.size))
# we wait a bit here to let the roach2 sync catch up. figuring this out still.... |
neeraj9/gprsmonitor | src/sniff.py | Python | apache-2.0 | 1,409 | 0.023421 | #! /usr/bin/python
__author__="kebo"
__date__ ="$2009-11-5 11:15:55$"
import pcap
import sys
import string
import time
import socket
import struct
import getopt
protocols={socket.IPPROTO_TCP:'tcp',
socket.IPPROTO_UDP:'udp',
socket.IPPROTO_ICMP:'icmp'}
node = None
mb = None
decoder = None
def se... | )
dev = "eth0"
net, mask = pcap.lookupnet(dev)
# note: to_ms does nothing on linux
p.open_live(dev, 1600, 0, 100)
#p.dump_open('dumpfile')
p.setfilter(string.join(["tcp","port 22"],' '), 0, 0)
# try-except block to catch keyboard interrupt. Failure to shut
# down cleanly can result in ... | eyboardInterrupt:
print '%s' % sys.exc_type
print 'shutting down'
print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
|
novafloss/django-formidable | formidable/exceptions.py | Python | mit | 99 | 0 |
class Un | knownAccess(Exception):
"""
Access doesn't exist for this user.
""" |
pass
|
Arcanemagus/SickRage | tests/torrent_tests.py | Python | gpl-3.0 | 4,493 | 0.003784 | # coding=UTF-8
# Author: Dennis Lutter <lad1337@gmail.com>
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of... | = "Italian Works"
show.episodes = []
episode = TVEpisode(show, 5, 10)
episode.name = "Pines of Rome"
episode.scene_season = 5
episode.scene_episode = 10
show.episodes.append(episode)
cls.shows.append(show)
def test_bitcannon(self):
"""
Test bi... | here (e.g., "http://localhost:3000/")
bitcannon.api_key = ""
if bitcannon.custom_url:
# pylint: disable=protected-access
search_strings_list = bitcannon._get_episode_search_strings(self.shows[0].episodes[0]) # [{'Episode': ['Italian Works S05E10']}]
for search_stri... |
ttfseiko/openerp-trunk | openerp/addons/hr_attendance/wizard/hr_attendance_bymonth.py | Python | agpl-3.0 | 2,066 | 0.000968 | # -*- coding: utf-8 -*-
###############################################################################
#
# 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 GN... | lds.integer('Year', required=True)
}
_defaults = {
'month': lambda *a: time.gmtime()[1],
'year': lambda *a: time.gmtime()[0],
}
def print_report(self, cr, uid, ids, context=None):
datas = {
'ids': [],
| 'active_ids': context['active_ids'],
'model': 'hr.employee',
'form': self.read(cr, uid, ids)[0]
}
return {
'type': 'ir.actions.report.xml',
'report_name': 'hr.attendance.bymonth',
'datas': datas,
}
# vim:expandtab:smartindent... |
rajul/tvb-framework | tvb/core/services/texture_to_json.py | Python | gpl-2.0 | 2,352 | 0.005102 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | 0.5)/img_width for i in xrange(img_width/band_height)]
color_schemes = []
for v in tex_vs:
idx = int(v * img_width)
color_schemes.append(ima[idx, :, :3].tolist())
return color | _schemes |
ibabushkin/BeastBot | src/inc/modules/tinyurl.py | Python | gpl-3.0 | 1,158 | 0.007772 | from inc import *
#from __future__ import with_statement
import re
import contextlib
from urllib import urlencode
from urllib2 import urlopen
import sys
modFunc.addCommand('tiny', 'tinyurl', 'getTiny')
modFunc.addCommand('tinygfm', 'tinyurl', 'tinyLMGTFY')
modFunc.addCommand('tinylmgtfy', 'tinyurl', 'tinyLMGTFY')
modF... | equest_url)) as response:
ircFunc.ircSay(msgto, response.read().decode('utf-8'), irc)
def tinyLMGTFY(line, irc):
message, whole, username, msgto = ircFunc.ircMessage(line.strip(), whl=True)
url = ' '.join(message[1:])
| url = 'http://lmgtfy.com/?q=' + url
request_url = ('http://tinyurl.com/api-create.php?%s' % urlencode({'url':url}))
with contextlib.closing(urlopen(request_url)) as response:
ircFunc.ircSay(msgto, response.read().decode('utf-8'), irc)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.