repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
cernops/neutron | neutron/db/migration/alembic_migrations/versions/5ac1c354a051_n1kv_segment_alloc.py | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
chienlieu2017/it_management | odoo/odoo/addons/base/res/res_font.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from reportlab.pdfbase import ttfonts
from odoo import api, fields, models
from odoo.report.render.rml2pdf import customfonts
"""This module allows the mapping of some system-available TTF fonts to
the r... |
mzdaniel/oh-mainline | vendor/packages/celery/celery/tests/test_events/test_events_state.py | from __future__ import absolute_import
from time import time
from itertools import count
from celery import states
from celery.events import Event
from celery.events.state import State, Worker, Task, HEARTBEAT_EXPIRE
from celery.utils import uuid
from celery.tests.utils import unittest
class replay(object):
d... |
mzdaniel/oh-mainline | vendor/packages/celery/celery/events/dumper.py | # -*- coding: utf-8 -*-
"""
celery.events.dumper
~~~~~~~~~~~~~~~~~~~~
THis is a simple program that dumps events to the console
as they happen. Think of it like a `tcpdump` for Celery events.
:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
from __fu... |
mclois/iteexe | twisted/internet/_posixserialport.py | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Serial Port Protocol
"""
# system imports
import os, errno
# dependent on pyserial ( http://pyserial.sf.net/ )
# only tested w/ 1.18 (5 Dec 2002)
import serial
from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
from serial im... |
yuyuyu101/VirtualBox-NetBSD | src/libs/xpcom18a4/python/test/pyxpcom_test_tools.py | # test tools for the pyxpcom bindings
from xpcom import _xpcom
import unittest
# export a "getmemusage()" function that returns a useful "bytes used" count
# for the current process. Growth in this when doing the same thing over and
# over implies a leak.
try:
import win32api
import win32pdh
import win32... |
samsu/neutron | plugins/mlnx/common/constants.py | # Copyright 2013 Mellanox Technologies, Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
Lambdanaut/crits | crits/ips/migrate.py | def migrate_ip(self):
"""
Migrate to the latest schema version.
"""
migrate_1_to_2(self)
migrate_2_to_3(self)
def migrate_2_to_3(self):
"""
Migrate from schema 2 to 3.
"""
if self.schema_version < 2:
migrate_1_to_2(self)
if self.schema_version == 2:
self.schem... |
bjolivot/ansible | lib/ansible/modules/cloud/openstack/os_nova_flavor.py | #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# This module 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... |
gkotton/vmware-nsx | vmware-nsx/neutron/tests/unit/vmware/extensions/test_portsecurity.py | # Copyright (c) 2014 OpenStack Foundation.
# 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... |
bjolivot/ansible | lib/ansible/modules/network/avi/avi_analyticsprofile.py | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 16.3.8
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/python/kernel_tests/init_ops_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
omco/mpir | yasm/tools/python-yasm/pyxelator/genpyx.py | #!/usr/bin/env python
""" genpyx.py - parse c declarations
(c) 2002, 2003, 2004, 2005 Simon Burton <simon@arrowtheory.com>
Released under GNU LGPL license.
version 0.xx
This is a module of mixin classes for ir.py .
Towards the end of ir.py our global class definitions
are remapped to point to the class definitions ... |
paninetworks/neutron | neutron/tests/functional/agent/linux/test_interface.py | # Copyright (c) 2015 Red Hat, 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 ... |
xiejianying/pjsip | tests/pjsua/scripts-sendto/330_srtp_prefer_rtp_savp.py | # $Id$
import inc_sip as sip
import inc_sdp as sdp
# When SRTP is enabled in pjsua, it should prefer to use
# RTP/SAVP media line if there are multiple m=audio lines
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0
a=rtpmap:0 pcmu/8000
m=audio 4000 RTP/SAVP 0
a=crypto:1 aes_... |
mheap/ansible | test/units/modules/cloud/openstack/test_os_server.py | import collections
import inspect
import mock
import pytest
import yaml
from ansible.module_utils.six import string_types
from ansible.modules.cloud.openstack import os_server
class AnsibleFail(Exception):
pass
class AnsibleExit(Exception):
pass
def params_from_doc(func):
'''This function extracts th... |
huchoi/edx-platform | cms/djangoapps/contentstore/views/public.py | """
Public views
"""
from django_future.csrf import ensure_csrf_cookie
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.conf import settings
from edxmako.shortcuts import render_to_response
from external_auth.views import (s... |
dknlght/dkodi | src/plugin.video.animehere/servers/depositfiles.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para depositfiles
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core ... |
JazzeYoung/VeryDeepAutoEncoder | pylearn2/pylearn2/datasets/tfd.py | """
.. todo::
WRITEME
"""
import numpy as np
from pylearn2.datasets import dense_design_matrix
from pylearn2.utils.serial import load
from pylearn2.utils.rng import make_np_rng
from pylearn2.utils import contains_nan
class TFD(dense_design_matrix.DenseDesignMatrix):
"""
Pylearn2 wrapper for the Toronto ... |
halexan/Headquarters | src/headquarters/packet/stream_parser.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... |
youtube/cobalt | third_party/blink/Tools/Scripts/webkitpy/thirdparty/coverage/results.py | """Results of coverage measurement."""
import os
from coverage.backward import set, sorted # pylint: disable=W0622
from coverage.misc import format_lines, join_regex, NoSource
from coverage.parser import CodeParser
class Analysis(object):
"""The results of analyzing a code unit."""
def __init__(s... |
gusai-francelabs/datafari | windows/python/Lib/warnings.py | """Python part of the warnings subsystem."""
# Note: function level imports should *not* be used
# in this module as it may cause import lock deadlock.
# See bug 683658.
import linecache
import sys
import types
__all__ = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefil... |
prashanthr/wakatime | wakatime/packages/pygments_py3/pygments/lexers/actionscript.py | # -*- coding: utf-8 -*-
"""
pygments.lexers.actionscript
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for ActionScript and MXML.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, using,... |
jessekl/flixr | venv/lib/python2.7/site-packages/sqlalchemy/dialects/sybase/__init__.py | # sybase/__init__.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.dialects.sybase import base, pysybase, pyodbc
# default dialect
ba... |
iaddict/mercurial.rb | vendor/mercurial/mercurial/encoding.py | # encoding.py - character transcoding support for Mercurial
#
# Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import error
import unicodedata, locale, os
def _getpr... |
edisonlz/fruit | web_project/base/site-packages/django/conf/locale/mk/formats.py | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd F Y'
TIME_FORMAT = 'H:i:s'
DATE... |
diogocs1/comps | web/addons/resource/faces/plocale.py | ############################################################################
# Copyright (C) 2005 by Reithinger GmbH
# mreithinger@web.de
#
# This file is part of faces.
#
# faces is free software; you can redistribute it and/or modify
# ... |
minhphung171093/OpenERP_V8 | openerp/addons/google_spreadsheet/google_spreadsheet.py | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General... |
lafrenierejm/ietf-cli | ietf/test/xml-fyi.py | #!/usr/bin/env python3
import os
import unittest
import xml.etree.ElementTree as ET
from ietf.sql.base import Base
from ietf.sql.fyi import Fyi
from ietf.xml.fyi import add_all
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
class TestXmlRfc(unittest.TestCase):
data_file = os.path.jo... |
sieben/pycolo | tests/core/TestRequest.py | # coding=utf-8
"""
Testing CoAP requests
"""
import json
import os
import tempfile
import unittest
import pycolo as coap
from pycolo.request import request
from pycolo.endpoint import Endpoint
from pycolo.exceptions import InvalidURL, COAPError
from tests.examples.TestCoAPbin import coapbin
class CarelessTest(unitt... |
blcook223/bencook.info | blog/models.py | from markdown import markdown
from django.db import models
from django.core.urlresolvers import reverse
class Tag(models.Model):
"""
A subject-matter tag for blog posts
"""
slug = models.CharField(max_length=200, unique=True)
name = models.SlugField(max_length=200, unique=True)
def __str__(s... |
sulami/feed2maildir | feed2maildir/reader.py | import feedparser
from multiprocessing.pool import ThreadPool
def fetch_and_parse_feed(args):
name, feed = args
return (name, feedparser.parse(feed))
class Reader:
"""Get updates on the feeds supplied"""
def __init__(self, feeds, silent=False, njobs=4):
self.feeds = []
self.silent = s... |
ifwe/wxpy | src/tests/wxPythonTests/testGauge.py | """Unit tests for wx.Gauge.
Methods yet to test:
__init__, Create, Pulse"""
import unittest
import wx
import wxtest
import testControl
class GaugeTest(testControl.ControlTest):
def setUp(self):
self.app = wx.PySimpleApp()
self.frame = wx.Frame(parent=None)
self.testControl = wx.Gauge(par... |
gst/amqpy | amqpy/consumer.py | from abc import ABCMeta, abstractmethod
class AbstractConsumer(metaclass=ABCMeta):
"""
This class provides facilities to create and manage queue consumers. To
create a consumer, subclass this class and override the :meth:`run`
method. Then, instantiate the class with the desired parameters and call
... |
Alfredx/django-db2charts | db2charts/router.py | # -*- coding: utf-8 -*-
# author: Alfred
import os
import re
DB_MODULE_PATTERN = re.compile(r'db2charts_models\.(?P<module>.*)_models')
class DB2ChartsRouter(object):
def db_for_module(self, module):
match = DB_MODULE_PATTERN.match(module)
if match:
return match.groupdict()['module']
... |
peteboyd/lammps_interface | lammps_interface/Molecules.py | """
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... |
sevazhidkov/leonard | modules/menu.py | import random
import telegram
MENU = [[('handler', 'Venues ☕', 'foursquare-location-choice'),
('handler', 'Weather 🌤', 'weather-show'),
('handler', 'News 📰', 'news-get-entry')],
[('handler', 'Vinci 🌇', 'vinci-upload-image'),
('handler', 'Get Uber 🚘', 'uber-choose-location'),
... |
emjosephs/eQTL | calc_HW_deviations.py | #takes in an eQTL file and outputs allele freq and deviation from HWE
#0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
#scaf pac locus freq fold effect dom d_over_a f p hom1 het hom2 Rsquared f(hom1/het/hom2)
#scaf8 20911662 9414108 0.80... |
hobson/pug-dj | pug/dj/miner/tests.py | # import time
# import unittest
import doctest
from django.test import LiveServerTestCase #, TestCase
from selenium import webdriver
import pug.nlp.util
# from pug.dj import db as djdb
# from traceback import print_exc
class HomeTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox... |
istommao/wechatkit | wechatkit/resource.py | """Resource manage module."""
import os
from .utils import RequestUtil
class ResourceAPI(object):
"""Resource wechat api."""
ADD_TEMP_URI = ('https://api.weixin.qq.com/cgi-bin/media/'
'upload?access_token={}&type={}')
@classmethod
def upload(cls, path, token, rtype, upload_type=... |
ypkang/keras | keras/constraints.py | from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
class Constraint(object):
def __call__(self, p):
return p
def get_config(self):
return {"name":self.__class__.__name__}
class MaxNorm(Constraint):
def __init__(self, m=2):
self.m = m
... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/contrib/lite/toco/toco_flags_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/contrib/lite/toco/toco_flags.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from goog... |
elvian/alfred | scripts/pollutionController.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
def getSoupAQHI():
html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80")
soup = BeautifulSoup(html, "lxml")
return soup
def getLatestAQHI(dataTable):
aqhiTable = data... |
b29308188/Deep-Generative-Model-for-Text-Data | src/basic_sentiment.py | import sys
import re
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, TimeDistributed, Dropout, Activation, LSTM, BatchNormalization
from keras.optimizers import RMSprop, Adam
from keras.layers.advanced_activations import LeakyReLU
from keras.utils import np_utils
#from seq2seq.mod... |
DeflatedPickle/pkinter | pkinter/boundbutton.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""""""
import tkinter as tk
from tkinter import ttk
# link
__title__ = "BoundButton"
__version__ = "1.0.3"
__author__ = "DeflatedPickle"
class BoundButton(ttk.Button):
"""
-----DESCRIPTION-----
A ttk Button that can be bound to any key to run any fu... |
dnaextrim/django_adminlte_x | adminlte/static/plugins/datatables/extensions/ColVis/examples/button_order.html.py | XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXX XXXXXXX X XXXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX... |
dgk/django-business-logic | tests/test_signals.py | # -*- coding: utf-8 -*-
#
from .common import *
class SignalCatchException(Exception):
pass
def raise_on_enter(**kwargs):
raise SignalCatchException(kwargs)
class SignalsTest(TestCase):
def tearDown(self):
signals.interpret_enter.disconnect(raise_on_enter)
signals.interpret_leave.dis... |
TigerND/djangocms-tonicdev | djangocms_tonicdev/migrations/0003_auto_20160509_1538.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-09 12:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangocms_tonicdev', '0002_tonicnotebookpluginmodel_name'),
]
operations = [
... |
NicoRahm/CGvsPhoto | Textures/dsift.py | '''
dsift.py: this function implements some basic functions that
does dense sift feature extraction.
The descriptors are defined in a similar way to the one used in
Svetlana Lazebnik's Matlab implementation, which could be found
at:
http://www.cs.unc.edu/~lazebnik/
Yangqing Jia, jiayq@eecs.berkeley.edu
'''
import num... |
encukou/qdex | qdex/delegate.py | #!/usr/bin/env python
# Encoding: UTF-8
"""Part of qdex: a Pokédex using PySide and veekun's pokedex library.
A query models for pokémon
"""
from PySide import QtGui, QtCore
Qt = QtCore.Qt
class PokemonDelegate(QtGui.QStyledItemDelegate):
"""Delegate for a Pokémon
Shows summary information when the group o... |
jwinzer/OpenSlides | server/openslides/users/models.py | import smtplib
from decimal import Decimal
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
Group as DjangoGroup,
GroupManager as _GroupManager,
Permission,
PermissionsMixin,
)
from... |
aodag/WebDispatch | webdispatch/testing.py | """ utilities for testing
"""
def setup_environ(**kwargs):
""" setup basic wsgi environ"""
environ = {}
from wsgiref.util import setup_testing_defaults
setup_testing_defaults(environ)
environ.update(kwargs)
return environ
def make_env(path_info, script_name):
""" set up basic wsgi enviro... |
duncan-r/SHIP | ship/fmp/ief.py | """
Summary:
Ief file data holder.
Contains the functionality for loading ISIS .ief files from disk.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
import os
from ship.utils import utilfunctions as uf
from ship.utils i... |
bitmazk/django-monitoring | monitoring/views.py | """Views for the monitoring app."""
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import Http404
from django.utils.decorators import method_decorator
from django.views.generic import ListView, TemplateView
from .register import monitor
class MonitoringV... |
qiudebo/13learn | code/stat/stat_random.py | # -*- coding: utf-8 -*-
import numpy as np
import numpy.random as random
# 设置随机数种子
random.seed(42)
# 产生一个1x3,[0,1)之间的浮点型随机数
# array([[ 0.37454012, 0.95071431, 0.73199394]])
# 后面的例子就不在注释中给出具体结果了
random.rand(1, 3)
# 产生一个[0,1)之间的浮点型随机数
random.random()
# 下边4个没有区别,都是按照指定大小产生[0,1)之间的浮点型随机数array
random... |
aurzenligl/prophy | prophyc/generators/prophy.py | from collections import namedtuple
from prophyc.generators import base, word_wrap
INDENT_STR = u" "
MAX_LINE_WIDTH = 100
DocStr = namedtuple("DocStr", "block, inline")
def _form_doc(model_node, max_inl_docstring_len, indent_level):
block_doc, inline_doc = "", ""
if model_node.docstring:
if len(m... |
jrbourbeau/cr-composition | comptools/binning.py |
from collections import namedtuple
import numpy as np
def get_energybins(config='IC86.2012'):
"""Function to return analysis energy bin information
Parameters
----------
config : str, optional
Detector configuration (default is 'IC86.2012').
Returns
-------
energybins : namedtup... |
alex-dow/psistatsrd | psistatsrd/utils/drawable.py | import pygame
import sys
from psistatsrd.app import App
def create_queue_row(data, config):
mem_graph = create_mem_graph(config)
cpu_graph = create_cpu_graph(config)
scroll_text = []
title = []
if type(data['ipaddr']).__name__ == "list":
scroll_text = scroll_text + data['ipaddr']
el... |
cpsaltis/pythogram-core | src/gramcore/filters/morphology.py | """Morphological filters.
The following work on 2D arrays. They wrap the relevant scipy functions. The
ones provided by skimage are not well documented for now.
"""
from scipy.ndimage import morphology
def closing(parameters):
"""Calculates morphological closing of a greyscale image.
This is equal to perfo... |
Reimilia/Privacy_Server | resources/common/json_parser.py | import json
import copy
formtable = {"name":[u'name'],
"gender":[u'gender'],
"contact":[u'contact'],
"address":[u'address']}
def is_reserved_layer(dict,reserved_word):
for key in dict:
if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]:
... |
stavinsky/lsshipper | lsshipper/reader_aio.py | import os
import aiofiles
async def get_line(name, offset=0, sep=b'\r\n', chunk_size=4096):
name = os.path.abspath(name)
async with aiofiles.open(name, 'r+b') as f:
await f.seek(offset)
tmp_line = b""
chunk = await f.read(chunk_size)
while chunk:
if len(tmp_line):
... |
rsms/smisk | lib/smisk/serialization/xmlbase.py | # encoding: utf-8
'''XML support.
'''
import logging
from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError
from smisk.core import Application
try: import xml.etree.cElementTree as ET
except ImportError:
try: import xml.etree.ElementTree as ET
except ImportError:
... |
simpeg/discretize | tutorials/inner_products/4_advanced.py | """
Advanced Examples
=================
In this section, we demonstrate how to go from the inner product to the
discrete approximation for some special cases. We also show how all
necessary operators are constructed for each case.
"""
####################################################
#
# Import Packages
# -... |
mawri/sswe-team9 | src/prepare_svm_data.py | import numpy as np
from subprocess import call
#this readies the data for svm
data_folder_path = '../data/'
file_names = ['test']
word_embedding_size = 50
# read the vectors.bin file and create a map
vec_dict = {}
# vec_file = open ('vectors.bin', 'r')
# create vectors and counts
for f in file_names:
with open (... |
knowitnothing/btcx | gui/qt/systray.py | import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
def chunk(seq, size):
for i in xrange(0, len(seq), size):
yield seq[i:i+size]
class TextSysTray(object):
def __init__(self, parent, text, ntray=2, **kwargs):
self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)]
self._curr_... |
raphael-group/comet | run_comet_full.py | #!/usr/bin/python
# Load required modules
import sys, os, json, re, time, comet as C, multiprocessing as mp, random
from math import exp
import run_comet_simple as RC
def get_parser():
# Parse arguments
import argparse
description = 'Runs CoMEt on permuted matrices.'
parser = argparse.ArgumentParser(d... |
navcoindev/navcoin-core | qa/rpc-tests/walletbackup.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Exercise the wallet backup code. Ported from walletbackup.sh.
Test case is:
4 nodes. 1 2 and 3 send... |
timj/scons | test/SConscript/Return.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, publish,
... |
neilb14/featurewise | scripts/generate_usage.py | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def working_hours(current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * ... |
abitofalchemy/ScientificImpactPrediction | analyze_altmetric.py | # -*- coding: utf-8 -*-
__author__ = "Sal Aguinaga"
__copyright__ = "Copyright 2015, The Phoenix Project"
__credits__ = ["Sal Aguinaga", "Rodrigo Palacios", "Tim Weninger"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Sal Aguinaga"
__email__ = "saguinag (at) nd dot edu"
import json
import argparse,trac... |
avalcarce/gym-learn | utils.py | import os
import numpy as np
def get_last_folder_id(folder_path):
t = 0
for fn in os.listdir(folder_path):
t = max(t, int(fn))
return t
def movingaverage(values, window):
weights = np.repeat(1.0, window)/window
sma = np.convolve(values, weights, 'valid')
return sma
... |
EPiCS/soundgates | hardware/tools/to_samples.py | #!/usr/bin/env python
# coding: utf8
import sys;
import struct;
def do_convert(filename):
fid_in = open(filename, 'rb')
fid_out = open('sound_conv.out','w')
data = fid_in.read(4) # read 4 bytes = 32 Bit Sample
while data:
ser = str(struct.unpack('<i', data)[0]) + '\n'
fid_out.... |
wanqizhu/mtg-python-engine | MTG/player.py | import pdb
import traceback
import random
from copy import deepcopy
from collections import defaultdict
from MTG import mana
from MTG import zone
from MTG import play
from MTG import gamesteps
from MTG import cards
from MTG import triggers
from MTG import token
from MTG.exceptions import *
class Player():
is_pla... |
stetro/pix-table | pixmodules/pong.py | import threading
import random
from pixmodule import PixModule
class Pong(PixModule):
speed = 0
speedcounter = 0
direction = 1
position = 0
stats = (0,0)
startSleep = 0
def render(self):
if(self.stats is (0,0) and self.startSleep < 4000):
self.startSleep += 1
elif self.stats[0] == 9:
if self.leftPre... |
rwl/PyCIM | CIM15/IEC61970/Informative/InfOperations/ChangeSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
IQSS/miniverse | dv_apps/metrics/stats_util_dataverses.py | """
Create metrics for Dataverses.
This may be used for APIs, views with visualizations, etc.
"""
from collections import OrderedDict
from django.db import models
from dv_apps.utils.date_helper import get_month_name_abbreviation,\
get_month_name
from dv_apps.dataverses.models import Dataverse, DATAVERSE_TYPE_UNCA... |
hms-dbmi/clodius | clodius/tiles/hitile.py | import base64
import h5py
import math
import numpy as np
import os
import os.path as op
def array_to_hitile(
old_data, filename, zoom_step=8, chunks=(1e6,), agg_function=np.sum
):
"""
Downsample a dataset so that it's compatible with HiGlass (filetype: hitile, datatype: vector)
Parameters
-------... |
fabteam1/komsukomsuhuhu | komsukomsuhuu/komsukomsuhuu/celery.py | from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'komsukomsuhuu.settings')
from django.conf import settings
app = Celery('komsukomsuhuu',
broker='amqp://',
... |
nwjs/nw.js | test/sanity/issue5730-add-node-in-permissions/test.py | import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
chrome_options.add_argument('nwapp=' + testdir)
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_optio... |
theno/fabsetup | fabsetup/fabfile/setup/powerline.py | import os.path
from fabric.api import env
from fabsetup.fabutils import checkup_git_repo_legacy, needs_packages
from fabsetup.fabutils import needs_repo_fabsetup_custom, suggest_localhost
from fabsetup.fabutils import install_file_legacy, run, subtask, subsubtask, task
from fabsetup.utils import flo, update_or_append... |
ktok07b6/polyphony | tests/if/if23.py | from polyphony import testbench
class C:
def __init__(self):
self.v1 = 0
self.v2 = 0
def set_v(self, i, v):
if i == 0:
pass
elif i == 1:
self.v1 = v
elif i == 2:
self.v2 = v
else:
return
def if23():
c = C()
... |
szymonlipinski/hackernews_dowloader | hnusers.py | """
A simple script for downloading user data.
"""
import argparse
import csv
import json
import os
from dataclasses import dataclass
from shutil import move
import requests as r
from common import convert, limit_rate, max_request_per_hour, pid_run
users_file_name = "users"
users_data_file_name = "users.data.csv"
te... |
SimplyCo/cityproblems | cityproblems/accounts/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('cityproblems.accounts.views',
url(r'^register/$', 'register', name="accounts_register"),
url(r'^profile/edit/$', 'accounts_profile_edit', name="accounts_profile_edit"),
url(r'^profil... |
fxdemolisher/frano | frano/templatetags/frano_filters.py | from django import template
from django.template.defaultfilters import stringfilter
import locale
register = template.Library()
#-----------\
# FILTERS |
#-----------/
@register.filter
@stringfilter
def num_format(value, places = 2, min_places = 2):
return format(value, '.', int(places), 3, ',', int(min_places))... |
Nymphet/acgnz-spider | AcgnzSpider/spiders/AcgnzSpider01.py | # -*- coding: utf-8 -*-
import scrapy
import logging
from scrapy.utils.project import get_project_settings
from time import sleep
from AcgnzSpider.items import AcgnzItem
class AcgnzSpider(scrapy.Spider):
name = 'acgnz.cc'
start_urls = ['http://www.acgnz.cc/sign']
allowed_domains = ['acgnz.cc']
def... |
gietal/Stocker | sandbox/udacity/1-9.py | import utils
import pandas as pd
import numpy as np
import scipy.optimize as spo
def get_data():
return utils.get_data(['SPY', 'MSFT', 'GOOG', 'AMD', 'TSLA', 'GLD'], pd.date_range('2011-01-01', '2017-01-01'))
def optimizer_error(allocs, data):
return 0
def test():
data = get_data()
n... |
Signiant/maestro-core | maestro/tools/path.py | import os, platform, re, shutil
def get_tree_size(path = '.'):
"""
get_tree_size will return the total size of a directory tree
"""
if not os.path.exists(path):
raise OSError("Path " + str(path) + " does not exist!")
total_size = 0
for dirpath, dirnames, filenames in os.walk(str(path))... |
closeio/tasktiger | tasktiger/redis_semaphore.py | """Redis Semaphore lock."""
import os
import time
SYSTEM_LOCK_ID = 'SYSTEM_LOCK'
class Semaphore(object):
"""Semaphore lock using Redis ZSET."""
def __init__(self, redis, name, lock_id, timeout, max_locks=1):
"""
Semaphore lock.
Semaphore logic is implemented in the lua/semaphore.l... |
elstupido/rpg | rooms/testrooms/testroom2.room.py |
from room import Room
r = Room()
r.roomname = 'testroom2'
r.exits = {'up': 'testroom'}
r.roomdesc = """
As you look around, you notice there seems to be not much here.
it appears you can go up and get back to where you came from
there is a pile of gold and a large monster looking at you strangely.
"""
r.looktargets ... |
baklanovp/pystella | pystella/rf/lc.py | import numpy as np
from pystella.rf import band
from pystella.rf.ts import TimeSeries, SetTimeSeries
__author__ = 'bakl'
class LightCurve(TimeSeries):
def __init__(self, b, time, mags, errs=None, tshift=0., mshift=0.):
"""Creates a Light Curve instance. Required parameters: b (band), time, mags."""
... |
Xarxa6/hackathon | src/config.py | import json
import os, sys, traceback
script_dir = os.path.dirname(__file__)
config_file = os.path.join(script_dir, './config/application.json')
defaults = os.path.join(script_dir, './config/reference.json')
def loadConfig(f):
print "[INFO] Loading configuration from " + f + "..."
with open(f, 'r') as opened:... |
stryder199/RyarkAssignments | Assignment2/web2py/gluon/http.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
__all__ = ['HTTP', 'redirect']
defined_status = {
200: 'OK',
201: 'CREATED',
202: 'ACCEPTE... |
weidnerm/solar_data_monitor | SolarSensors_test.py |
from unittest import TestCase, main, skip
from mock import patch, call, MagicMock
from SolarSensors import SolarSensors
import os
class SolarSensors_test(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def get_default_config(self):
config = [
{
... |
zeraien/odb_shared_django | http_shortcuts.py | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators import available_attrs
from functools import wraps
def render(requ... |
matthewearl/photo-a-day-aligner | pada/landmarks.py | # Copyright (c) 2016 Matthew Earl
#
# 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, publish, distr... |
corbanmailloux/MysteryMansion | win_animation.py | """Win animation frames for Mystery Mansion.
Animation from: http://www.angelfire.com/ca/mathcool/fireworks.html
"""
win_animation = [
"""
.|
| |
|'| ._____
___ | | |. |' .---"|
_ .-' ... |
PublicShawn/eye | util.py | import glob
import subprocess
from threading import Timer
import logging
import distutils.dir_util
import sys
import multiprocessing
import os
from shutil import copy2
import eyetype
import shutil
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def runWithTimeOutByDaemon(cmd... |
genos/online_problems | rosalind/lia.py | #!/usr/bin/env python
# coding: utf-8
from rosalind import binom
def pbinom(n, p, r):
return binom(n, r) * pow(p, r) * pow(1 - p, n - r)
def dbinom(n, p, r):
return sum(pbinom(n, p, i) for i in range(r + 1))
def lia(k, N):
t = 1 << k
return 1 - dbinom(t, .25, N - 1)
if __name__ == "__main__":
... |
GETLIMS/LIMS-Backend | lims/projects/migrations/0011_auto_20160822_1527.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0010_product_design_format'),
]
operations = [
migrations.AlterField(
model_name='product',
... |
nint8835/NintbotForDiscordV2 | NintbotForDiscord/Enums.py | from enum import Enum
class EventType(Enum):
"""Enum containing the various types of events that can occur."""
CLIENT_READY = "CLIENT_READY"
CLIENT_RESUMED = "CLIENT_RESUMED"
MESSAGE_RECEIVED = "MESSAGE_RECEIVED"
SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED"
PRIVATE_MESSAGE_RECEIVED = "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.