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 |
|---|---|---|---|---|---|---|---|---|
quattor/aquilon | lib/aquilon/worker/commands/grant_root_access.py | Python | apache-2.0 | 2,384 | 0.000839 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2014,2015,2016,2017 Contributor
#
# 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 Li... | eed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the logic for `aq grant root acces... | NetGroupWhiteList
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.dbwrappers.change_management import ChangeManagement
class CommandGrantRootAccess(BrokerCommand):
requires_plenaries = True
required_parameters = ['personality', 'justification']
def _update_dbobj(self, obj, dbuser=No... |
smartshark/vcsSHARK | pyvcsshark/utils.py | Python | apache-2.0 | 1,460 | 0.007534 | import os
import sys
def readable_dir(prospective_dir):
""" Function that checks if a path is a directory, if it exists and if it is accessible and only
returns true if all these three are the case
:param prospective_dir: path to the directory"""
if prospective_dir is not None:
if not os.... | eption("readable_dir:{0} is not a readable dir".format(prospective_dir))
def find_plugins(plugin_dir):
"""Finds all python files in the spec | ified path and imports them. This is needed, if we want to
detect automatically, which datastore and parser we can apply
:param plugin_dir: path to the plugin directory"""
plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")]
sys.path.insert(0, plugin_dir)
for plugin in p... |
gratefulfrog/lib | python/web/pymolhttpd.py | Python | gpl-2.0 | 32,673 | 0.005632 | # Copyright (C) Schrodinger, LLC.
# All Rights Reserved
#
# For more information, see LICENSE in PyMOL's home directory.
#
# pymolhttpd.py
#
# web server interface for controlling PyMOL
# we make extensive use of Python's build-in in web infrastructure
import BaseHTTPServer, cgi, urlparse
import StringIO, socket
# w... | ethod name or trailing slash -> blank
parts.append('')
if (parts[1] == 'apply'): # calling a method
self.pymol_apply(parts[2])
elif (parts[1] == 'getattr'): # retrieving a property
self.pymol_getattr(parts[2])
elif (parts[1] == 'echo'):... | self.echo_args(parts[2])
else: # simple file retrieval
self.send_doc()
def pymol_getattr(self, attr):
"""
apply the repr method to the requested attr, but only for
allowed attributes - those stored in the session dictionary
"""
key = '/getattr/... |
coursera/courseraresearchexports | courseraresearchexports/containers/__init__.py | Python | apache-2.0 | 65 | 0 | __ | all__ = [
"clie | nt",
"utils"
]
from . import * # noqa
|
mmgen/mmgen | mmgen/color.py | Python | gpl-3.0 | 3,151 | 0.046652 | #!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
#
# 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 Softwa... | dim': ( 108, (32,0) ),
'redbg': ( (232,210), (30,101) ),
'grnbg': ( (232,121), (30,102) ) | ,
'blubg': ( (232,75), (30,104) ),
'yelbg': ( (232,229), (30,103) ),
}
def nocolor(s):
return s
def set_vt100():
'hack to put term into VT100 mode under MSWin'
from .globalvars import g
if g.platform == 'win':
from subprocess import run
run([],shell=True)
def get_terminfo_colors(term=None):
f... |
watchdogpolska/poradnia.siecobywatelska.pl | poradnia/events/views.py | Python | bsd-3-clause | 5,142 | 0.000583 | import locale
from atom.ext.guardian.views import RaisePermissionRequiredMixin
from braces.views import (
FormValidMessageMixin,
LoginRequiredMixin,
SelectRelatedMixin,
UserFormKwargsMixin,
)
from cached_property import cached_property
from dateutil.relativedelta import relativedelta
from django.conf i... | ort (
ArchiveIndexView,
CreateView,
MonthArchiveView,
UpdateView,
)
from django.views.generic.list import BaseListView
from poradnia.cases.models import C | ase
from poradnia.keys.mixins import KeyAuthMixin
from poradnia.users.utils import PermissionMixin
from .forms import EventForm
from .models import Event
from .utils import EventCalendar
class EventCreateView(
RaisePermissionRequiredMixin, UserFormKwargsMixin, FormValidMessageMixin, CreateView
):
model = Eve... |
kaji-project/shinken-mod-logstore-sqlite | module/module.py | Python | agpl-3.0 | 28,080 | 0.003098 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redis... | ack is used to create a full-blown select-statement
self.sql_filter_stack = LiveStatusSqlStack()
# This stack is used to create a minimal select-statement which
# selects only by time >= and time <=
self.sql_time_filter_stack = LiveStatusSqlStack()
# Now sleep one second, so tha... |
def load(self, app):
self.app = app
def init(self):
self.old_implementation = old_implementation
def open(self):
logger.info("[Logstore SQLite] Open LiveStatusLogStoreSqlite ok : %s" % self.database_file)
self.dbconn = sqlite3.connect(self.database_file, check_same_thread... |
noironetworks/aci-integration-module | aim/db/hashtree_db_listener.py | Python | apache-2.0 | 18,457 | 0 | # Copyright (c) 2016 Cisco Systems
# 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 require... | roupRule and
obj.remote_group_id and
not obj.remote_ips):
continue
# Need a | ll the faults and statuses as well
stat = self.aim_manager.get_status(
aim_ctx, obj, create_if_absent=False)
if getattr(obj, 'sync', True):
if stat:
log_by_root.setdefault(obj.root, []... |
wholland/env | vim/runtime/bundle/ultisnips/plugin/UltiSnips/_diff.py | Python | mit | 7,737 | 0.010857 | #!/usr/bin/env python
# encoding: utf-8
from collections import defaultdict
import sys
from UltiSnips import _vim
from UltiSnips.geometry import Position
def is_complete_edit(initial_line, a, b, cmds):
buf = a[:]
for cmd in cmds:
ctype, line, col, char = cmd
line -= initial_line
if ct... | character costs only have of the first deletion.
- Insertion is cheaper the earlier it happes. The first character is more
expensive that any later [2].
[1] This is that world -> aolsa will be "D" world + "I" aolsa instead of
"D" w , "D" rld, "I" a, "I" lsa
[2] This is that "... | sys.maxsize)
d[0] = [ (0,0,sline, 0, ()) ]
cost = 0
D_COST = len(a)+len(b)
I_COST = len(a)+len(b)
while True:
while len(d[cost]):
x, y, line, col, what = d[cost].pop()
if a[x:] == b[y:]:
return what
if x < len(a) and y < len(b) and a[x]... |
home-assistant/home-assistant | tests/components/wemo/conftest.py | Python | apache-2.0 | 3,246 | 0 | """Fixtures for pywemo."""
import asyncio
from unittest.mock import create_autospec, patch
import pytest
import pywemo
from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.helpers import entity_registry as er
from homeassistant... | ess", return_value=url), patch(
"pywemo.discovery.device_from_description", return_value=device
):
yield device
@pytest.fixture(name="wemo_entity_suffix")
def wemo_entity_suffix_fixture():
"""Fixture to select a specific entity for wemo_entity."""
return ""
@pytest.fixture(name="w | emo_entity")
async def async_wemo_entity_fixture(hass, pywemo_device, wemo_entity_suffix):
"""Fixture for a Wemo entity in hass."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [f"{MOCK_HOST}... |
jad-b/garden | garden_test/testfile.py | Python | mit | 42 | 0 | #!/usr/bin/ | env python3
ve | rsion = '0.1.2'
|
cvxgrp/ncvx | ncvx/orthog.py | Python | gpl-3.0 | 1,674 | 0 | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... | pe=(size, size), *args, **kwargs)
def init_z(self, rand | om):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(self, matrix):
"""All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
return U.dot(... |
sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/auxilium/tools/git_tools.py | Python | apache-2.0 | 3,958 | 0 | # -*- coding: utf-8 -*-
# auxilium
# --------
# Python project for an automated test and deploy toolkit.
#
# Author: sonntagsgesicht
# Version: 0.1.9, copyright Saturday, 02 October 2021
# Website: https://github.com/sonntagsgesicht/auxilium
# License: Apache License 2.0 (see LICENSE file)
from logging import l... | + '@' + url
class Buffer(list):
def write(self, b):
self.append(b)
def push_git(remote='None', branch=BRANCH, path=getcwd()):
"""push current branch of local to remote `git` repo"""
log(INFO, ICONS["push"] + "push | current branch to remote `git` repo")
log(DEBUG, ICONS[""] + "at " + clean_url(remote))
out = Buffer()
try:
porcelain.push(Repo(path), remote, branch, out, out)
except Exception as e:
log(ERROR, ICONS['error'] + str(e))
return 1
for line in out:
log(INFO, ICONS[""]... |
ohmu/pghoard | pghoard/archive_sync.py | Python | apache-2.0 | 13,251 | 0.003773 | """
pghoard: sync local WAL files to remote archive
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
import argparse
import hashlib
import logging
import os
import sys
import requests
from pghoard.common import get_pg_wal_directory
from . import config, logutil, version, wal
from .rohmu.errors import Invalid... | eline
existing_wal_without_checksum_count += 1
if existing_wal_without_checksum_count == 1:
self.log.info(
"%s file %r already archived but no hash is available, reuploading", archive_type, wal_fi | le
)
need_archival.append(wal_file)
continue
if check_hash:
hash_checks_done += 1
our_hash = self.calculate_hash(os.path.join(wal_dir, wal_file), hash_algorithm)
... |
br0r/systemet-api | server.py | Python | mit | 230 | 0.017391 | impo | rt os
from flask import jsonify
from systemetapi import app
from systemetapi import config
@app.route("/")
def index():
return jsonify(version=config.VERSION, status='ok')
if __name__ | == "__main__":
app.run(debug=True)
|
TangentMicroServices/BuildService | buildservice/urls.py | Python | mit | 697 | 0.005739 | from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import sta | tic
from api.views import router
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^ui/', include('ui.urls', namespace='build_ui')),
url(r'^api-auth/',
include('rest_framework.urls', namespace=' | rest_framework')),
url(r'^explorer/',
include('rest_framework_swagger.urls', namespace='swagger')),
]
# Setting up static files for development:
if settings.DEBUG is True:
urlpatterns = urlpatterns + \
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
Insanityandme/dotfiles | vim/bundle/YouCompleteMe/python/ycm/youcompleteme.py | Python | unlicense | 25,635 | 0.030505 | # Copyright (C) 2011, 2012 Google Inc.
#
# 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 option) any late... | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from __future__ import pri... |
Babaritech/babar3 | back/babar_server/tests.py | Python | mit | 3,743 | 0 | import random
from decimal import Decimal, ROUND_HALF_UP
from django.test import TestCase
from django.core.validators import ValidationError
from .models import *
def setup():
"""
Create dummy data
"""
Status.objects.create(
name="Hero",
overdraft="0"
)
Status.objects.create(
... | )
amount -= 5
else:
m = random.randrange(0, 20000) / 100
Payment.objects.create(
customer=Customer.objects.get(nickname="jim"),
amount=m
)
amount += Decimal(m)
self.a... | ts.get(nickname="jim").balance,
amount.quantize(Decimal('.001'), rounding=ROUND_HALF_UP)
)
class PurchaseTests(TestCase):
def test_purchase_auto_amount(self):
"""
Test the amount field is automatically created
"""
setup()
p = Purchase.objects.create(
... |
bigdatafoundation/qngene | Export_gen_files/gentotsv.py | Python | apache-2.0 | 14,598 | 0.037608 | #!/usr/bin/python
#title :gentotsv.py
#description :Script to process impute files .gz and create a csv file
#author :Diego Alvarez
#date :2016-06-05
#python_version :3.5
#==============================================================================
import gzip
import os
import fn... |
utils.log(logger,"Begin - Create SNP file -")
filename = p_destination_dir+"SNP"+p_dest_file_type
open(filename, 'w').close()
for file_l | ist in sorted(os.listdir(p_source_dir)):
if fnmatch.fnmatch(file_list,'*'+p_source_file_type):
with gzip.open(p_source_dir+file_list,'rb') as genfile:
sequence=0
gencountlines=0
utils.log(logger,"Reading file GEN: " + file_list)
with open(filename,'ab') as SNPfile:
... |
batiste/django-page-cms | pages/testproj/documents/views.py | Python | bsd-3-clause | 577 | 0 | from django.shortcuts import render
from pages.testproj.documents.models import Document
def document_view(request, *args, **kwargs):
context = kwargs
if kwargs.get('current_page', False):
documents = Document.objects.filter(page=kwargs['current_page'])
context['documents'] = documents
if ... | = Document.objects.get(pk=int(kwargs['document_i | d']))
context['document'] = document
context['in_document_view'] = True
return render(
request, 'pages/examples/index.html',
context)
|
AustinDKB/War-Card-Game-Simulator | war_sim.py | Python | gpl-2.0 | 4,472 | 0.003131 | import random
def war_handler():
war_handler.count += 1
print("War is {0} is happening.").format(war_handler.count)
if len(player_one) > 4 and len(player_two) > 4:
limiter = 3
elif len(player_one) == 4 or len(player_two) == 4:
limiter = 2
else: # len(player_one) < 4 or len(player_... | > player_two:
player_one.append(temp[0])
player_one.append(temp[1])
else: # player_one < player_two
player_two.append(temp[0])
player_two.append(temp[1])
else:
continue
if not player_one:
print("Player {0} Wins!").format(player_two_name)
elif ... | _two:
print("Player {0} Wins!").format(player_one_name)
print("War Count: {0}").format(total_wars)
|
arnaudsj/titanium_mobile | support/android/builder.py | Python | apache-2.0 | 74,676 | 0.03076 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Appcelerator Titanium Mobile
# Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
# Licensed under the terms of the Apache Public License
# Please see the LICENSE included with this distribution for details.
#
# General builder script for staging, packaging, ... | ath.join(top_support_dir, 'module'))
fro | m tiapp import *
from android import Android
from androidsdk import AndroidSDK
from deltafy import Deltafy, Delta
from css import csscompiler
from module import ModuleDetector
import localecompiler
import fastdev
ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store'];
ignoreDirs = ['.git','.svn','_svn', 'CVS'];
andro... |
cmdunkers/DeeperMind | Players/Connect4_RandomAI.py | Python | bsd-3-clause | 894 | 0.00783 | from Player import Player
import random
import numpy
import time
class Connect4_RandomAI(Player):
def __init__(self,value):
# In | itialize the random number generator using the current time as a seed so that we don't see the exact same AI
# behavior every time.
random.seed(time.clock())
self.value = value
#end def init()
'''
'''
def value(self):
return self.value;
#end def value()
'''
... | lf, board):
#####
# Pick a random valid column to drop our disc in
#####
# Keep generating random moves until we get one that is valid
while True:
move = numpy.array([0, random.randint(0, board.width - 1)])
if board.IsValidMove(move):
bre... |
langcog/wordbank | instruments/schemas/French_Quebecois_WG.py | Python | gpl-2.0 | 67,512 | 0.01182 | from django.db import models
from instruments.base import BaseTable
class French_Quebecois_WG(BaseTable):
item_1_choices = [('understands', 'understands'), ('produces', 'produces')]
item_1 = models.CharField(max_length=11, choices=item_1_choices, null=True)
item_2_choices = [('understands', 'understands')... | 11, choices=item_30_choices, null=True)
item_31_choices = [('understands', 'understands'), ('produces', 'produces')]
item_31 = models.CharField(max_length=11, choices=item_31_choices, null=True)
item_32_choices = [('understands', 'understands'), ('produces', 'produces')]
item_32 = models.CharField(max_l... | em_32_choices, null=True)
item_33_choices = [('understands', 'understands'), ('produces', 'produces')]
item_33 = models.CharField(max_length=11, choices=item_33_choices, null=True)
item_34_choices = [('understands', 'understands'), ('produces', 'produces')]
item_34 = models.CharField(max_length=11, choi... |
danielbair/aeneas | aeneas/extra/__init__.py | Python | agpl-3.0 | 1,124 | 0 | #!/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, Re | adBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it)
#
# This program is free 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, ... |
calpeyser/google-cloud-python | logging/google/cloud/logging/entries.py | Python | apache-2.0 | 7,721 | 0 | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ls = resource.get('labels')
severity = resource.get('severity')
http_request = resource.get('httpRequest')
monitored_resource_dict = resource.get('resource')
monitored_resource = None
if monitored_resource_dict is not None:
monitored_resour | ce = Resource._from_dict(monitored_resource_dict)
return cls(payload, logger, insert_id=insert_id, timestamp=timestamp,
labels=labels, severity=severity, http_request=http_request,
resource=monitored_resource)
class TextEntry(_BaseEntry):
"""Entry created with ``text... |
tempbottle/ironpython3 | Tests/modules/type_related/array_test.py | Python | apache-2.0 | 10,771 | 0.013555 | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of th... | copy")
if is_cli or is | _silverlight:
#CodePlex 19200
y = x.__deepcopy__()
else:
y = x.__deepcopy__(x)
Assert(id(x) != id(y), "copy should copy")
def test_array___deepcopy__():
'''
TODO
'''
pass
def test_array___delattr__():
'''
TODO
'''
pass
def test_array___delitem__():
... |
edisonlz/fruit | web_project/base/site-packages/gdata/tlslite/utils/OpenSSL_TripleDES.py | Python | apache-2.0 | 1,666 | 0.004802 | """OpenSSL/M2Crypto 3DES implementation."""
from cryptomath import *
from TripleDES import *
if m2cryptoLoaded:
def new(key, mode, IV):
return OpenSSL_TripleDES(key, mode, IV)
class OpenSSL_TripleDES(TripleDES):
def __init__(self, key, mode, IV):
TripleDES.__init__(self, key, mo... | IV, encrypt)
return context
def encrypt(self, plaintext):
TripleDES.encrypt(self, plaintext)
context = self._createContext(1)
ciphertext = m2.cipher_update(context, plaintext)
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_si... | xt
def decrypt(self, ciphertext):
TripleDES.decrypt(self, ciphertext)
context = self._createContext(0)
#I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
#To work around this, we append sixteen zeros to the string, below:
... |
yoosw/printrun_etri | printrun/gui/control_printing.py | Python | gpl-3.0 | 6,280 | 0.007643 | import wx
import os
from printrun.utils import imagefile
def Print_Control(root, parentpanel):
if os.name == "nt":
root.text_loading_file = wx.StaticText(parentpanel, label=str(root.var_loading_file_name), pos=(75, 33))
else:
root.text_loading_file = wx.StaticText(parentpanel, label=str(root.... | e_temp1, (34, 233))
root.text_print_nozzle_temp1_set = wx.StaticText(parentpanel, label=("0" + u"\u00B0C"), pos=(111, 247))
root.text_print_nozzle_temp1_on = wx.StaticText(parentpanel, label=("0" + u"\u00B0C"), pos=(111, 281))
root.text_print_nozzle_temp1_set.SetFont(root.font_base)
root.text | _print_nozzle_temp1_on.SetFont(root.font_base)
root.text_print_nozzle_temp1_set.SetForegroundColour("#3399FF") # set text color
root.text_print_nozzle_temp1_on.SetForegroundColour("#FF3300")
# nozzle2
wx.StaticBitmap(parentpanel, -1, bmp_print_nozzle_temp2, (230, 233))
root.text_print_nozzle_temp2_... |
gappleto97/Senior-Project | common/bounty.py | Python | mit | 14,300 | 0.002587 | import os, pickle, re, sys, rsa
from common.safeprint import safeprint
from common.call import parse
from multiprocessing import Lock
from hashlib import sha256
global bountyList
global bountyLock
global bountyPath
global masterKey
bountyList = []
bountyLock = Lock()
bounty_path = "data" + os.sep + "bounties.pickle"
m... | te key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-... | ept:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for cha... |
pennyan/Smtlink | z3_interface/RewriteExpt.py | Python | bsd-3-clause | 15,337 | 0.006194 | # Copyright (C) 2015, University of British Columbia
# Written (originally) by Mark Greenstreet (13th March, 2014)
# Editted by Yan Peng (11th Nov. 2016)
#
# License: A 3-clause BSD license.
# See the LICENSE file distributed with this software
import collections
import ACL2_to_Z3
import z3
def prod(stuff)... | return
report | (' appending ', v, ' to allQ and workQ')
allQ.append(v)
workQ.append(v)
def xpt(x, n):
v = self.expt(x, n)
enqueue(v)
return v
def lookfor_expt(v):
if(v is None): return
elif(hasattr(v, "decl") and hasattr(... |
waseem18/Shorten-it | main.py | Python | mit | 2,602 | 0.036126 | import webapp2
import os
import urllib2
from google.appengine.ext import db
import jinja2
import urlparse
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(... | :
def get(self):
self.render('welcome.html')
def post(self):
lurl = self.request.get('lurl')
lurl_instance = StoreUrl(lurl=lurl)
lurl_instance.put()
k = lurl_instance.key()
idd = k.id() #Here comes the ID of the stored url which I needed the most.
#This ID... | idd_c = idd%1000000
id_list = []
while(idd_c > 0):
rem = idd_c%62
id_list.append(rem)
idd_c = idd_c/62
id_list.reverse()
i=0
final_url = "http://shorten-it-app.appspot.com/"
while i<len(id_list):
x = alphabets[id_list[i]]
... |
Pexego/sale_commission | __unported__/full_stock_traceability/mrp_production.py | Python | agpl-3.0 | 4,398 | 0.005231 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2011 Pexego (<www.pexego.es>). All Rights Reserved
# $Omar Castiñeira Saavedra$
#
# This program is free software: you can redistribute it ... | ove.move_dest_id.id], {'state': 'assigned'})
to_delete_moves.append(move.id)
if move.product_id.track_all and not move.product_id.miscible:
default_prodlot, prodlot_location, default_qty, split = self.pool.get('stock.pr | oduction.lot').get_default_production_lot(cr, uid, move.location_id.id, move.product_id.id, self.pool.get('product.uom')._compute_qty(cr, uid, move.product_uom.id, move.product_qty, move.product_id.uom_id.id), deep=True)
if split:
new_moves = self.pool.get('stock.move').move_reserve... |
LarsMichelsen/pmatic | tests/TestAPI.py | Python | gpl-2.0 | 1,142 | 0.000876 | #!/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 Foundation; either version 2 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. ... | have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Add Python 3.x behaviour to 2.7
from __future__ import absolute_import
from __future__ import division
from __future__ i... |
redisca/django-redisca | redisca/template/templatetags/builtin.py | Python | mit | 833 | 0 | from django.template import Library
register = Library()
@register.simple_tag(takes_context=True)
def assign(context, **kwargs):
"""
Usage:
{% assign hello="Hello Django" %}
"""
for key, value in kwargs.items():
context[key] = value
return ''
@register.filter
def get(content, key):... | etattr(content, key, '')
return ''
@register.simple_tag()
def call( | fn, *args, **kwargs):
"""
Usage:
{% call object.method *args **kwargs %}
Callable function should be decorated with
redisca.template.decorators.template_func.
"""
if callable(fn):
return fn(*args, **kwargs)
return fn
|
wimglenn/argboss | test_override_kwargs.py | Python | mit | 1,470 | 0.003401 | from override_kwargs import override_kwargs
from other_module import delegating_function, function
from datetime import datetime
from unittest import TestCase
def function_in_this_module(x=123):
"""hello I'm a docstring"""
return x
def MyClass(object):
def method_in_this_module(x=123):
return x
w... | erride_kwargs('other_module', 'ClassInOtherModule.method', {'x': 69}):
assert delegating_function() == 69
assert delegating_function() == 123
with override_kwargs('other_module', 'another_modu | le.another_function', {0: 69}):
assert delegating_function() == 69
assert delegating_function() == 123
then = datetime(year=1982, month=3, day=19)
with override_kwargs('__main__', 'datetime', {'year': 1982}):
assert datetime(year=2014, month=3, day=19) == then
|
anhstudios/swganh | data/scripts/templates/object/draft_schematic/space/capacitor/shared_heavy_battery_mk5.py | Python | mit | 462 | 0.047619 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.temp | late = "object/draft_schematic/space/capacitor/shared_heavy_battery_mk5.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFIC | ATIONS ####
return result |
openthread/silk | silk/tests/openthread/ot_test_off_mesh_route_traffic.py | Python | apache-2.0 | 8,855 | 0.002259 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | _MESH_ROUTE_1 = "fd00:abba::"
OFF_MESH_ROUTE_2 = "fd00:cafe::"
OFF_MESH_ROUTE_3 = "fd00:baba::"
OFF_MESH_ADDR_1 = OFF_MESH_ROUTE_1 + "1"
OFF_MESH_ADDR | _2 = OFF_MESH_ROUTE_2 + "2"
OFF_MESH_ADDR_3 = OFF_MESH_ROUTE_3 + "3"
POLL_INTERVAL = 400
class TestOffMeshRouteTraffic(testcase.TestCase):
# Test description: Adding off-mesh routes (on routers and FEDs) and traffic flow to off-mesh addresses.
#
# Test topology:
#
# r1 ---- r2
# | ... |
anupcshan/buddyfs | settings.py | Python | mit | 55 | 0 | BUDDY_P | ORT = 5000
DBPATH = '.'
RE | PONAME = ".buddyrepo"
|
skirpichev/omg | diofant/logic/__init__.py | Python | bsd-3-clause | 512 | 0 | """
Pack | age for handling logical expressions.
"""
from .boolalg import (ITE, And, Equivalent, Implies, Nand, Nor, Not, Or,
POSform, SOPform, Xor, bool_map, false, simplify_logic,
to_cnf, to_dnf, to_nnf, true)
from .inference import satisfiable
__all__ = ('ITE', 'And', 'Equivalent'... | 'satisfiable')
|
hellrich/coling2016 | python/compare_word_over_models.py | Python | gpl-3.0 | 2,208 | 0.000453 | import gensim
import sys
import collections
import codecs
import re
import math
from copy import deepcopy
def compare(word, topn, models):
words = {}
counts = {}
sim = {}
for m in models:
model = gensim.models.Word2Vec.load_word2vec_format(m, binary=True)
words[m] = model.most_similar(... | nter.intersection(set(s))
return inter
def main():
if len(sys.argv) < 2:
raise Exception(
"Provide 2+ arguments:\n\t1,word\n\t2+,model(s)")
word = sys.argv[1].lower()
models = sys.argv[2:]
words = compare(word, 20, models)
for key in words:
print(words[key])
fo... | = [[word for word, sim in words[key][:i]]for key in words]
common = common_with_limit(ws)
print("common:", common, "--->", len(common), "@", i)
inter = intersection(ws)
print("intersection:", inter, "--->", len(inter), "@", i)
if __name__ == "__main__":
main()
|
YueLinHo/Subversion | subversion/bindings/swig/python/svn/repos.py | Python | apache-2.0 | 12,959 | 0.007099 | #
# repos.py: public Python interface for repos components
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
######################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contrib... | dir_baton[2], # base_rev
dir_path, # path
| False, # added
CHANGE_ACTION_MODIFY,
)
def add_file(self, path, parent_baton,
copyfrom_path, copyfrom_revision, file_pool=None):
action = path in self.changes and CHANGE_ACTION... |
pyfa-org/eos | eos/eve_obj/effect/repairs/ship_module_ancillary_remote_shield_booster.py | Python | lgpl-3.0 | 1,564 | 0 | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as publi... | ftware Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Eos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI | TNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Eos. If not, see <http://www.gnu.org/licenses/>.
# ==============================================================================
imp... |
sourabhg/HelpSet | app/Utils/__init__.py | Python | gpl-2.0 | 39 | 0.076923 | __al | l__=['ResponseWriter','serverSets' | ] |
qtproject/pyside-pyside | tests/QtMultimediaWidgets/qmultimediawidgets.py | Python | lgpl-2.1 | 2,146 | 0.010718 | #############################################################################
##
## Copyright (C) 2017 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the test suite of PySide2.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensees holding valid commercial ... | QWidget.__init__(self)
layout = QVBoxLayout(self)
layout.addWidget(QVideoWidget())
graphicsScene = QGraphicsScene()
graphicsView = QGraphicsView(graphicsScene)
graphicsScene.addItem(QGraphicsVideoI | tem())
layout.addWidget(graphicsView)
class QMultimediaWidgetsTest(UsesQApplication):
def testMultimediaWidgets(self):
w = MyWidget()
w.show()
timer = QTimer.singleShot(100, self.app.quit)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
|
graphql-python/graphql-epoxy | tests/test_register_enum.py | Python | mit | 519 | 0.001927 | from graphql.core.type.definition import GraphQLEnumType
from epoxy.registry import TypeRegistry
from enum import Enum
def test_register_builtin_enum():
R = TypeRegistry()
@R
| class MyEnum(Enum):
FOO = 1
BAR = 2
BAZ = 3
enum = R.type('MyEnum')
assert isinstance(enum, GraphQLEnumType)
values = enum.get_values()
assert [v.name for v | in values] == ['FOO', 'BAR', 'BAZ']
assert [v.value for v in values] == [MyEnum.FOO.value, MyEnum.BAR.value, MyEnum.BAZ.value]
|
googleapis/synthtool | synthtool/gcp/gapic_bazel.py | Python | apache-2.0 | 13,771 | 0.001234 | # Copyright 2019 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, ... | "nodejs":
suffix = f"{service}-{version}-nodejs"
elif language == "go":
suffix = f"gapi-{'-'.join(parts[1:])}-go"
else:
suffix = f"{'-'.join(parts)}-{language}"
bazel_target = f"//{os.path.sep.join(parts)}:{suffix}"
# Confi... | dError(
f"Unable to find directory for protos: {(api_definitions_repo / protos)}."
)
if not tuple((api_definitions_repo / protos).glob("*.proto")):
raise FileNotFoundError(
f"Directory {(api_definitions_repo / protos)} exists, but no pr... |
javacruft/pylxd | pylxd/operation.py | Python | apache-2.0 | 3,139 | 0 | # Copyright (c) 2015 Canonical 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 ... | data = data.get('metadata')
return parse_date(data['created_at']).strftime('%Y-%m-%d %H:%M:%S')
def operation_update_time(self, operation, data):
if data is None:
(state, data) = self.connection.get_object(
'GET', '/1.0/operations/%s' % operation)
... | data['updated_at']).strftime('%Y-%m-%d %H:%M:%S')
def operation_status_code(self, operation, data):
if data is None:
(state, data) = self.connection.get_object(
'GET', '/1.0/operations/%s' % operation)
data = data.get('metadata')
return data['status']
de... |
henkelis/sonospy | sonospy/brisa/upnp/control_point/msearch.py | Python | gpl-3.0 | 6,719 | 0.001786 | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php or see LICENSE file.
#
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <coherence@beebits.net>
# Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org>
""" Contains the MSearch class which ca... | @type host: string
@type port: integer
"""
# print "datagram_received start"
cmd, headers = parse_http_response(data)
if cmd[0] == 'HTTP/1.1' and cmd[1] == '200':
if self.ssdp != None:
if not self.ssdp.is_known_device(headers['usn']):
| log.debug('Received MSearch answer %s,%s from %s:%s',
headers['usn'], headers['st'], host, port)
# print "_datagram_received _register"
# print "_datagram_received headers: " + str(headers)
self.ssdp._register(heade... |
eort/OpenSesame | opensesame_extensions/quick_switcher/quick_switcher.py | Python | gpl-3.0 | 2,188 | 0.023766 | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free So | ftware Foundation, either version 3 of the License, or
(at your option) any later | version.
OpenSesame is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ... |
chillbear/django-role-permissions | docs/conf.py | Python | mit | 8,335 | 0.006599 | # -*- coding: utf-8 -*-
#
# django-role-permissions documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 9 09:02:16 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogener... | .
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name ... | le to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to ... |
mozilla/firefox-flicks | vendor-local/lib/python/celery/tests/utilities/test_saferef.py | Python | bsd-3-clause | 1,896 | 0 | from __future__ import absolute_import
from celery.utils.dispatch.saferef import safe_ref
from celery.tests.utils import Case
class Class1(object):
def x(self):
pass
def fun(obj):
pass
class Class2(object):
def __call__(self, obj):
pass
class SaferefTests(Case):
def setUp(sel... | 1
for t in self.ts:
if hasattr(t, 'x'):
self.assertIn(safe_ref(t.x), sd)
else:
self.assertIn(safe_ref(t), sd)
def testRepresentation(self):
"""Test that the reference object's representation works
XXX Doesn't currentl | y check the results, just that no error
is raised
"""
repr(self.ss[-1])
def _closure(self, ref):
"""Dumb utility mechanism to increment deletion counter"""
self.closureCount += 1
|
mrGeen/eden | modules/eden/menus.py | Python | mit | 70,805 | 0.00233 | # -*- coding: utf-8 -*-
""" Sahana Eden Menu Structure and Layout
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
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 So... | ))
auth = current.auth
# Modules to hide due to insufficient permissions
hidden_modules = auth.permission.hidden_modules()
has_role = auth.s3_has_role
# The Modules to display at the top level (in order)
for module_type in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
for m... |
continue
_module = all_modules[module]
if (_module.module_type == module_type):
if not _module.access:
menu_modules.append(MM(_module.name_nice, c=module, f="index"))
else:
groups... |
wylieswanson/agilepyfs | fs/expose/dokan/__init__.py | Python | bsd-3-clause | 37,866 | 0.005123 | """
fs.expose.dokan
===============
Expose an FS object to the native filesystem via Dokan.
This module provides the necessary interfaces t | o mount an FS object into
the local filesystem using Dokan on win32::
http://dokan-dev.net/en/
For simple usage, the function 'mount' takes an FS object | and a drive letter,
and exposes the given FS as that drive::
>>> from fs.memoryfs import MemoryFS
>>> from fs.expose import dokan
>>> fs = MemoryFS()
>>> mp = dokan.mount(fs,"Q")
>>> mp.drive
'Q'
>>> mp.path
'Q:\\'
>>> mp.unmount()
The above spawns a new background process to mana... |
chrissmall22/odl-client | odlclient/datatypes.py | Python | apache-2.0 | 43,110 | 0.00007 | #!/usr/bin/env python
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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... | AP['packet'],
'apps': JSON_MAP['app'],
'licenses': JSON_MAP['license'],
'paths': JSON_MAP['path'],
'nexthops': JSON_MAP['nexthop']
}
CLASS_MAP = {'ControllerStats': {'lost': 'Counter',
'packet_in': 'Counter',
... |
'instructions': 'Instruction'},
'Stats': {'port_stats': 'PortStats',
'group_stats': 'GroupStats',
'meter_stats': 'MeterStats'},
'Packet': {'eth': 'Ethernet',
'ip': 'Ip',
'ipv6':... |
RationalAsh/configs | i3-exit.py | Python | mit | 4,584 | 0.007199 | #!/usr/bin/env python
# based on cb-exit used in CrunchBang Linux <http://crunchbanglinux.org/>
import pygtk
pygtk.require('2.0')
import gtk
import os
import getpass
import time
class i3_exit:
def disable_buttons(self):
self.cancel.set_sensitive(False)
self.logout.set_sensitive(False)
sel... | et_border_widt | h(4)
self.reboot.connect("clicked", self.reboot_action)
self.button_box.pack_start(self.reboot)
self.reboot.show()
#Shutdown button
self.shutdown = gtk.Button("_Power off")
self.shutdown.set_border_width(4)
self.shutdown.connect("clicked", self.shutdown_a... |
lpancescu/atlas-lint | setup.py | Python | mit | 3,767 | 0.000266 | # vim: set fileencoding=utf-8 :
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from ... | ou wish (should match "license" above) |
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programmi... |
City-of-Helsinki/kerrokantasi | democracy/models/initial_data.py | Python | mit | 860 | 0.001168 | from democracy.enums import InitialSectionType
INITIAL_SECTION_TYPE_DATA = [
{
'identifier': InitialSectionType.MA | IN,
'name_singular': 'pääosio',
'name_plural': 'pääosiot', |
},
{
'identifier': InitialSectionType.CLOSURE_INFO,
'name_singular': 'sulkeutumistiedote',
'name_plural': 'sulkeutumistiedotteet',
},
{
'identifier': InitialSectionType.SCENARIO,
'name_singular': 'vaihtoehto',
'name_plural': 'vaihtoehdot',
},
{
... |
lcpt/xc | verif/tests/materials/ec2/test_EC2Concrete.py | Python | gpl-3.0 | 5,205 | 0.074352 | # -*- coding: utf-8 -*-
from __future__ import division
from materials.ec2 import EC2_materials
import os
from miscUtils import LogMessages as lmsg
__author__= "Ana Ortega (AO_O) "
__copyright__= "Copyright 2015, AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "ana.ortega@ciccp.es "
fckDat=[12,16,20,25,30,35,... | i in range(0,len(fctk095Dat)):
sqrErr+= (fctk095Dat[i]-fctk095Calc[i])**2
fname= os.path.basename(__file__)+'-fctk095'
if sqrErr<1e-8:
print "test ",fname,": ok."
else:
lmsg.error(fname+' ERROR.')
#Test Ecm
EcmDat=[27,29,30,31,33,34,35,36,37,38,39,41,42,44] #[GPa]
sqrErr= 0.0
for i in range(0,len(EcmDat)):
sq... | ')
#Test Epsc1
Epsc1Dat=[1.8,1.9,2.0,2.1,2.2,2.2,2.3,2.4,2.5,2.5,2.6,2.7,2.8,2.8] #[per thousand]
sqrErr= 0.0
for i in range(0,len(Epsc1Dat)):
sqrErr+= (Epsc1Dat[i]-Epsc1Calc[i])**2
fname= os.path.basename(__file__)+'-Epsc1'
if sqrErr<1e-8:
print "test ",fname,": ok."
else:
lmsg.error(fname+' ERROR.')
#Test Ep... |
fbradyirl/home-assistant | homeassistant/components/media_player/const.py | Python | apache-2.0 | 1,935 | 0 | """Proides the constants needed for component."""
ATTR_APP_ID = "app_id"
ATTR_APP_NAME = "app_name"
ATTR_INPUT_SOURCE = "source"
ATTR_INPUT_SOURCE_LIST = "source_list"
ATTR_MEDIA_ALBUM_ARTIST = "media_album_artist"
ATTR_MEDIA_ALBUM_NAME = "media_album_name"
ATTR_MEDIA_ARTIST = "media_artist"
ATTR_MEDIA_CHANNEL = "medi... | n"
ATTR_MEDIA_SERIES_TITLE = "media_series_title"
ATTR_MEDIA_SHUFFLE = "shuffle"
ATTR_MEDIA_TITLE = "media_title"
ATTR_MEDIA_TRACK = "media_track"
ATTR_MEDIA_VOLUME_LEVEL = "volume_level"
ATTR_MEDIA_VOLUME_MUTED = "is_volume_muted"
ATTR_SOUND_MODE = "sound_mode"
ATTR_SOUND_MODE_LIST = "sound_mode_list"
DOMAIN = "media... | _TYPE_CHANNEL = "channel"
MEDIA_TYPE_PLAYLIST = "playlist"
MEDIA_TYPE_IMAGE = "image"
MEDIA_TYPE_URL = "url"
MEDIA_TYPE_GAME = "game"
MEDIA_TYPE_APP = "app"
SERVICE_CLEAR_PLAYLIST = "clear_playlist"
SERVICE_PLAY_MEDIA = "play_media"
SERVICE_SELECT_SOUND_MODE = "select_sound_mode"
SERVICE_SELECT_SOURCE = "select_source... |
i1ikey0u/watchwxfiles | watchdog_of_wxgzh.py | Python | gpl-3.0 | 6,141 | 0.02833 | #!/usr/bin/env python
# coding:utf-8
# environ: python3.6 32bit
# code by shuichon
'''
V3.2,优化了执行流程和操作的简易性,修补了几个bug
'''
from urllib import request, parse
from bs4 import BeautifulSoup
import re, json, sys
def get_warn(soup):
'''
频繁访问时,搜狗会需要二次验证,判断是否需要二次验证
'''
warn = soup.find_all('p', class_='ip... | 的公众号' % sys.argv[2])
if (len(sys.argv[:]) > 3) and (sys.argv[3][1:] == 'gnum'):
option2 = sys.argv[3][1:]
print('获取%i个微信公众号进行内容识别' % int(sys.argv[4]))
gzh_url_l = get_gzh_lists(keys=sys.argv[2], gzh_num=int(sys.argv[4]))
for l in gzh_url_l:
print("当前公众号访问URL:")
print(l)
... | 当前公众号最近10篇公众号文章URL:")
for wz in get_gzh_content_top10(l):
print(wz)
elif (len(sys.argv[:]) > 3) and (sys.argv[3][1:] == 'key'):
option2 = sys.argv[3][1:]
print('使用 "%s" 关键字搜索微信公众号' % sys.argv[2])
gzh_url_l = get_gzh_lists(keys=sys.argv[2])
for l in gzh_url_l:
print(l)
... |
badracket/django-brdesigner | brdesigner/admin.py | Python | gpl-2.0 | 2,044 | 0.029843 | from django import forms
from django.contrib import admin
from myproject.brdesigner.model | s import *
from django.utils.safestring import mark_safe
class BadRacketAdminBase(admin.ModelAdmin):
class Media:
js = (
'brdesigner/js/admin_list_reorder.js',
' | brdesigner/js/tinymce/tinymce.min.js',
'brdesigner/js/textareas.js',
)
class SortablePageAdmin(BadRacketAdminBase):
list_display = ["id","name","title","url_pattern","page_type","is_active","display_order"]
list_display_links = ["id"]
list_editable = ["name","title","url_pattern","page_... |
jorik041/Network | dht/node.py | Python | mit | 3,684 | 0.000814 | """
Copyright (c) 2014 Brian Muller
Copyright (c) 2015 OpenBazaar
"""
import heapq
from operator import itemgetter
from protos import objects
class Node:
def __init__(self, id, ip=None, port=None, signed_pubkey=None,
vendor=False):
self.id = id
self.ip = ip
| self.port = port
self.signed_pubkey = signed_pubkey
self.vendor = vendor
self.long_id = long(id.encode('hex'), 16)
def getProto(self):
n = objects.Node()
n.guid = self.id
n.signedPublicKey = se | lf.signed_pubkey
n.vendor = self.vendor
if self.ip is not None: n.ip = self.ip
if self.port is not None: n.port = self.port
return n
def sameHomeAs(self, node):
return self.ip == node.ip and self.port == node.port
def distanceTo(self, node):
"""
Get the ... |
dabillox/kcl-globalgasflaring | src/tests/test_ggf.py | Python | mit | 7,690 | 0.00078 | import unittest
import pandas as pd
import numpy as np
import glob
import epr
import src.utils as utils
from src.ggf.detectors import SLSDetector, ATXDetector
class MyTestCase(unittest.TestCase):
# -----------------
# unit tests
# -----------------
def test_szn_interpolation(self):
path_to_... | glob("../../data/test_data/S3A*.zip")[0]
path_to_target = "../../data/test_data/sls_de | tect_hotspots.npy"
path_to_temp = "../../data/temp/"
target = np.load(path_to_target)
product = utils.extract_zip(path_to_data, path_to_temp)
HotspotDetector = SLSDetector(product)
HotspotDetector.run_detector()
self.assertEqual(True, (target == HotspotDetector.hotspot... |
NarlikarLab/DIVERSITY | weblogoMod/corebio/db/astral.py | Python | gpl-3.0 | 12,519 | 0.011662 |
# Copyright 2000 by Jeffrey Chang. All rights reserved.
# Copyright 2001 by Gavin E. Crooks. All rights reserved.
# Modifications Copyright 2004/2005 James Casbon.
# Copyright 2005 by Regents of the University of California. All rights reserved
# (Major rewrite for conformance to corebio. Gavin Crooks)
#
# This c... |
_domain_re = re.compile(r">?([\w_\.]*)\s+([\w\.]*)\s+\(([^)]*)\) (.*)")
def parse_domain(str) :
"""Convert an ASTRAL fasta header string into a SCOP domain.
An ASTRAL (http://astral.stanford.edu/) header contains a concise
description of a SCOP domain. A very similar format is used when a
Domain... | ject is converted into a string. The Domain returned by this
method contains most of the SCOP information, but it will not be located
within the SCOP hierarchy (i.e. the parent node will be None). The
description is composed of the SCOP protein and species descriptions.
A typical ASTRAL header looks l... |
nwjs/chromium.src | tools/flags/list_flags.py | Python | bsd-3-clause | 4,638 | 0.009702 | #!/usr/bin/env python3
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Emits a formatted, optionally filtered view of the list of flags.
"""
from __future__ import print_function
import argparse
impor... | [{'expiry_milestone': 3}]
>>> keep_expired_by([{'expiry_milestone': -1}], 3)
[]
"""
return [f for f in flags if -1 != f['expiry_milestone'] <= mstone]
def keep_never_expires(flags):
"""Filter flags to contain only flags that never expire.
>>> keep_never_expires([{'expiry_milestone': -1}, {'expiry_milest... | of owners for every flag in the provided list.
Given a list of flags, for each flag, resolves owners for that flag. Resolving
owners means, for each entry in a flag's owners list:
* Turning owners files references into the transitive set of owners listed in
those files
* Turning bare usernames into @chrom... |
DistributedML/TorML | eurosys-eval/results_tor_no_tor/makeplot.py | Python | mit | 1,404 | 0.002849 | import matplotlib.pyplot as plt
import numpy as np
import pdb
if __name__ == "__main__":
fig, ax = plt.subplots(figsize=(10,5))
for clients in (10, 50, 100, 200):
median_data = np.zeros(5)
for k in (1, 2, 3, 4, 5):
data = np.loadtxt("loss_" + str(clients) + "_" + str(k) + ".csv... | + str(np.median(median_data))
print str(clients) + " stddev is " + str(np.std(median_data | ))
data1 = np.loadtxt("loss_10_2.csv", delimiter=',')
data2 = np.loadtxt("loss_50_2.csv", delimiter=',')
data3 = np.loadtxt("loss_100_2.csv", delimiter=',')
data4 = np.loadtxt("loss_200_2.csv", delimiter=',')
plt.plot(data1, color="black", label="10 clients", lw=5)
plt.plot(data2, color="r... |
gtaylor/evarify | setup.py | Python | mit | 1,220 | 0 | import re
from setuptools import setup, find_packages
with open('evarify/__init__.py', 'r') as fd:
version = re.search(r'^__version | __\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
setup(
name="evarify",
version=version,
author="Greg Taylor",
author_email="gtaylor@gc-taylor.com",
description="Environment variable v... | keywords="environment variable",
url='https://github.com/gtaylor/evarify',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: System Administrators',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Lang... |
nicolashainaux/mathmaker | tests/integration/mental_calculation/04_yellow1/test_04_yellow1_W02b.py | Python | gpl-3.0 | 1,241 | 0 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2018 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | with Mathmaker; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from mathmaker.lib import shared
from mathmaker.lib.document.frames import Sheet
def test_W02b():
"""Check this sheet is | generated without any error."""
shared.machine.write_out(str(Sheet('mental_calculation',
'04_yellow1',
'W02b')),
pdf_output=True)
|
beni55/flocker | flocker/common/__init__.py | Python | apache-2.0 | 193 | 0 | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__al | l__ = ['INode', 'FakeNode', 'ProcessNode']
from ._ipc import INode, FakeNode, ProcessNod | e
|
pdehaye/theming-edx-platform | common/lib/xmodule/xmodule/capa_module.py | Python | agpl-3.0 | 44,840 | 0.001784 | import cgi
import datetime
import hashlib
import json
import logging
import os
import traceback
import struct
import sys
from pkg_resources import resource_string
from capa.capa_problem import LoncapaProblem
from capa.responsetypes import StudentInputError, \
ResponseError, LoncapaProblemError
from capa.util impo... | ngs)
graceperiod = Timedelta(
help="Amount of time after the due date that submissions will be accepted",
scope=Scope.settings
)
showanswer = S | tring(
display_name="Show Answer",
help=("Defines when to show the answer to the problem. "
"A default value can be set in Advanced Settings."),
scope=Scope.settings,
default="finished",
values=[
{"display_name": "Always", "value": "always"},
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/models/object_detection/trainer_test.py | Python | bsd-2-clause | 6,635 | 0.002411 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | agreed to in writing, software
# distributed under the License is distributed on an "AS IS | " BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for object_detection.trainer."""
import t... |
chapman-phys227-2016s/cw-5-classwork-team | calculus.py | Python | mit | 2,271 | 0.005724 | #!/usr/bin/python
"""
Cw5 the pinacle of grupwork and efficienceyc and comroodery
Calculus module implementing
discrete function function
differentiation function
and trapezoidal integration function
"""
import numpy as np
import math
def diff(f, a, b, n):
"""An iterative version of a forward differentiation m... | matrix[-1][-2] = -1 / h
return np.dot(matrix, y)
def test_diff():
apt = math.fabs(diff(math.sin, 0, 1, 100000)[1][-1] - math.cos(1)) < 1e-3
msg = 'That aint how the sine function do.'
assert apt, msg
def test_diff2():
apt = math.fabs(diff(math.sin, 0, 1, 100000)[1][-1] - math.cos(1)) < 1e-3
m... | oidal_matrix(f, a, b, n):
"""Trapezoidal integration via matrix multiplication."""
h = (b-a)/float(n)
indexer = np.linspace(a, b, n)
values = f(indexer)
matrixer = np.zeros(n)
matrixer.fill(h)
matrixer[0] = h/2.0
matrixer[n - 1] = h/2.0
I = np.dot(values, matrixer)
return I
def ... |
vrde/pandora | pandora/views.py | Python | mit | 458 | 0.002183 | from django.shortcuts import render
f | rom django.middleware.csrf import get_token
from ajaxuploader.views import AjaxFileUploader
from pandora.backends import SignalBasedLocalUploadBackend
from pandora.models import Item
def home(request):
return render(request, 'pandora/home.html', {
'items': Item.objects.all(),
'csrf_token'... | xFileUploader(SignalBasedLocalUploadBackend)
|
saxix/django-uuid-pk | django_uuid_pk/tests/settings.py | Python | bsd-3-clause | 1,626 | 0.00246 | import os
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY =';pkj;lkj;lkjh;lkj;oi'
db = os.environ.get('DBENGINE', None)
if db == 'pg':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django_uuid_pk',
'HOST': '127.0.0.1',
... | DATABASES = {
' | default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_uuid_pk.sqlite',
'HOST': '',
'PORT': ''}}
INSTALLED_APPS = ('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.... |
modulexcite/catapult | dashboard/dashboard/group_report_test.py | Python | bsd-3-clause | 6,327 | 0.003161 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import webapp2
import webtest
from google.appengine.ext import ndb
from dashboard import group_report
from dashboard import test_owner
fro... | :
super(GroupReportTest, self).setUp()
app = webapp2.WSGIApplication(
[('/group_report', group_report.GroupReportHandler)])
self.testapp = webtest.TestApp(app)
def _AddAnomalyEntities(
self, revision_ranges, test_key, sheriff_key, bug_id=None):
"""Adds a group of Anomaly entities to the... | d_revision=end_rev,
test=test_key, bug_id=bug_id, sheriff=sheriff_key,
median_before_anomaly=100, median_after_anomaly=200).put()
urlsafe_keys.append(anomaly_key.urlsafe())
return urlsafe_keys
def _AddTests(self):
"""Adds sample Test entities and returns their keys."""
testing_c... |
rendermotion/RMPY | AutoRig/RMGenericRigStructure.py | Python | lgpl-3.0 | 2,106 | 0.004748 | import maya.cmds as cmds
try:
from MetacubeScripts import MetacubeFileNameConvention
except:
pass
class genericRigStructure(object):
def __init__(self):
self.groups = {
"mesh": {"group": "mesh_grp",
"subGroup": ["body_grp", "cloth_grp", "accesories_grp", "hair_grp... | "]:
for eachgroup in self.groups[genericGroup]["subGroup"]:
if not cmds.ob | jExists(eachgroup):
cmds.group(empty=True, name=eachgroup)
cmds.parent(eachgroup, self.groups[genericGroup]["group"])
|
albertaparicio/tfg-voice-conversion | attention_graphs.py | Python | gpl-3.0 | 905 | 0.022099 | import gzip
import os
import pickle
import matplotlib
import matplotlib.pyplot as | plt
import numpy as np
matplotlib.use('TKagg')
def show_attention():
# Load attentions
print('Loading attentions to pickle file')
with gzip.open(
os.path.join('training_results', 'torch_train', 'attentions.pkl.gz'),
'r') as att_file:
attentions = pickle.load(att_file)
# Set up figure with co... | = ax.matshow(np.mean(np.array(attentions),axis=(0,1)), cmap='bone')
fig.colorbar(cax)
# # Set up axes
# ax.set_xticklabels([''] + input_sentence.split(' ') +
# ['<EOS>'], rotation=90)
# ax.set_yticklabels([''] + output_words)
#
# # Show label at every tick
# ax.xaxis.set_major_locato... |
yoyo2k/l10n-romania | l10n_ro_invoice_report/__init__.py | Python | agpl-3.0 | 1,102 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008 Deltatech All Rights Reserved
# Dorin Hongu <dhongu(@)gmail(.)com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GN... | e
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
########### | ###################################################################
import account_invoice
import company
import report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
sonium0/pymatgen | pymatgen/core/tests/test_surface.py | Python | mit | 13,101 | 0.00084 | #!/usr/bin/python
import unittest
import os
import random
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.core.surface import Slab, SlabGenerator, generate_all_slabs, \
get_symmetrically_distinct_miller_indices
from pymatgen.symmetry.group... | reaterEqual(len(gen_normal.oriented_unit_cell),
len(gen.oriented_unit_cell))
sc = Structure(Lattice.hexagonal(3.32, 5.15), ["Sc", "Sc"],
| [[1/3, 2/3, 0.25], [2/3, 1/3, 0.75]])
gen = SlabGenerator(sc, (1, 1, 1), 10, 10, max_normal_search=1)
self.assertAlmostEqual(gen.oriented_unit_cell.lattice.angles[1], 90)
def test_get_slabs(self):
gen = SlabGenerator(self.get_structure("CsCl"), [0, 0, 1], 10, 10)
... |
dozymoe/fireh_runner | modules/odoo_test.py | Python | mit | 7,100 | 0.003239 | """ Odoo Test module.
Odoo is an OpenERP framework.
A copy of odoo.py with added features that eases testing.
Website: http://www.odoo.com
"""
import logging
import os
import subprocess
import sys
# set server timezone in UTC before time module imported
os.environ['TZ'] = 'UTC'
SHELL_TIMEOUT = None
SHELL_ENV_QUIET =... | y'
def odoo_test(loader, project=None, variant='testing', *args): #pylint:disable=keyword-arg-before-vararg
project, variant = loader.setup_project_env(project, variant)
loader.setup_virtualenv()
loader.setup_shell_env()
config = loader.get_project_config()
| python_bin = loader.get_python_bin()
config_file = os.environ.get('ODOO_CONFIG_FILE')
work_dir = config.get('work_dir', project)
work_dir = loader.expand_path(work_dir)
# bugfix, command like `odoo.py shell`, the word 'shell' must be mentioned
# before we define --config, weird
binargs = [py... |
rh-s/heat | heat/tests/test_glance_image.py | Python | apache-2.0 | 7,257 | 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
# ... | n: 0, max: None)')
self._test_validate(image, error_msg)
def test_invalid_min_ram(self):
# invalid 'min_ram'
tpl = template_format.parse(image_template_validate)
stack = parser.Stack(
self.ctx, 'glance_image_stack_validate',
template.Template(tpl)
)
... | : '
'-1 is out of range (min: 0, max: None)')
self._test_validate(image, error_msg)
def test_miss_disk_format(self):
# miss disk_format
tpl = template_format.parse(image_template_validate)
stack = parser.Stack(
self.ctx, 'glance_image_stack_validate'... |
grimoirelab/GrimoireELK | utils/gelk.py | Python | gpl-3.0 | 5,856 | 0.000854 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2019 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any l... | ms for feed
connector[0].add_params(subparser)
args = parser.parse_args()
app_init = datetime.now()
backend_name = args.backend
if not backend_name:
parser.print_help()
sys.exit(0)
if 'debug' in args and | args.debug:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
logging.debug("Debug mode activated")
else:
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("requ... |
vivaxy/algorithms | python/problems/add_binary.py | Python | mit | 1,091 | 0.000917 | """
https://leetcode.com/problems/add-binary/
https://leetcode.com/submissions/detail/106524947/
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
length = max(len(a), len(b))
remaining = 0
index = ... | remaining = 1
sum_value = sum_value - 2
result = str(sum_valu | e) + result
index += 1
if remaining != 0:
result = str(1) + result
return result
import unittest
class Test(unittest.TestCase):
def test(self):
self.assertEqual(Solution().addBinary('11', '1'), '100')
if __name__ == '__main__':
unittest.main()
|
daringer/schemmaker | src/force_optimizer/group.py | Python | apache-2.0 | 7,382 | 0.004741 | '''
Created on 23.08.2014
@author: christian auth
'''
from block import Block
class Group:
def __init__(self, group_id):
#set the ID of the group
self.group_id = group_id
#set the parent group
self.parent = None
self.childs = []
self.is_bias = False
se... | if self.childs.count(child) == 0:
self.childs.append(child)
def __str__(self):
nl = "\n"
less_padding = 16
padding = 20
more_padding = 24
# header (group_id + size + pos)
o = "" + nl
o += "+------------------------------------------" + nl
... | n_y, nl, pad=less_padding)
o += "+------------------------------------------" + nl
#show is bias
if self.is_bias:
o += "|{:>{pad}} {}".format("BIAS", nl, pad=padding)
# show parent
if self.parent is not None:
o += "|{:>{pad}}: {}{}".format("Parent", self.... |
Fabfm4/Sita-BackEnd | src/sita/payments/migrations/0001_initial.py | Python | apache-2.0 | 1,397 | 0.003579 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-05-22 03:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Paymen... | ISA'), (b'MASTERCARD', b'MASTERCARD'), | (b'AMEX', b'AMEX')], max_length=10)),
('amount', models.DecimalField(decimal_places=2, max_digits=10)),
('description', models.TextField()),
('reference_id_conekta', models.BinaryField()),
('currency', models.CharField(max_length=10)),
('t... |
altanawealth/django-report-builder | report_builder_demo/demo_models/migrations/0004_waiter_days_worked.py | Python | bsd-3-clause | 434 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('demo_models', '0003_auto_20150419_2110'),
]
operations = [
migrations.AddField( | model_name='waiter',
name='days_worked',
field=models.IntegerField(default=None, null=True, blank=True),
),
]
| |
Alex-Ian-Hamilton/sunpy | sunpy/spectra/tests/test_callisto.py | Python | bsd-2-clause | 10,406 | 0.000961 | # -*- coding: utf-8 -*-
# Author: Florian Mayer <florian.mayer@bitsrc.org>
from __future__ import absolute_import
import shutil
from tempfile import mkdtemp
from datetime import datetime
import pytest
import os
import glob
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
import... | 'Time',
'Frequency',
'Test',
None,
None,
None,
False
)
pairs_indices, factors, constants = c1._homogenize_params(
c2, 0
)
assert pairs_indices == [(0, 0)]
assert_array_almost_equal(factors, [0.5], 2)
assert_array_almost_equal(consta... | constant():
a = np.float64(np.random.randint(0, 255, 3600))[np.newaxis, :]
c1 = CallistoSpectrogram(
a,
np.arange(3600),
np.array([1]),
datetime(2011, 1, 1),
datetime(2011, 1, 1, 1),
0,
1,
'Time',
'Frequency',
'Test',
None,... |
morrisonlevi/FrameworkBenchmarks | netty/setup.py | Python | bsd-3-clause | 860 | 0.012791 | import subprocess
import sys
import setup_util
import os
def start(args, logfile, errfile):
try:
subprocess.check_call("mvn clean compile assembly:single", shell=True, cwd="netty", stderr=errfile, stdout=logfile)
subprocess.Popen("java -jar netty-example-0.1-jar-with-dependencies.jar".rsplit(" "), cwd="netty... | = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'netty-example' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
return 0
| |
icereval/osf.io | addons/dropbox/views.py | Python | apache-2.0 | 1,287 | 0.003885 | """Views fo the node settings page."""
# -*- coding: utf-8 -*-
from flask import request
import logging
from addons.dropbox.serializer import DropboxSerializer
from addons.base import generic_views
from website.project.decorators import must_have_addon, must_be_addon_authorizer
logger = logging.getLogger(__name__)
de... | )
return node_addon.get_folders(folder_id=folder_id)
dropbox_get_config = generic_views.get_config(
SHORT_NAME,
DropboxSerializer
)
def _set_folder(node_addon, folder, auth):
uid = fol | der['id']
node_addon.set_folder(uid, auth=auth)
node_addon.save()
dropbox_set_config = generic_views.set_config(
SHORT_NAME,
FULL_NAME,
DropboxSerializer,
_set_folder
)
dropbox_deauthorize_node = generic_views.deauthorize_node(
SHORT_NAME
)
|
mtlchun/edx | common/test/acceptance/tests/studio/test_studio_settings_details.py | Python | agpl-3.0 | 6,290 | 0.001908 | """
Acceptance tests for Studio's Settings Details pages
"""
from unittest import skip
from acceptance.tests.studio.base_studio_test import StudioCourseTest
from ...fixtures.course import CourseFixture
from ...pages.studio.settings import SettingsPage
from ...pages.studio.overview import CourseOutlinePage
from ...test... | ls in suite in Jenkins.')
def test_enable_entrance_exam_for_course(self):
"""
Test that entrance exam sh | ould be created after checking the 'enable entrance exam' checkbox.
And also that the entrance exam is destroyed after deselecting the checkbox.
"""
self.settings_detail.require_entrance_exam(required=True)
self.settings_detail.save_changes()
# getting the course outline page.
... |
osm-pl/osm-translation-scrapper | sites/weblate.py | Python | unlicense | 648 | 0 | from bs4 import BeautifulSoup
import requests as r
def run(projects, language):
base_url = "https://hosted.weblate.org/projects/{0}/{1}/ | #overview"
results = []
for project in projects:
url = base_url.format(project, language)
html_doc = r.get(url).text
soup = BeautifulSoup(html_doc, 'html.parser')
findings = soup.find(attrs={'class': "percent"})
if findings is not None:
value = findings.get_t... | s
|
eliseuegewarth/sibaho | empregado/migrations/0008_auto_20170209_1606.py | Python | lgpl-3.0 | 616 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-09 18:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration | ):
dependencies = [
('empregado', '0007_auto_20170208_2116'),
]
operations = [
migrations.Alter | Field(
model_name='estagiario',
name='email',
field=models.EmailField(max_length=100),
),
migrations.AlterField(
model_name='supervisor',
name='email',
field=models.EmailField(max_length=100),
),
]
|
kyvinh/home-assistant | homeassistant/components/emulated_hue/hue_api.py | Python | apache-2.0 | 13,038 | 0 | """Provides a Hue API to control Home Assistant."""
import asyncio
import logging
from aiohttp import web
from homeassistant import core
from homeassistant.const import (
ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_SET,
SERVICE_OPEN_COVER, SERVICE_CLOSE_COVER, STATE_ON, STATE_OFF,
HT... | (self.config, entity)
json_response = entity_to_json(entity, state, brightness)
return self.json(json_response)
class HueOneLightChangeView(HomeAssistantView):
"""Handle requests for getting and setting info about entities."""
url = '/api/{username}/lights/{entity_number}/state'
name = ... | e
def put(self, request, username, entity_number):
"""Process a request to set the state of an individual light."""
config = self.config
hass = request.app['hass']
entity_id = config.number_to_entity_id(entity_number)
if entity_id is None:
_LOGGER.error('Unknown ... |
sjdv1982/seamless | docs/archive/documentation-OLD/sphinx-source/conf.py | Python | mit | 5,272 | 0.000948 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# seamless documentation build configuration file, created by
# sphinx-quickstart on Mon Jul 3 17:16:13 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | t of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'seamless.tex', 'seamless documentation',
'Sjoerd de Vries', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry pe... | description, authors, manual section).
man_pages = [
(master_doc, 'seamless', 'seamless documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,... |
xiaoguoai/ec-dev-swift | swift/common/utils.py | Python | apache-2.0 | 85,284 | 0.000176 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wit | h the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# | Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""... |
sapcc/monasca-notification | tests/test_hipchat_notification.py | Python | apache-2.0 | 3,335 | 0.0009 | # 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 Li... | ,
"alarmDescription": "test Alarm description",
"oldState": "OK",
"newState": "ALARM",
"severity": "CRITI | CAL",
"link": "some-link",
"lifecycleState": "OPEN",
"stateChangeReason": "I am alarming!",
"timestamp": 1429023453632,
"metrics": metrics}
class requestsResponse(object):
def __init__(self, status):
self.status_code = status
class TestHipchat(... |
dlab-projects/python-taq | marketflow/dsf_with_sic.py | Python | bsd-2-clause | 887 | 0.036077 | class DSF_SIC_Map(object):
"""docstring for SIC_Map"""
def __init__(self, dsffile = 'crsp/dsf.csv', sicfile = 'sic_codes.txt'):
self.dsf = pd.read_csv("dsf.csv", dtype = {'CUSIP': np.str, 'PRC': np.float}, na_values = {'PRC': '-'})
self.sic = pd.read_table(sicfile, header = 1)
self.sic.c... | ocess(self, day = 20100101, columns = ['PERMNO', 'DATE', 'PRC', 'VOL', 'SHROUT', 'RET', 'HSICCD']):
self.dsf_startdate(date = day)
self.dsf_subset(to_keep = columns)
self.sic_merge()
def dsf_startdate(self, date = 20100101):
self.dsf = self.dsf[self.dsf.DATE >= date]
def dsf_subs... | self.dsf = self.dsf[to_keep]
def sic_merge(self):
self.clean_dsf = self.dsf.merge(self.sic, how = "left") |
strange/django-simple-comments | simple_comments/comments.py | Python | bsd-3-clause | 15,043 | 0.002792 | import datetime
from django import http
from django.conf import settings
from django.forms.models import modelform_factory
from django.shortcuts import get_object_or_404
from django.views.generic.list_detail import object_list
from django.views.generic.simple import direct_to_template
from django.core.urlresolvers imp... | _website']
return exclude
exclude = property(fget=lambda self: self.get_exclude())
def days_since_target_was_published(self, target):
"""Return the number of days that have passed since ``target`` was
published.
"""
now = datetime.datetime.now()
publ... | e(now.year, now.month, now.day) - \
datetime.date(published.year, published.month, published.day)
return diff.days
def allow_comments(self, target):
"""Return a boolean dictating whether comments are allowed for
``target`` or not.
"""
if self.allow_c... |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_rich_string01.py | Python | bsd-2-clause | 1,233 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
sel | f.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
italic = workbook.add_format({'italic': 1})
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.