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 |
|---|---|---|---|---|---|---|---|---|
previtus/MGR-Project-Code | Settings/set1-test_of_models_against_datasets/mix299.py | Python | mit | 1,829 | 0.006014 | def Setup(Settings,DefaultModel):
# set1-test_of_models_against_datasets/osm299.py
Settings["experiment_name"] = "set1_Mix_model_versus_datasets_299px"
Settings["graph_histories"] = ['together'] #['all','together',[],[1,0],[0,0,0],[]]
# 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5... | els"][n]["unique_id"] = 'mix_minlen30_299px'
Settings["models"][n]["top_repeat_FC_block"] = 2
Settings["models"][n]["epochs"] = 800
Settings["models"].append(DefaultModel.copy())
n+=1
Settings["models"][n]["dataset_pointer"] = -1 |
Settings["models"][n]["dataset_name"] = "5556x_reslen20_299px"
Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump'
Settings["models"][n]["pixels"] = 299
Settings["models"][n]["model_type"] = 'img_osm_mix'
Settings["models"][n]["unique_id"] = 'mix_minlen20_299px'
... |
dragondjf/musicplayer | gui/menus/settingsmenu.py | Python | gpl-2.0 | 3,819 | 0.000262 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from gui.dwidgets import DMenu
class SettingsMenu(DMenu):
"""docstring for SettingsMenu"""
def __init__(self, parent=None):
super(SettingsMenu, self).__init__(parent)
self.parent = parent
self.menuItems = [
{
'na... | connect(self.updateChecked)
def updateChecked(self):
for item in ['English', 'Chinese']:
action = getattr(self, '%sAction' % item)
| if self.sender() is action:
action.setChecked(True)
else:
action.setChecked(False)
|
pranjan77/kb_go_express | scripts/prepare_deploy_cfg.py | Python | mit | 2,069 | 0.003867 | import sys
import os
import os.path
from jinja2 import Template
from ConfigParser import ConfigParser
import StringIO
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: <program> <deploy_cfg_template_file> <file_with_properties>")
print("Properties from <file_with_properties> will be a... | point = os.environ.get("KBASE_ENDPOINT")
props = "[global]\n" + \
"kbase_endpoint = " + kbase_endpoint + "\n" + \
"job_service_url = " + kbase_endpoint + "/userandjobstate\n" + \
"workspace_url = " + kbase_endpoint + "/ws\n" + \
"shock_url = " + kb... | \n" + \
"srv_wiz_url = " + kbase_endpoint + "/service_wizard\n" + \
"njsw_url = " + kbase_endpoint + "/njs_wrapper\n"
if "AUTH_SERVICE_URL" in os.environ:
props += "auth_service_url = " + os.environ.get("AUTH_SERVICE_URL") + "\n"
elif "auth2services" in kbase_... |
NicolasT/typeclasses | demo/eq.py | Python | lgpl-2.1 | 1,630 | 0 | # typeclasses, an educational implementation of Haskell-style type
# classes, in Python
#
# Copyright (C) 2010 Nicolas Trangez <eikke eikke com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Fou... |
# MERCHANTABILITY or FITNESS 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 this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#... | rations of the Eq typeclass and its `eq` and `ne` functions'''
from typeclasses.eq import eq, ne
import typeclasses.instances.list
import typeclasses.instances.tuple
from typeclasses.instances.maybe import Just, Nothing
from typeclasses.instances.tree import Branch, Leaf
# List
assert eq([1, 2, 3], [1, 2, 3])
assert... |
glogiotatidis/mozillians-new | vendor-local/lib/python/kombu/tests/transport/test_amqplib.py | Python | bsd-3-clause | 4,458 | 0.000449 | from __future__ import absolute_import
import sys
from kombu.transport import amqplib
from kombu.connection import BrokerConnection
from kombu.tests.utils import TestCase
from kombu.tests.utils import mask_modules, Mock
class MockConnection(dict):
def __setattr__(self, key, value):
self[key] = value
... | test_message_to_python(self):
message = Mock()
message.headers = {}
message.properties = {}
self.assertTrue(self.channel.message_to_python(message))
def test_close_resolves_connection_cycle(self):
self.assertIsNotNone(self.channel.connection)
self.channel.close()
... | tus(self):
self.channel.wait_returns = "my-consumer-tag"
self.channel.basic_consume("foo", no_ack=True)
self.assertIn("my-consumer-tag", self.channel.no_ack_consumers)
self.channel.wait_returns = "other-consumer-tag"
self.channel.basic_consume("bar", no_ack=False)
self.a... |
luozhaoyu/TTTT | outputSlaves.py | Python | mit | 313 | 0.00639 |
#!/usr/bin/pytho | n
# -*- coding: utf-8 -*-
"""
fabfile.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
try:
from config import MACHINES
except ImportError as e:
print "You should cp config.py.sample config.py, a | nd modify it then"
raise e
for node in MACHINES['slave']:
print node
|
gblanchard4/viamics | framework/tools/heatmap.py | Python | gpl-2.0 | 7,248 | 0.009934 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 - 2011, University of New Orleans
#
# 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 o... | ("\t")[1:]
#creating an entry for every bacterium in the abundance file
row_names_non_scaled = []
exprs_non_scaled = []
row_names = []
exprs = []
for line in open(abundance_file).readlines()[1:]:
row_names_non_scaled.append(line.strip().split("\t")[0])
exprs_non_scaled.append(ma... | ):
if sum(exprs_non_scaled[i]) > options.min_percentage and len([x for x in exprs_non_scaled[i] if x > 0.0]) > options.min_present:
if options.log:
exprs.append([math.log10(x + 1) for x in exprs_non_scaled[i]])
row_names.append(row_names_non_scaled[i])
els... |
adriendelsalle/unsysap | unsysap/components_library.py | Python | bsd-2-clause | 4,949 | 0.001819 | from .components_generic import System
from .ports_library import FluidPort, MechPort, CustomPort
class Duct(System):
def __init__(self, name='n/a'):
super().__init__()
self.name = name
self.params['fl_in'] = FluidPort()
self.outputs['fl_out'] = FluidPort()
self.set()
... | uts['fl1_out']
self.set()
self.version = 1.
self.duct.cst_loss = 1.
def run(self):
pass
class DuctComplex(System):
def __init__(self, name='n/a'):
super().__init__()
self.name = name
self.add(Duct('duct'))
self.add(Merger('merger'))
sel... | ams['fl_in'] = self.duct.outputs['fl_out']
self.merger.params['fl2_in'] = self.bleed.outputs['fl2_out']
self.set()
self.version = 1.
self.duct.cst_loss = 1.
def run(self):
pass
|
Hybrid-Cloud/cinder | cinder/volume/drivers/blockbridge.py | Python | apache-2.0 | 21,860 | 0 | # Copyright 2013-2015 Blockbridge Networks, 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 appl... | BlockbridgeISCSIDriver.VERSION),
'Accept': 'application/vnd.blockbridge-3+json',
'Authorization': authz,
},
}
return self._api_cfg
| def submit(self, rel_url, method='GET', params=None, user_id=None,
project_id=None, req_id=None, action=None, **kwargs):
"""Submit a request to the configured API endpoint."""
cfg = self._get_api_cfg()
if cfg is None:
msg = _("Failed to determine blockbridge API conf... |
alexanderfefelov/nav | python/nav/web/navlets/status.py | Python | gpl-2.0 | 3,566 | 0 | #
# Copyright (C) 2013 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV 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.
#
# This program is distributed in the hope... | and no
# preference is set
navlet.preferences = {REFRESH_INTERVAL: self.refresh_interval}
navlet.save()
context['interval'] = navlet.preferences.get(
REFRESH_INTERVAL, self.refresh_inter | val) / 1000
return context
def post(self, request):
"""Save refresh interval for this widget"""
account = get_account(request)
try:
interval = int(request.POST.get('interval')) * 1000
except ValueError:
return HttpResponse(status=400)
try:
... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/eventhubs/tests/latest/test_eventhub_commands_consumergroup_test.py | Python | mit | 3,921 | 0.003826 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | } --eventhub-name {eventhubname} --name {consumergroupname}', checks=[self.check('name', self.kwargs['consumergroupname'])])
# Update ConsumerGroup
self.cmd('eventhubs eventhub consumer-group update --resource-group {rg} --namespace-name {namespacename} --eventhub-name {eventhubname} --name {consumergr... | tadata {usermetadata2}', checks=[self.check('userMetadata', self.kwargs['usermetadata2'])])
# Get ConsumerGroup List
listconsumergroup = self.cmd('eventhubs eventhub consumer-group list --resource-group {rg} --namespace-name {namespacename} --eventhub-name {eventhubname}').output
self.assertGre... |
djangocali/blog-api | blog-api/config/production.py | Python | bsd-3-clause | 4,350 | 0.001839 | # -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use sendgrid to send emails
- Use MEMCACHIER on Heroku
'''
from configurations import values
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings... | heify
from memcacheify import memcacheify
CACHES = memcac | heify()
except ImportError:
CACHES = values.CacheURLValue(default="memcached://127.0.0.1:11211")
# END CACHING
# Your production stuff: Below this line define 3rd party libary settings
|
ymap/aioredis | tests/conftest.py | Python | mit | 22,698 | 0 | import asyncio
import pytest
import socket
import subprocess
import sys
import contextlib
import os
import ssl
import time
import logging
import tempfile
import atexit
from collections import namedtuple
from urllib.parse import urlencode, urlunparse
from async_timeout import timeout as async_timeout
import aioredis
i... | :
conn = conns.pop(0)
conn.close()
waiters.append(conn.wait_closed())
if waiters:
loop.run_until_complete(asyncio.gather(*waiters, loop=loop))
@pytest.fixture(scope='session')
def server(start_server):
"""Starts redis-server instance."""
return start_ser... | ')
@pytest.fixture(scope='session')
def serverB(start_server):
"""Starts redis-server instance."""
return start_server('B')
@pytest.fixture(scope='session')
def sentinel(start_sentinel, request, start_server):
"""Starts redis-sentinel instance with one master -- masterA."""
# Adding master+slave for... |
jwlockhart/concept-networks | examples/draw_tripartite.py | Python | gpl-3.0 | 3,581 | 0.021502 | # @author Jeff Lockhart <jwlock@umich.edu>
# Script for drawing the tripartite network underlying analysis.
# version 1.0
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import sys
#add the parent directory to the current session's path
sys.path.insert(0, '../')
from network_utils import *
#... | s = ['culture_problem',
#'culture_absent',
| 'culture_solution',
'culture_helpless',
'culture_victim',
'cishet_problem',
'cishet_victim',
'cishet_solution',
#'cishet_absent',
'cishet_helpless',
'sgm_victim',
'sgm_problem',
's... |
sputnick-dev/weboob | modules/gdfsuez/pages/homepage.py | Python | agpl-3.0 | 2,508 | 0.001595 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob 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, or
# (at your op... | n) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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 ... | ser import Page
from weboob.capabilities.bill import Subscription
class LoginPage(Page):
def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_... |
intel-analytics/BigDL | python/orca/test/bigdl/orca/learn/test_metrics.py | Python | apache-2.0 | 8,250 | 0.000485 | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
def test_torch_CategoricalAccuracy():
from bigdl.orca.learn.pytorch.pytorch_metrics import | CategoricalAccuracy
pred = torch.tensor([[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
target = torch.tensor([[0, 0, 1], [0, 1, 0]])
cacc = CategoricalAccuracy()
cacc(pred, target)
assert cacc.compute() == 0.5
pred = torch.tensor([[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
target = torch.tensor([[0, 1, 0], [0,... |
priyankamandikal/arowf | backlog.py | Python | apache-2.0 | 3,939 | 0.030972 | # -*- coding: utf-8 -*-
### denote lines that need to be changed for different categories
import sys
reload(sys)
sys.setdefaultencoding("utf-8") # to handle UnicodeDecode errors
from math import ceil # top 20% of rankings
from traceback import format_exc # to handle errors
import pickle # to store art... | load(f)
cnt = 0
counter = int(ceil(0.2*len(od))) # top 20% of rankings
#url = 'http://127.0.0.1:5000/ask' # url for POSTing to ask. Replace with Labs/PythonAnywhere instance if needed
for i in od:
# POSTing to ask
# data = {'question':'The article '+i[1]+' is in https://en.wikipedia.org/wiki/'+i[3]+'.\nH... | fn = recdir + nextrecord() + 'q'
print fn
if path.exists(fn):
print('A billion questions reached! Start answering!')
exit()
f = open(fn, 'w')
# use 'How would you resolve it?' for NPOV and 'How would you update it?' for outdated
f.write('The article <a target="_blank" href="' + i[1] + '">' + i[0] +
... |
egabancho/invenio-knowledge | invenio_knowledge/models.py | Python | gpl-2.0 | 12,573 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2011, 2012, 2014, 2015 CERN.
#
# Invenio 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... | ion,
collection=collection)
@staticmethod
def generate_slug(name):
"""Generate a slug for | the knowledge.
:param name: text to slugify
:return: slugified text
"""
slug = slugify(name)
i = KnwKB.query.filter(db.or_(
KnwKB.slug.like(slug),
KnwKB.slug.like(slug + '-%'),
)).count()
return slug + ('-{0}'.format(i) if i > 0 else '')... |
EduPepperPDTesting/pepper2013-testing | lms/djangoapps/reportlab/graphics/barcode/__init__.py | Python | agpl-3.0 | 5,911 | 0.011673 | #
# Copyright (c) 1996-2000 Tyler C. Sarna <tsarna@sarna.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# not... | VISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
__all__ = tuple('''registerWidget getCodes getCodeNames createBarcodeDrawing createBarcodeImageInMemory'''.split())
__version__ = '0.9'
__doc__='''Popular barcodes available as reusable widgets'''
_widgets = []
def registerWidget(widget):
_widgets.append(widget... | from reportlab.graphics.barcode.widgets import BarcodeI2of5, BarcodeCode128, BarcodeStandard93,\
BarcodeExtended93, BarcodeStandard39, BarcodeExtended39,\
BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM,\
BarcodePOSTNET, BarcodeUSPS_4Sta... |
snehasi/servo | tests/wpt/web-platform-tests/referrer-policy/generic/subresource/subresource.py | Python | mpl-2.0 | 3,167 | 0.011683 | import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... | tloc)
destination_url = urlparse.urlunsplit(urlparse.SplitResult(
scheme = parsed.scheme,
netloc = destination_netloc,
path = parsed.path,
query = None,
fragment = None))
return destination_url
def redirect(url, response):
response.add_required_headers = False
... | low-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.write("")
def preprocess_redirection(request, response):
if "redirection" not in request.GET:
return False
redirection = request.GET["redirection"]
if redirection == "no-redi... |
peteboyd/lammps_interface | lammps_interface/Molecules.py | Python | mit | 18,379 | 0.005985 | """
Molecule class.
"""
import numpy as np
from .water_models import SPC_E_atoms, TIP3P_atoms, TIP4P_atoms, TIP5P_atoms
from .gas_models import EPM2_atoms
from .structure_data import MolecularGraph
import networkx as nx
class Molecule(MolecularGraph):
#TODO(pboyd):add bonding calculations for the atoms in each mo... | line += "%6i %6i # %s\n"%(node, data['ff_type_index'], data['force_field_type'])
line += "\nCharges\n\n"
for node, data in self.nodes_iter2(data=True):
line += "%6i %12.5f\n"%(node, data['charge'])
#TODO(pboyd): add bonding, angles, dihedra | ls, impropers, etc.
if self.number_of_edges():
line += "\nBonds\n\n"
count = 0
for n1, n2, data in self.edges_iter2(data=True):
count += 1
line += "%6i %6i %6i %6i # %s %s\n"%(count, data['ff_type_index'], n1, n2,
... |
pkuhad/django-student | students/urls.py | Python | mit | 684 | 0.010234 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib | import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examp | les:
# url(r'^$', 'students.views.home', name='home'),
# url(r'^students/', include('students.foo.urls')),
# App 'Index Classic'
url(r"^index_classic/", include('students.index_classic.urls'), name="index_classic"),
# Uncomment the admin/doc line below to enable admin documentation:
# url(... |
jeffamstutz/rfManta | scenes/csafe/CMake/make2cmake.py | Python | mit | 768 | 0.011719 | #!/usr/bin/python
import os,sys,string
if __name__ == "__main__":
# Check the argument list size
if (len(sys.argv) < 3):
sys.stderr.write("USAGE: " + sys.argv[0] + " <input file> <output file>\n")
sys.exit(1)
infilename = sys.argv[1]
outfilename = sys.argv[2]
# U is the mode to ... | name, "w")
# Now read the lines
lines = map( lambda x: string.strip(x, string.whitespace+"\\"),
infile.readlines() )
infile.close( | )
# Now write them
outfile.write("SET( MANTA_SWIG_DEPEND\n")
for l in lines[1:]:
outfile.write(l + "\n")
outfile.write(")\n")
outfile.close()
|
yunstanford/sanic | examples/request_stream/server.py | Python | mit | 1,683 | 0 | from sanic import Sanic
from sanic.views import Compo | sitionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text
bp = Blueprint('blueprint_request_stream')
app = Sanic('request_stream')
class SimpleView(HTTPMethodView):
@stream_decorator
asy... | request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
@app.post('/stream', stream=True)
async def handler(request):
async def streaming(response):
while True:
body = await request.stream.get()
... |
jinankjain/zamboni | mkt/collections/tests/test_authorization.py | Python | bsd-3-clause | 8,106 | 0.00037 | import json
from urllib import urlencode
from nose.tools import ok_
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.settings import api_settings
from access.middleware import ACLMiddleware
from amo.tests import TestCase
from users.models import UserPro... | or()
ok_(not self.is_authorized_object(self.request('DELETE')))
def test_delete_detail_permission_curator(self):
self.give_permission()
self.make_curator()
ok_(self.is_authorized_ob | ject(self.request('DELETE')))
class TestStrictCuratorAuthorization(TestCuratorAuthorization):
auth_class = StrictCuratorAuthorization
def test_get_list(self):
ok_(not self.is_authorized(self.request('GET')))
def test_get_detail(self):
ok_(not self.is_authorized_object(self.request('GET')... |
mrmookie/btcrecover | make-unicode.py | Python | gpl-2.0 | 4,149 | 0.002651 | #!/usr/bin/python
# make-unicode.py -- build the Unicode version of btcrecover from the ASCII version
# Copyright (C) 2014, 2015 Christopher Gurnee
#
# This file is part of btcrecover.
#
# btcrecover is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as pub... | o_pause:
atexit.regist | er(lambda: raw_input("\nPress Enter to exit ..."))
# Build the Unicode versions of btcrecover and the test-btcr test suite
modified1 = make_unicode_version("btcrecover.py", "btcrecoveru.py")
modified2 = make_unicode_version("test-btcr.py", "test-btcru.py")
if not modified1 and not modified2:
p... |
jgrasser/pyRussianSquare | russianSquare.py | Python | gpl-2.0 | 27,299 | 0.0211 | # RussianSquare - Tetris like block game
# Copyright (C) 2011 Joseph Grasser
#
# 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 optio... | -----------------------------------------------------#
def load_alphabet(alphabet_file, charwidth, charheight):
letterImage = pygame.image.load( alphabet_file )
letters = []
height = letterImage.get_height()
width = letterImage.get_width()
x = 0
y = 0
while y+charheight < height and x ... | letters.append( letterImage.subsurface(pygame.Rect(x, y, charwidth, charheight) ) )
y = y + charheight
return letters
def big_Alpha():
char_width = 32
char_height = 40
alpha = load_alphabet(os.path.join('data', 'abcdefghijkl_big.tga' ), char_width, char_height)
alpha.extend( lo... |
Jaymebb/MIE | MIE/UTILS/quickumls.py | Python | mit | 10,762 | 0.000093 | # future statements for Python 2 compatibility
from __future__ import (
unicode_literals, division, print_function, absolute_import)
# built in modules
import os
import sys
import datetime
# installed modules
import spacy
from unidecode import unidecode
# project modules
try:
import toolbox
import consta... | rcased
# in the step above
if not self.to_lowercase_flag and ngram_normalized.isupper():
ngram_normalized = ngram_normalized.lower()
prev_cui = None
| ngram_cands = list(self.ss_db.get(ngram_normalized))
ngram_matches = []
for match in ngram_cands:
cuisem_match = sorted(self.cuisem_db.get(match))
for cui, semtypes, preferred in cuisem_match:
match_similarity = toolbox.get_similar... |
Yajo/maintainer-tools | template/module/tests/test_something.py | Python | agpl-3.0 | 1,454 | 0 | # Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL- | 3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).s | etUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(So... |
StupidTortoise/personal | python/oracle_test.py | Python | gpl-2.0 | 1,079 | 0.016684 | # -*- coding: utf-8 -*-
import cx_Oracle
db = cx_Oracle.connect("username", "password", "10.17.1.220:1521/db")
cursor = db.cursor()
cursor.execute("select loginid from sys_user")
for loginid in cursor:
print("loginid: ", loginid)
cursor.close()
cursor = db.cursor()
#插入一条记录
cursor.execute("""insert into tb_user ... | e(6, 11): # [6,7,8,9,10]
param.append((i, 'user | ' + str(i), 'password' + str(i)))
#插入数据
cursor.executemany('insert into tb_user values(:1,:2,:3)', param);
cursor.close()
db.commit()
db.close()
|
pombredanne/neomodel | neomodel/cardinality.py | Python | mit | 2,569 | 0.001557 | from .relationship_manager import RelationshipManager, ZeroOrMore # noqa
class ZeroOrOne(RelationshipManager):
description = "zero or one relationship"
def single(self):
nodes = super(ZeroOrOne, self).all()
if len(nodes) == 1:
return nodes[0]
if len(nodes) > 1:
... | tion("Cardinality one, cannot disconnect use reconnect")
def connect(self, obj, properties=None):
if not hasattr(self.source, '_id'):
raise ValueError("Node has not been saved cannot connect!")
if len(self):
raise AttemptedCardinalityViolation("Node already has one relations... | :
def __init__(self, rel_manager, actual):
self.rel_manager = str(rel_manager)
self.actual = str(actual)
def __str__(self):
return "CardinalityViolation: Expected {0} got {1}".format(self.rel_manager, self.actual)
|
mountainstorm/urwid | urwid/container.py | Python | lgpl-2.1 | 84,566 | 0.002814 | #!/usr/bin/python
#
# Urwid container widget classes
# Copyright (C) 2004-2012 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Licen... | widget and proceeding along newly focused child widgets. Any
failed assignment due do incompatible position types or invalid
positions will raise an IndexError.
This method may be used to restore a particular widget to the
focus by passing in the value returned from an earlier call ... | """
w = self
for p in positions:
if p != w.focus_position:
w.focus_position = p # modifies w.focus
w = w.focus.base_widget
def get_focus_widgets(self):
"""
Return the .focus values starting from this container
and proceeding along each... |
jihunhamm/Crowd-ML | client/python/loss_nndemo1.py | Python | apache-2.0 | 3,849 | 0.030657 | import numpy as np
from scipy.optimize import check_grad
## Two-layer NN with ReLU
# Tw | o-layer NN, with 200 units per layer | with ReLu ai = max(0,oi)
# X - (W01) - Layer1 - (W12) - Layer2 - (W23) - Output
# ((D+1)*nh) + ((nh+1)*nh) + ((nh+1)*K)
nh = 200
def getAvgGradient(w, X, y, L, K):
[N,D] = X.shape
W01,b1,W12,b2,W23,b3 = parseParams(w,D,K)
# Forward pass
h1 = np.maximum(0, np.dot(X, W01) + np.tile(b1,(N,1))) # N... |
boskee/simplui | setup.py | Python | bsd-3-clause | 803 | 0.05604 | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = 'simplui',
version = '1.0.4',
author = 'Tristam MacDonald',
author_email = 'swiftcoder@gmail.com',
description = 'Light-weigh | t GUI toolkit for pyglet',
url = 'http://simplui.goog | lecode.com/',
platforms = ['all'],
license = 'BSD',
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Scient... |
bobintetley/asm3 | import/org/org_sb1875.py | Python | gpl-3.0 | 11,412 | 0.004118 | #!/usr/bin/python
import asm
"""
Import script for sb1875 csv files
1st March, 2019
"""
START_ID = 1000
ANIMAL_FILENAME = "/home/robin/tmp/asm3_import_data/sb1875_csv/ASM_Animal_Master.csv"
LOG_FILENAME = "/home/robin/tmp/asm3_import_data/sb1875_csv/ASM_Animal_Log.csv"
PERSON_FILENAME = "/home/robin/tmp/asm3_impor... | ments = d["PERSONCOMMENTS"]
o.JurisdictionID = asm.jurisdiction_from_db(d["PERSONADDITIONALCOUNCILNAME"])
# Animal intake records
for d in asm.csv_to_list(ANIMAL_FILENAME, remove_non_ascii=True):
# Each row contains an animal with intake info:
a = asm.Animal()
animals.append(a)
ppa[d["Animal_Ident | ifier"]] = a
a.AnimalTypeID = asm.type_from_db(d["Pound_Reason"])
a.SpeciesID = asm.species_id_for_name(d["Species"])
a.AnimalName = d["Name"]
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
a.DateBroughtIn = getdate(d["Date_Admitted"]) or asm.today()
if d["Date_Of_Birth"].stri... |
dantebarba/docker-media-server | plex/Subliminal.bundle/Contents/Code/logger.py | Python | gpl-3.0 | 1,288 | 0.004658 | import logging
def registerLoggingHander(dependencies):
plexHandler = PlexLoggerHandler()
for dependency in dependencies:
Log.Debug("Registering LoggerHandler for | dependency: %s" % dependency)
log = logging.getLogger(dependency)
log.setLevel('DEBUG')
log.addHandler(plexHandler)
class PlexLoggerHandler(logging.StreamHandler):
def __init__(self, level=0):
super(PlexLoggerHandler, self).__init__(level)
def getF | ormattedString(self, record):
return record.name + ": " + record.getMessage()
def emit(self, record):
if record.levelno == logging.DEBUG:
Log.Debug(self.getFormattedString(record))
elif record.levelno == logging.INFO:
Log.Info(self.getFormattedString(record))
... |
Luiti/etl_utils | etl_utils/list_utils.py | Python | mit | 1,250 | 0.0016 | # -*- coding: utf-8 -*-
from collections import Counter
from .design_pattern import singleton
@singleton()
class ListUtilsClass(object):
def most_common_inspect(self, list1):
new_list = []
for s1 in list1:
if not isinstance(s1, unicode):
s1 = str(s1).decode("UTF-8")
... | one):
if uniq_lambda is None:
return list(set(seqs))
__uniq = set([])
__remove_idxes = []
for idx1, seq1 in enumerate(seqs[:]):
__id = uniq_lambda(seq1)
if __id in __uniq:
__remove_idxes.append(idx1)
else:
... | _id)
new_seqs = []
for idx1, seq1 in enumerate(seqs[:]):
if idx1 not in __remove_idxes:
new_seqs.append(seq1)
seqs = new_seqs
return seqs
ListUtils = ListUtilsClass()
uniq_seqs = ListUtils.uniq_seqs
|
awood/orbach | orbach/core/urls.py | Python | gpl-3.0 | 1,005 | 0 | '''
Copyright 2015
This file is part of Orbach.
Orbach 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.
Orbach is distributed in the hope t... | 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 Orbach. If not, see <http://www.gnu.org/licenses/>.
'''
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from orbach.core import views
router = DefaultRouter()
router.register(r'galleries', views.GalleryViewSet)
router.regis... |
ibobalo/python-for-android | pythonforandroid/recipes/twisted/__init__.py | Python | mit | 1,038 | 0.000963 |
import glob
from pythonforandroid.toolchain import (
CythonRecipe,
Recipe,
current_directory,
info,
shprint,
)
from os.path import join
import sh
class TwistedRecipe(CythonRecipe):
version = '17.9.0'
url = 'https://github.com/twisted/twisted/archive/twisted-{version}.tar.gz'
depends ... | e', 'incremental', 'constantly']
call_hostpython_via_targetpython = False
in | stall_in_hostpython = True
def prebuild_arch(self, arch):
super(TwistedRecipe, self).prebuild_arch(arch)
# TODO Need to whitelist tty.pyo and termios.so here
print('Should remove twisted tests etc. here, but skipping for now')
def get_recipe_env(self, arch):
env = super(Twisted... |
portnov/sverchok | tests/cubic_spline_tests.py | Python | gpl-3.0 | 1,513 | 0.017845 |
import numpy as np
from sverchok.utils.testing import *
from sverchok.utils.logging import debug, info
from sverchok.utils.geom import CubicSpline
class CubicSplineTests(SverchokTestCase):
def setUp(self):
super().setUp()
vertices = [(-1, -1, 0), (0, 0, 0), (1, 2, 0), (2, 3, 0)]
self.spli... | [[-1.0, -1.0, 0.0 ],
[-0.60984526, -0.66497986, 0.0 ],
[ 0.29660356, 0.5303721, 0.0 ],
[ 0.5, 1.0, 0.0 ],
[ 0.94256655, 1.91347161, 0.0 ],
[ 2.0, 3.0, 0.0 ]])
| self.assert_numpy_arrays_equal(result, expected_result, precision=8)
def test_tangent(self):
t_in = np.array([0.0, 0.1, 0.4, 0.5, 0.7, 1.0])
result = self.spline.tangent(t_in)
#info(result)
expected_result = np.array(
[[ 0.00789736, 0.00663246, 0.0 ],
... |
PhilippMundhenk/IVNS | ECUSimulation/components/base/ecu/types/abst_ecu.py | Python | mit | 5,802 | 0.018614 | from components.base.automotive_component import AutomotiveComponent
from config import project_registration as proj
from tools.ecu_logging import ECULogger as L
import random
class AbstractECU(AutomotiveComponent):
'''
This abstract class defines the interface of
an E | CU as it is found in an automotive network
'''
def __init__(self, sim_env, ecu_id, data_rate):
''' Constructor
Input: sim_env simpy.Environment environment of this | component
ecu_id string id of the corresponding AbstractECU
data_rate float datarate of the ecu
Output: -
'''
AutomotiveComponent.__init__(self, sim_env)
self._ABSTRACT_ECU = True
... |
tomasy23/evertonkrosnodart | tools/export/blender25/io_scene_dae/__init__.py | Python | mit | 6,444 | 0.006518 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | , ExportHelper):
'''Selection to DAE'''
bl_idname = "export_scene.dae"
bl_label = "Export DAE"
bl_options = {'PRESET'}
filename_ext = ".dae"
filter_glob = StringProperty(default="*.dae", options={' | HIDDEN'})
# List of operator properties, the attributes will be assigned
# to the class instance from the operator settings before calling.
object_types = EnumProperty(
name="Object Types",
options={'ENUM_FLAG'},
items=(('EMPTY', "Empty", ""),
('C... |
pvdheijden/OpenCaster | libs/dvbobjects/dvbobjects/PSI/UNT.py | Python | gpl-2.0 | 2,864 | 0.013268 | #! /usr/bin/env python
# This file is part of the dvbobjects library.
#
# Copyright 2009-2013 Lorenzo Pallara l.pallara@avalpa.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 vers... | "")
# pack compatibility_descriptor_loop
compatibility_bytes = string.join(
map(lambda x: x.pack(),
self.compatibility_descriptor_loop),
"")
fmt = "!HBBH%ds%ds" % (len(common_bytes), len(compatibility_bytes))
return pack(fmt,
self.OUI ... | )
######################################################################
class unt_compatibility_descriptor_loop_item(DVBobject):
def pack(self):
# pack target_descriptor_loop
tdl_bytes = string.join(
map(lambda x: x.pack(),
self.target_descriptor_loop),... |
Kunalpod/codewars | is_this_a_triangle.py | Python | mit | 163 | 0.042945 | #Kunal Gautam
#Codewars | : @Kunal | pod
#Problem name: Is this a triangle?
#Problem level: 7 kyu
def is_triangle(a, b, c):
return (a+b>c) and (b+c>a) and (c+a>b)
|
linea-it/dri | api/product/admin.py | Python | gpl-3.0 | 5,841 | 0.002226 | from django.contrib import admin
from .models import *
class ProductAdmin(admin.ModelAdmin):
list_display = ('id', 'prd_process_id', 'prd_name',
'prd_display_name', 'prd_owner', 'prd_product_id', 'prd_date',
'prd_class', 'prd_filter', 'prd_is_public', 'prd_is_permanent',)
... | ,)
class ProductContentAssociationAdmin(admin.ModelAdmin):
list_display = ('id', 'pca_product', 'pca_class_content', 'pca_product_content',)
search_fields = (' | pca_product__prd_display_name', 'pca_product__prd_name')
class ProductContentSettingAdmin(admin.ModelAdmin):
list_display = ('id', 'pcs_content', 'pcs_setting', 'pcs_is_visible', 'pcs_order')
class ProductSettingAdmin(admin.ModelAdmin):
list_display = (
'id', 'cst_product', 'owner', 'cst_display_nam... |
pczhaoyun/wolf | wolf/spiders/wolves/cnscg.py | Python | apache-2.0 | 1,092 | 0.003663 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import r | e
import urlparse
from scrapy import log
from scrapy.http import Request
from base.base_wolf import Base_Wolf
class Wolf(Base_Wolf):
def __init__(self, *args, **kwargs):
super(Wolf, self).__init__(*args, **kwargs)
self.name = 'cnscg'
self.see | d_urls = [
'http://www.cnscg.org/',
]
self.base_url = 'http://www.cnscg.org/'
self.rule['follow'] = re.compile(r'show-')
self.anchor['desc'] = "//*[@class='intro']"
def get_resource(self, item, response, tree):
item = super(Wolf, self).get_resource(item, response... |
michaelBenin/django-oscar | setup.py | Python | bsd-3-clause | 3,934 | 0.001017 | #!/usr/bin/env python
"""
Installation script:
To release | a new version to PyPi:
- Ensure the version is correctly set in oscar.__init__.py
- Run: python setup.py sdist upload
"""
from setuptools import setup, find_packages
import os
import sys
fr | om oscar import get_version
PROJECT_DIR = os.path.dirname(__file__)
# Change to the current directory to solve an issue installing Oscar on the
# Vagrant machine.
if PROJECT_DIR:
os.chdir(PROJECT_DIR)
setup(name='django-oscar',
version=get_version().replace(' ', '-'),
url='https://github.com/tangentl... |
Laurawly/tvm-1 | python/tvm/relay/op/contrib/ethosu.py | Python | apache-2.0 | 42,334 | 0.001819 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ependency using your Python package manager."
) from None
return func(*args, **kwargs)
return wrapper
class TensorParams:
"""
This class will parse a tvm Expr along with quantization scale
and zero point to populate parameters that are required
for the creation of tensors in V... | def __init__(self, tensor, layout=None, scale=None, zero_point=None):
self.tensor = tensor
if isinstance(tensor, Constant):
self.values = tensor.data.asnumpy()
else:
self.values = None
self.dtype = tensor.checked_type.dtype
self.shape = [int(i) for i in... |
pyGBot/pyGBot | pyGBot/Plugins/system/CommandSpec/Seen.py | Python | gpl-3.0 | 3,387 | 0.004724 | ##
## pyGBot - Versatile IRC Bot
## Copyright (C) 2008 Morgan Lokhorst-Blight, Alex Soborov
##
## 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, ... | ick, searchChannel)
except IndexError, e:
bot.replyout(channel, user, str(e))
return
outmessage = "The user, %s, was last seen " % event.user
if event.channel:
outmessage += "on channel %s " % event.channel
else:
outmessage += "on this net... | stseen.seconds / 3600
minutes = (lastseen.seconds % 3600) / 60
seconds = lastseen.seconds % 60
timemessage = []
if days != 0:
timemessage.append("%i days" % days)
if hours != 0:
timemessage.append("%i hours" % hours)
if minutes != 0:
t... |
behconsci/sniffets-python | setup.py | Python | mit | 749 | 0.001335 | try:
from setuptools import setup
except ImportError:
from distutils.c | ore import setup
try:
with open('README.rst') as file:
long_description = file.read()
except IOError:
long_description = 'Python lib for sniffets.com'
setup(
name='sniffets',
packages=['sniffets'],
version='0.1.8',
long_description=long_description,
description='Python lib for snif... | ci/sniffets-python/archive/0.1.8.tar.gz',
keywords=['track', 'monitor', 'bug'],
classifiers=[],
install_requires=[
'requests', 'grequests'
],
)
|
estin/pomp | pomp/contrib/concurrenttools.py | Python | bsd-3-clause | 5,193 | 0 | """
Concurrent downloaders
"""
import os
import sys
import signal
import logging
import itertools
from functools import partial
from concurrent.futures import ProcessPoolExecutor
from pomp.core.base import (
BaseCrawler, BaseDownloader, BaseCrawlException,
)
from pomp.contrib.urllibtools import UrllibDownloadWorke... | omp.contrib.concurrent')
def _run_download_worker(params, request):
pid = os.getpid()
log.debug("Download worker pid=%s params=%s", pid, params)
try:
# Initialize worker and call get_one method
return params['worker_class'](
**params.get('worker_kwargs', {})
).process(r... | (
"Exception on download worker pid=%s request=%s", pid, request
)
raise
def _run_crawler_worker(params, response):
pid = os.getpid()
log.debug("Crawler worker pid=%s params=%s", pid, params)
try:
# Initialize crawler worker
worker = params['worker_class'](**par... |
Paul-St-Young/solid_hydrogen | qharv_db/dpmd_train.py | Python | mit | 2,815 | 0.013144 | def descriptor(rcut=4, desc_type='se_ar', mneiba=150):
smth_frac = 0.85
if desc_type == 'se_ar':
rmult = 1.5
mneibr = 500
ar_smth = rcut*smth_frac
desc = {
'type': 'se_ar',
'a': {
'sel': [mneiba],
'rcut_smth': ar_smth,
'rcut': rcut,
'neuron': [10, 20, 40],... | }
elif desc_type == 'se_a':
desc = {
'type': 'se_a',
'sel': [mneiba],
'rcut_smth': rcut*smth_frac,
'rcut': rcut,
'neuron': [16, 32, 64],
'resnet_dt': False,
'axis_neuron': 4,
'seed': 1,
}
else:
msg = 'please add inputs for descriptor type %s' % desc_typ... | e,
'seed': 1
}
return fn
def loss_function():
loss = {
'start_pref_e': 0.02,
'limit_pref_e': 1,
'start_pref_f': 1000,
'limit_pref_f': 1,
'start_pref_v': 1000,
'limit_pref_v': 1
}
return loss
def calc_decay_steps(stop_batch, start_lr, stop_lr, decay_rate):
import numpy as np
d... |
ziwenxie/netease-dl | netease/weapi.py | Python | mit | 14,637 | 0.000273 | # -*- coding: utf-8 -*-
"""
netease-dl.weapi
~~~~~~~~~~~~~~~~
This module provides a Crawler class to get NetEase Music API.
"""
import re
import hashlib
import os
import sys
import click
import requests
from requests.exceptions import RequestException, Timeout, ProxyError
from requests.exceptions import ConnectionE... | ally select the best one.
:params limit: playlist count returned by weapi.
| :return: a Playlist object.
"""
result = self.search(playlist_name, search_type=1000, limit=limit)
if result['result']['playlistCount'] <= 0:
LOG.warning('Playlist %s not existed!', playlist_name)
raise SearchNotFound('playlist {} not existed'.format(playlist_nam... |
FrancescElies/bquery | bquery/benchmarks/bench_groupby.py | Python | bsd-3-clause | 2,373 | 0.000421 | from __future__ import print_function
# bench related imports
import numpy as np
import shutil
import bquery
import pandas as pd
import itertools as itt
import cytoolz
import cytoolz.dicttoolz
from toolz import valmap, compose
from cytoolz.curried import pluck
import blaze as blz
# other imports
import contextlib
impor... | elapsed/t_pa | ndas, 2)))
print(result)
# -- blaze + bcolz --
blaze_data = blz.Data(ct.rootdir)
expr = blz.by(blaze_data.f0, sum_f2=blaze_data.f2.sum())
with ctime(message='blaze over bcolz'):
result = blz.compute(expr)
print('x{0} slower than pandas'.format(round(t_elapsed/t_pandas, 2)))
print(result)
# -- bquery --
with ctime... |
sheeshmohsin/shopping_site | app/cart/urls.py | Python | mit | 546 | 0.007326 | from django.conf.urls import patterns, include, url
from | django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^add/$', 'cart.views.add'),
url(r'^clear/$... | art.views.checkout'),
)
|
robotics-silver-surfer/surfer-main | lab3/hoverboard/src/hoverboard/msg/_ServoRaw.py | Python | mit | 5,572 | 0.018844 | """autogenerated by genpy from hoverboard/ServoRaw.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class ServoRaw(genpy.Message):
_md5sum = "cf1c9d17f7bbedbe8dd2c29cdb7700f8"
_type = "hoverboard/ServoRaw"
_has_header = True ... | frame_id
"""
__slots__ = | ['header','port','value']
_slot_types = ['std_msgs/Header','int8','int8']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future messa... |
mstepniowski/simpledb | search.py | Python | bsd-2-clause | 2,080 | 0.001923 | import sys
import struct
ULL_BYTES = struct.calcsize('!Q')
SHORT_BYTES = struct.calcsize('!h')
INDEX_HEADER = 'IDX'
def search(dbfile, prefix):
"""Returns all words having a given prefix using a dbfile."""
idx = Index.from_file(dbfile)
for letter in prefix:
if letter not in idx.nodes:
... | '
for path in idx.leafs:
print ' - ' + path
class Index(object):
def __init__(self, data):
self.data = data
self.no | des = {}
self.leafs = []
self.parse()
@classmethod
def from_file(self, f, offset=0):
f.seek(offset)
size_data = f.read(len(INDEX_HEADER) + ULL_BYTES)
header, index_size = struct.unpack('!%dsQ' % len(INDEX_HEADER), size_data)
if header != INDEX_HEADER:
... |
DavideCanton/Python3 | audio/freq.py | Python | gpl-3.0 | 663 | 0.001508 | import numpy as np
import struct
import wave
from winso | und import PlaySound, SND_FILENAME, SND_ASYNC
import matplotlib.pyplot as plt
CHUNK = 1 << 8
def play(filename):
PlaySound(filename, SND_FILENAME | SND_ASYNC)
fn = r"D:\b.wav"
f = wave.open(fn)
print(f.getparams())
ch = f.getnchannels() |
sw = f.getsampwidth()
n = f.getnframes()
data = bytearray()
while len(data) < n * ch * sw:
data.extend(f.readframes(CHUNK))
data = np.array(struct.unpack('{n}h'.format(n=n * ch), data))
w = np.fft.fft(data)
freqs = np.fft.fftfreq(len(w))
module = np.abs(w)
idmax = module.argmax()
print(abs(freqs[idmax]) * f.get... |
dennisobrien/bokeh | bokeh/sampledata/tests/test_commits.py | Python | bsd-3-clause | 1,961 | 0.010199 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | --------------------------------
# Standard library imports
# External imports
# Bokeh imports
from bokeh._testing.util.api import verify_all
# Module under test
#import bokeh.sampledata.commits as bsc
#-----------------------------------------------------------------------------
# Setup
#-------------------------... | -----
ALL = (
'data',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
Test___all__ = pytest.mark.sampledata(verify_all("bokeh.sampledata.commits", ALL))
@pytest.mark.sampledata
def test_... |
khchine5/book | lino_book/projects/homeworkschool/__init__.py | Python | bsd-2-clause | 254 | 0 | # -*- coding: UTF-8 -*-
__copyright__ = """\
Copyright (c) 2012-2013 Luc Saffre.
This software comes with ABSOLUTELY NO WARRANTY and is
distributed under the terms of the GNU L | esser General Public License.
See file COPYING.txt f | or more information."""
|
tikan/rmock | src/rmock/runners/http/proxy/handler.py | Python | lgpl-3.0 | 2,108 | 0.004744 | # coding=utf8
#
# Copyright 2013 Dreamlab Onet.pl
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 3.0.
# This library is distributed in the hope that it will be useful,
# bu... | er
from rmock.runners.http.handler import with_exception_handling
from rmock.core.call import Call
from rmock.runners.http.handler import HttpCode
logger = logging.getLogger("rmock.http-proxy")
class ProxyMockHttpHandler(MockHttpHandler):
@with_exception_handling
def initi | alize(self,
rmock_data,
protocol_class,
protocol_args,
slug,
childs,
child_chooser):
super(ProxyMockHttpHandler, self).initialize(
rmock_data,
protocol_class,
... |
BlackstoneEngineering/yotta | yotta/test/ignores.py | Python | apache-2.0 | 6,131 | 0.008481 | #!/usr/bin/env python
# Copyright 2015 AR | M Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import unittest
import os
import tempfile
# internal modules:
from yotta.lib.fsutil | s import mkDirP, rmRf
from yotta.lib.detect import systemDefaultTarget
from yotta.lib import component
from .cli import cli
Test_Files = {
'.yotta_ignore': '''
#comment
/moo
b/c/d
b/c/*.txt
/a/b/test.txt
b/*.c
/source/a/b/test.txt
/test/foo
sometest/a
someothertest
ignoredbyfname.c
''',
'module.json': '''
{
... |
jobovy/apogee-maps | py/define_rgbsample.py | Python | bsd-3-clause | 20,638 | 0.02413 | import math
import numpy
import statsmodels.api as sm
lowess= sm.nonparametric.lowess
import esutil
from galpy.util import bovy_coords, bovy_plot
from scipy.interpolate import interp1d,UnivariateSpline
import apogee.tools.read as apread
import isodist
import numpy as np
import matplotlib.pyplot as plt
import os
import ... | _lowlow_highafe(feh):
# The high alpha edge (-0.15,0.075) to (-0.5,0.15)
return (0.15-0.075)/(-0.5--0.15)*(feh+0.1--0.15)+0.075
def get_lowlowsample():
"""
NAME:
get_lowlowsample
PURP | OSE:
get the RGB sample at low alpha, low iron
INPUT:
None so far
OUTPUT:
sample
HISTORY:
2015-03-18 - Started - Bovy (IAS)
2016-07-02 - modification - Mackereth (LJMU)
"""
# Get the full sample first
data= get_rgbsample()
# Now cut it
lowfeh= _lowlow_l... |
mtils/ems | ems/resource/dict_attribute_repository.py | Python | mit | 1,547 | 0.001939 |
from ems.typehint import accepts
from ems.resource.repository import Repository
class DictAttributeRepository(Repository):
@accepts(Repository)
def __init__(self, sourceRepo, sourceAttribute='data'):
self._sourceRepo = sourceRepo
self.sourceAttribute = sourceAttribute
def get(self, id_):... | es, obj=None):
"""
Store a new object. Create on if non passed, if one passed store the
passed one
: | returns: object
"""
if obj:
raise TypeError("Obj has to be None")
sourceAttributes = {self.sourceAttribute:self.new(attributes)}
if 'ID' not in sourceAttributes:
raise KeyError("attributes have to contain ")
model = self._sourceRepo.store(sourceAttribut... |
jansohn/pyload | module/plugins/accounts/ShareonlineBiz.py | Python | gpl-3.0 | 2,110 | 0.010427 | # -*- coding: utf-8 -*-
import re
from module.plugins.internal.Account import Account
from module.plugins.internal.Plugin import set_cookie
class ShareonlineBiz(Account):
__name__ = "ShareonlineBiz"
__type__ = "account"
__version__ = "0.41"
__status__ = "testing"
__description__ = """Sha... | premium = False
va | liduntil = None
trafficleft = -1
maxtraffic = 100 * 1024 * 1024 * 1024 #: 100 GB
api = self.api_response(user, password)
premium = api['group'] in ("PrePaid", "Premium", "Penalty-Premium")
validuntil = float(api['expire_date'])
traffic = float(api['traffic_1d']... |
gautampanday/nereid-webshop | tests/test_css.py | Python | bsd-3-clause | 1,062 | 0.000942 | # -*- coding: utf-8 -*-
"""
CSS Testing
:copyright: (C) 2014 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
from os.path import join
from cssutils import CSSParser
import unittest
import trytond | .tests.test_tryton
dir = 'static/css/'
class CSSTest(unittest.TestCase):
"""
Test case for CSS.
| """
def validate(self, filename):
"""
Uses cssutils to validate a css file.
Prints output using a logger.
"""
CSSParser(raiseExceptions=True).parseFile(filename, validate=True)
def test_css(self):
"""
Test for CSS validation using W3C standards.
... |
CredoReference/edx-platform | common/djangoapps/third_party_auth/pipeline.py | Python | agpl-3.0 | 35,110 | 0.003019 | """Auth pipeline definitions.
Auth pipelines handle the process of authenticating a user. They involve a
consumer system and a provider service. The general pattern is:
1. The consumer system exposes a URL endpoint that starts the process.
2. When a user visits that URL, the client system redirects the user t... | = getattr(settings, 'THIRD_PARTY_AUTH_CUSTOM_AUTH_FORMS', {})
def is_api(auth_entry):
"""Returns whether the auth entry point is via an API call."""
return (auth_entry == AUTH_ENTRY_LOGIN_API) or (auth_entry == AUTH_ENTRY_REGISTER_API)
# URLs associated with auth entry points
# These are used to request addi... | n the provider's login page).
# We don't use "reverse" here because doing so may cause modules
# to load that depend on this module.
AUTH_DISPATCH_URLS = {
AUTH_ENTRY_LOGIN: '/login',
AUTH_ENTRY_REGISTER: '/register',
AUTH_ENTRY_ACCOUNT_SETTINGS: '/account/settings',
}
_AUTH_ENTRY_CHOICES = frozenset([
... |
aurora-pro/apex-sigma | sigma/plugins/fun/cyanideandhappiness.py | Python | gpl-3.0 | 720 | 0.001393 | import discord
import random
import aiohttp
from lxml import html | as l
async def cyanideandhappiness(cmd, message, args):
comic_number = random.randint(1, 4562)
comic_url = f'http://explosm.net/comics/{comic_number}/'
async with aiohttp.ClientSession() as session:
async with session.get(comic_url) as data:
page = await data.text()
root = l.fromst... | = comic_element[0].attrib['src']
if comic_img_url.startswith('//'):
comic_img_url = 'https:' + comic_img_url
embed = discord.Embed(color=0x1ABC9C)
embed.set_image(url=comic_img_url)
await message.channel.send(None, embed=embed)
|
ftp21/BoilerPi | server.py | Python | gpl-3.0 | 3,260 | 0.010123 | import multiprocessing
import socket
import re
import time
def handle(connection, address):
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("process-%r" % (address,))
try:
logger.debug("Connected %r at %r", connection, address)
while True:
d... | self.socket.listen(1)
while True:
conn, address = self.socket.accept()
self.logger.debug("Got co | nnection")
process = multiprocessing.Process(target=handle, args=(conn, address))
process.daemon = True
process.start()
self.logger.debug("Started process %r", process)
def getTemp():
return 18
def checkTemp():
logging.info("Start checktemp")
stat... |
OCA/stock-logistics-warehouse | stock_measuring_device_zippcube/models/__init__.py | Python | agpl-3.0 | 131 | 0 | # Copyright 2021 Camptocamp SA
# Licen | se AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from . import | measuring_device
|
Indmind/Jomblo-Story | module/loading.py | Python | mit | 442 | 0.00905 | import time
import sys
def createDots(length, delay):
for i in range(length):
print('.', end='')
sys.stdout.flush()
time.sleep(delay)
def createHash(l | ength, delay):
for i in range(length):
print('#', end='')
sys.stdout.flush()
time.sleep(delay)
def createVrDots(length, delay):
for i in range(length):
print('.')
time.sl | eep(delay)
def deGa():
time.sleep(.3)
|
willu47/SALib | tests/test_ff.py | Python | mit | 6,285 | 0.004455 | '''
Created on 30 Jun 2015
@author: @willu47
'''
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from SALib.sample.ff import sample, find_smallest, extend_bounds
from SALib.analyze.ff import analyze, interactions
def test_find_smallest():
'''
'''
num_vars = [1, 2, 3, 4, 5, 6, 7... | np.array([-1, 1]), np.array([-1, 1]),
np.array([-1, 1]), np.array([-1, 1]),
np.array([-1, 1]), np.array([-1, 1]),
np.array([-1, 1]), np.array([-1, 1]),
np.array([0, 1]), np.array([0, ... | np.array([0, 1]), np.array([0, 1])],
'num_vars': 16}
assert_equal(actual, expected)
def test_ff_sample():
problem = {'bounds': [[0., 1.], [0., 1.], [0., 1.], [0., 1.]],
'num_vars': 4,
'names': ['x1', 'x2', 'x3', 'x4']}
actual = sample(prob... |
stefanklug/mapnik | scons/scons-local-2.3.6/SCons/compat/__init__.py | Python | lgpl-2.1 | 8,150 | 0.001104 | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge... | e('pickle', 'cPickle')
# In 3.x, 'profile' automatically loads the fast version if available.
rename_module('profile', 'cProfile')
# Before Python 3.0, the 'queue' module was named 'Queue'.
rename_module('queue', 'Queue')
# Before Python 3.0, the 'winreg' module was named '_winreg'
rename_module('winreg', '_winre... | '_scons_subprocess', 'subprocess')
try:
sys.intern
except AttributeError:
# Pre-2.6 Python has no sys.intern() function.
import builtins
try:
sys.intern = builtins.intern
except AttributeError:
# Pre-2.x Python has no builtin intern() function.
def intern(x):
retu... |
chrizel/onpsx | src/onpsx/gallery/urls.py | Python | gpl-3.0 | 160 | 0.00625 | from django.conf.url | s.defaults import *
urlpatterns = patterns('',
(r'^(\d+)/$', 'onpsx.gallery.v | iews.index'),
(r'^$', 'onpsx.gallery.views.index'),
)
|
eli261/jumpserver | apps/ops/celery/logger.py | Python | gpl-2.0 | 4,606 | 0.000434 | from logging import StreamHandler
from django.conf import settings
from celery import current_task
from celery.signals import task_prerun, task_postrun
from kombu import Connection, Exchange, Queue, Producer
from kombu.mixins import ConsumerMixin
from .utils import get_celery_task_log_path
routing_key = 'celery_log'... | _prerun.connect(self.on_task_start)
task_postrun.connect(self.on_start_end)
@staticmethod
def get_current_task_id():
if not current_task:
return
task_id = current_task.request.root_id
return task_id
def on_task_start(self, sender, task_id, **kwargs):
ret... |
def after_task_publish(self, sender, body, **kwargs):
pass
def emit(self, record):
task_id = self.get_current_task_id()
if not task_id:
return
try:
self.write_task_log(task_id, record)
self.flush()
except Exception:
self.... |
pinggit/plwe | bin/liaoxuefeng_scan.py | Python | mit | 1,649 | 0.002939 | #!/usr/bin/env python
# coding:utf-8
import urllib
domain = 'http://www.liaoxuefeng.com' #廖雪峰的域名
path = r'C:\Users\cyhhao2013\Desktop\temp\\' #html要保存的路径
# 一个html的头文件
input = open(r'C:\Users\cyhhao2013\Desktop\0.html', 'r')
head = input.read()
# 打开python教程主界面
f = urllib.urlopen("http://www.liaoxuefeng.c... | m/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000")
home = f.read()
f.close()
# 替换所有空格回车(这样容易好获取url)
geturl = home.replace("\n", "")
geturl = geturl.replace(" ", "")
# 得到包含url的字符串
list = geturl.split(r'em;"><ahref="')[1:]
# 强迫症犯了,一定要把第一个页面也加进去才完美
list.insert(0, '/wiki/001374738125095c955c1e6d8bb493182103fac9... | )
html = f.read()
# 获得title为了写文件名
title = html.split("<title>")[1]
title = title.split(" - 廖雪峰的官方网站</title>")[0]
# 要转一下码,不然加到路径里就悲剧了
title = title.decode('utf-8').replace("/", " ")
# 截取正文
html = html.split(r'<!-- block main -->')[1]
html = html.split(r'<h4>您的支持是作者写作最大的动力!</h4>')[0... |
ApexCoin/bitnote-abe | Abe/DataStore.py | Python | agpl-3.0 | 122,795 | 0.001678 | # Copyright(C) 2011,2012,2013,2014 by Abe developers.
# DataStore.py: back end database access for Abe.
# 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... | just set_flavour.
store.set_db(SqlAbstraction.SqlAbstraction(sql_args))
store.init_binfuncs()
def init_binfuncs(store):
store.binin = store._sql.binin
store.binin_hex = store._sql.binin_hex
store.binin_int = store._sql.binin_int
store.binout = store._s... | store.binout_hex = store._sql. |
danwchan/trail_of_cthulhu | mythos_website_upgrade/characterbirther/forms.py | Python | gpl-3.0 | 2,580 | 0.018217 | from django.forms import ModelForm, inlineformset_factory, HiddenInput, ModelChoiceField
from .models import BirthForm, SanityPillars, InnateAbility, StabilitySources
class CharBirthForm(ModelForm):
class Meta:
model = BirthForm
fields = ['name', 'pronoun', 'age', 'birthplace', 'drive', 'occupation... | ty
SourcesOfStability = inlineformset_factory(
BirthForm,
StabilitySources,
fields = ['name', 'relation', 'personal | ity', 'residence'],
extra = 0,
min_num = 1,
max_num = 4,
can_delete = True,
validate_min = True,
validate_max = True,
)
|
jdf76/plugin.video.youtube | resources/lib/youtube_plugin/refresh.py | Python | gpl-2.0 | 263 | 0 | # -*- coding: utf-8 -*-
| """
Copyright (C) 2018-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
import xbmc
if __name__ == '__main__':
xbmc.executebuiltin("Container.Refresh" | )
|
cowboysmall/rosalind | src/stronghold/rosalind_suff.py | Python | mit | 288 | 0.010417 | import os |
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))
import files
import tree
def main(argv):
dna | = files.read_line(argv[0])
st = tree.SuffixTree(dna)
print '\n'.join(st.traverse())
if __name__ == "__main__":
main(sys.argv[1:])
|
txomon/vdsm | tests/configNetworkTests.py | Python | gpl-2.0 | 7,351 | 0 | #
# Copyright 2012 IBM, Inc.
# Copyright 2012-2014 Red Hat, Inc.
#
# 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.
#
# T... | @MonkeyPatch(netinfo, 'networks', _fakeNetworks)
@MonkeyPatch(netinfo, 'getMaxMtu', lambda *x: 1500)
@MonkeyPatch(netinfo, 'getMtu', lambda *x: 1500)
@MonkeyPatc | h(configurators.ifcfg, 'ifdown', lambda *x:
_raiseInvalidOpException())
@MonkeyPatch(configurators.ifcfg, 'ifup',
lambda *x: _raiseInvalidOpException())
@MonkeyPatch(Bond, 'configure', lambda *x: _raiseInvalidOpException())
@MonkeyPatch(Bridge, 'configure', lambda *x: _rais... |
rwl/pylon | examples/pyreto/rlopf.py | Python | apache-2.0 | 5,046 | 0.005549 | __author__ = 'Richard Lincoln, r.w.lincoln@gmail.com'
""" This example demonstrates how optimise power flow with Pyreto. """
import sys
import logging
import numpy
import scipy.io
import pylab
import pylon
import pyreto
from pyreto.util import plotGenCost
from pybrain.rl.agents import LearningAgent
from pybrain.rl.... | 0.65, 0.58])
#p1h = p1h[6:-6]
p1h = p1h[:12]
nf = len(p1h)
# Create a case environment specifying the load profile.
env = pyreto.CaseEnvironment(case, p1h)
# Create an episodic cost minimisation task.
task = pyreto.MinimiseCostTask(env)
# Create a network | for approximating the agent's policy function that maps
# system demand to generator set-points..
nb = len([bus for bus in case.buses if bus.type == pylon.PQ])
ng = len([g for g in case.online_generators if g.bus.type != pylon.REFERENCE])
net = buildNetwork(nb, ng, bias=False)
# Create an agent and select an episodic... |
acsone/mozaik | mozaik_communication/mail_mail.py | Python | agpl-3.0 | 1,638 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of mozaik_communication, an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# mozaik_communication is free software:
# you can redistribute it and/or
# ... | 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 mozaik_communication.
# If not, see <http://www.gnu.org/licenses/>.
#
#############... | l.mail'
def _get_unsubscribe_url(
self, cr, uid, mail, email_to, msg=None, context=None):
'''
Override native method to manage unsubscribe URL for distribution list
case of newsletter.
'''
mml = mail.mailing_id
if mml.distribution_list_id and mml.distribu... |
toladata/TolaActivity | formlibrary/tests/test_models.py | Python | apache-2.0 | 1,601 | 0 | # -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.test import TestCase, tag
import factories
from formlibrary.models import CustomForm
@tag('pkg')
class CustomFormTest(TestCase):
def setUp(self):
self.organization = factories.Organization()
self.user = factori... | }
)
self.assertRaises(ValidationError, custom_form.save)
def test_save_without_public_url_info(self):
custom_form = CustomForm(
organization=self.organization,
name="Humanitec's Survey",
fields="{}",
public={'org': True}
)
se... | _form = CustomForm.objects.create(
organization=self.organization,
name="Humanitec's Survey",
fields="{}",
public={'org': True, 'url': True}
)
self.assertEqual(custom_form.name, "Humanitec's Survey")
self.assertEqual(custom_form.public, {'org': Tr... |
openconnectome/open-connectome | scripts/ingest/flyem/flyem_anno_parallel.py | Python | apache-2.0 | 4,133 | 0.031696 | import argparse
import numpy as np
from PIL import Image
import ocppaths
import ocpcarest
import zindex
import anydbm
import multiprocessing
import pdb
#
# ingest the PNG files into the database
#
"""This file is super-customized for Mitya's FlyEM data."""
# Stuff we make take from a config or the command line i... | zmin:zmax,ymin:ymax,xmin:xmax]
# insert the blob into the database
db.annotateDense ((x,y,sl-startslice), resolution, cubedata, 'O')
print "Commiting at x=%s, y=%s, z=%s" % (x,y,sl)
db.conn.commit( | )
return None
def run():
flypool = multiprocessing.Pool(totalprocs)
flypool.map(parallelwrite, totalslices, 16)
if __name__ == "__main__":
run()
|
DanielTakeshi/rl_algorithms | es/plot.py | Python | mit | 4,221 | 0.007344 | """
To plot this, you need to provide the experiment directory plus an output stem.
I use this for InvertedPendulum:
python plot.py outputs/InvertedPendulum-v1 --envname InvertedPendulum-v1 \
--out figures/InvertedPendulum-v1
(c) May 2017 by Daniel Seita
"""
import argparse
import matplotlib
matplotl... | ed only, however it's better to have multiple
random seeds so this code generalizes. For ES, we should store the output at
*every* timestep, so A['TotalIterati | ons'] should be like np.arange(...), but
this generalizes in case Ray can help me run for many more iterations.
"""
print("Now plotting based on directory {} ...".format(directory))
### Figure 1: The log.txt file.
num = len(ATTRIBUTES)
fig, axes = subplots(num, figsize=(12,3*num))
for (dd, ... |
agartland/utils | corncob_r.py | Python | mit | 3,388 | 0.007701 | import pandas as pd
import numpy as np
from os.path import join as opj
import sys
from fg_shared import *
sys.path.append(opj(_git, 'utils'))
import qu | ickr
corncob = """
require(dplyr)
require(tidy | r)
require(purr)
require(corncob)
###########################################################################################
# APPLIED TO MANY FEATURES:
###########################################################################################
# Function to Fit A Beta-Binomial Model to A Single Feature
# Note: YOU ... |
zymsys/sms-tools | software/models/spsModel.py | Python | agpl-3.0 | 7,289 | 0.024283 | # functions that implement analysis and synthesis of sounds using the Sinusoidal plus Stochastic Model
# (for example usage check the models_interface directory)
import numpy as np
from scipy.signal import resample, blackmanharris, triang, hanning
from scipy.fftpack import fft, ifft, fftshift
import math
import utilFu... | # inverse FFT of harmonic spectrum
ysw[:hNs-1] = fftbuffer[hNs+1:] | # undo zero-phase window
ysw[hNs-1:] = fftbuffer[:hNs+1]
fftbuffer = np.zeros(Ns)
fftbuffer = np.real(ifft(Yst)) # inverse FFT of stochastic spectrum
ystw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window
ystw[hNs-1:] = fftbuffer[:hNs+1]
ys[ri:r... |
noahgoldman/torwiz | torrents/torrents/database.py | Python | mit | 232 | 0.012931 | def get_all(tordb):
return tordb.find()
de | f delete(tordb, obj_id):
tordb.remove([obj_id])
def insert(tordb, obj):
return t | ordb.insert(obj)
def update_full(tordb, id, obj):
tordb.update({'_id': id}, {'$set': obj})
|
aeivazi/classroom-tracking | src/face_clipper.py | Python | mit | 257 | 0.007782 |
def clip_matrix(image_as_matrix | , width, height, top, left, expand_by=0):
x1 = left
x2 = left + width
y1 = top
y2 = top + height
crop_img = image_as_matrix[y1-expand_by:y2+expand_by, x1-expand_by:x2+expand_by]
| return crop_img
|
segfault87/Konstruktor | scripts/generate_color_table.py | Python | gpl-3.0 | 1,594 | 0.003137 | #!/usr/bin/python
import sys
if (len(sys.argv) < 2):
fn = '/usr/share/ldraw/LDConfig.ldr'
else:
fn = sys.argv[1]
f = open(fn)
for line in f:
if '!COLOUR' in line:
line = line.strip()
ns = line.split()
category = ''
if 'RUBBER' in line:
category = 'material... | category = 'material_normal'
name = '"' + ns[2].replace('_', ' ')
idx = int(ns[4])
color = ns[6][1:]
edge = ns[8][1:]
| cr = int(color[0:2], 16)
cg = int(color[2:4], 16)
cb = int(color[4:6], 16)
ca = 255
lumi = 0
for i in range(len(ns)):
if ns[i] == 'ALPHA':
ca = int(ns[i+1])
elif ns[i] == 'LUMINANCE':
lumi = int(ns[i+1])
er = int... |
elterminad0r/cipher_tools | src/scripts/freq_analysis.py | Python | gpl-3.0 | 1,559 | 0.009622 | #!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... | / (total ** 2 - total))
else:
return -1
def printchart(hist, start, interval, width=80):
(_, highest), = hist.most_common(1)
highw = len(str(highest))
return ("IOC {:.4f}\nInterval [{}::{}]\n{}"
.format(IOC(hist), start, interval,
("\n".... | "-" * int(width * frequency / highest),
highw=highw)
for letter, frequency in hist.most_common()))))
def histogram(text, start, interval):
return Counter(re.findall("[a-zA-Z]", text)[start::interval])
if __name__ == "__main__":
args = pa... |
kaplun/inspire-next | inspirehep/modules/refextract/__init__.py | Python | gpl-3.0 | 1,003 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2017 CERN.
#
# INSPIRE 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.
#
# INSPIRE 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 Gene... | icenses/>.
#
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.
"""RefExtract integration."""
from __future__ import absolute_import, division, print_function
|
jsocko515/python-lust | lust/config.py | Python | bsd-3-clause | 359 | 0.002786 | from ConfigParser import SafeConfigParser
def load_ini_file(file_name, defaults={}):
config | = SafeConfigParser()
config.readfp(open(file_name))
results = {}
for section in config.sections():
for key, value in config.items(section):
results[section + '.' + key] = value
|
results.update(defaults)
return results
|
greeneyesproject/testbed-demo | gui/pklot/designer.py | Python | mit | 8,338 | 0.020029 | '''
Created on 06/apr/2015
@author: luca
'''
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import xml.dom.minidom
STATE_NONE = 0
STATE_DRAW = 1
STATE_DELETE = 2
POINT_RADIUS = 3
POINT_COLOR_CANDIDATE = (0,127,255)
LINE_COLOR_CANDIDATE = (0,127,255)
LINE_THICK_CANDIDATE = 2
LINE_COLOR = (0,192,0)
... | ndRect":[],
"originalImg":img,
"currentImg":img.copy(),
| "rectangles":[],
"rotatedRectangles":[],
}
cv2.setMouseCallback(windowName,onMouse,drawingStatus)
pressedKey = -1
while (pressedKey != ord('q')):
pressedKey = cv2.waitKey(0)
if (pressedKey==ord('n')):
drawingStatus['status... |
shuoli84/gevent_socketio2 | socketio/binary.py | Python | mit | 2,907 | 0 | # coding=utf-8
"""
Binary class deconstruct, reconstruct packet
"""
import copy
class Binary(object):
@staticmethod
def deconstruct_packet(packet):
"""
Replaces every bytearray in packet with a numbered placeholder.
:param packet:
:return: dict with packet and list of buffers
... | ay:
place_holder = {
'_placeholder': True,
| 'num': len(buffers)
}
buffers.append(data)
return place_holder
if type(data) is list:
new_data = []
for d in data:
new_data.append(_deconstruct_packet(d))
return new_data
... |
godiard/memorize-activity | game.py | Python | gpl-2.0 | 14,959 | 0.000067 | # Copyright (C) 2006, 2007, 2008 One Laptop per Child
#
# 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... | ST, None,
[GObject.TYPE_PYOBJECT]),
'load_game': (GObject.Signa | lFlags.RUN_FIRST, None,
2 * [GObject.TYPE_PYOBJECT]),
'change_game': (GObject.SignalFlags.RUN_FIRST, None,
2 * [GObject.TYPE_PYOBJECT]),
'change_game_signal': (GObject.SignalFlags.RUN_FIRST, None,
5 * [GObject.TYPE_PYOBJECT]),
... |
hermco/jenkins_cli_tool | setup.py | Python | mit | 521 | 0 | from d | istutils.core import setup
setup(
name='jenkins_cli_tool',
version='3.1',
packages=['cli', 'cli.startjob', 'cli.startAndMonitor', 'tests'],
url='https://github.com/hermco/jenkins_cli_tool',
license='MIT',
author='chermet',
author_email='chermet@axway.com',
description='CLI tool for Jenk... | le_scripts': [
'jenkins-cli-tool = cli.cli:entry_point'
]
}
)
|
BenLand100/chatlogs | wordprofile.py | Python | gpl-3.0 | 2,410 | 0.009129 | #!/usr/bin/env python3
'''
* Copyright 2015 by Benjamin J. Land (a.k.a. BenLand100)
*
* This file is part of chatlogs.
*
* chatlogs 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 ... | * (at your option) any later version.
*
* chatlogs 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 ... | lections
import nltk
import string
import tools
import json
import sys
import re
import multiprocessing
import enchant
if len(sys.argv) < 5:
print('./wordprofile.py database num splittype maxlen src+')
print('\tsplittype can be one of: nltk, regex, respell')
sys.exit(1)
db = tools.database(sys.argv[1])
ma... |
6WIND/scapy | scapy/compat.py | Python | gpl-2.0 | 4,048 | 0.000247 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# Copyright (C) Gabriel Potter <gabriel@potter.fr>
# This program is published under a GPLv2 license
"""
Python 2 and 3 link classes.
"""
from __future__ import absolute_impor... | ython3 #
###########
def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code | __.co_argcount == 1:
return lambda *args: func(args[0] if len(args) == 1 else args)
else:
return func
if six.PY2:
bytes_encode = plain_str = str
chb = lambda x: x if isinstance(x, str) else chr(x)
orb = ord
def raw(x):
"""Builds a packet and returns its bytes representatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.