repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
egentry/stellarstructure | modelparameters.py | import numpy as np
import gasproperties
import astropy.constants as const
import gasproperties
M_solar = 1.988e33 # [g]
R_solar = 6.955e10 # [cm]
L_solar = 3.83e33 # [erg s^-1]
mass_scale = 1.5
# P_c = 2.2e17 # core pressure, [dyne cm^-2]
# T_c = 1.5e7 # core temperature, [K]
# M_star = mass_scale * M_sola... |
wikimedia/thumbor-request-storage | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='wikimedia_thumbor_request_storage',
version='0.1.1',
url='https://github.com/wikimedia/thumbor-request-storage',
license='MIT',
author='Gilles Dubuc, Wikimedia Foundation',
description='Thumbor request storage',
... |
obeattie/sqlalchemy | lib/sqlalchemy/dialects/sybase/schema.py | from sqlalchemy import *
ischema = MetaData()
tables = Table("SYSTABLE", ischema,
Column("table_id", Integer, primary_key=True),
Column("file_id", SMALLINT),
Column("table_name", CHAR(128)),
Column("table_type", CHAR(10)),
Column("creator", Integer),
#schema="information_schema"
)
domains... |
OiNutter/rivets | rivets/processing/slimmer_compressors.py | from lean.template import Template
class SlimmerCSSCompressor(Template):
@staticmethod
def is_engine_initialized():
return 'slimmer_css' in globals()
def prepare(self):
pass
def evaluate(self,scope, locals, block=None):
if not hasattr(self,'output') or not self.output:
from slimmer import css_slimmer
... |
py-in-the-sky/challenges | json_parser/lex.py | import re
from collections import deque, namedtuple
def lex(json_string):
return deque(lex_lazy(json_string))
def lex_lazy(json_string):
assert isinstance(json_string, unicode)
return (wrap_match(match.group()) for match in RE.finditer(json_string))
def wrap_match(s):
assert isinstance(s, unicode)... |
gnott/elife-poa-xml-generation | parseXlsFiles.py |
import xlrd
from collections import defaultdict
from generatePoaXml import *
import settings as settings
import re
from xml.dom import minidom
"""
Provide a thin wrapper around a set of functions
to read data from XLS files.
Ideally the calling script should not need to know
where the underlying XLS files are, or ... |
geertj/python-corosync | lib/corosync/test/test_cpg.py | #
# This file is part of python-corosync. Python-Corosync is free software
# that is made available under the MIT license. Consult the file "LICENSE"
# that is distributed together with this file for the exact licensing terms.
#
# Python-Corosync is copyright (c) 2008 by the python-corosync authors. See
# the file "AUT... |
luismesas/pydobot | pydobot/dobot.py | import serial
import struct
import time
import threading
import warnings
from .message import Message
from .enums import PTPMode
from .enums.CommunicationProtocolIDs import CommunicationProtocolIDs
from .enums.ControlValues import ControlValues
class Dobot:
def __init__(self, port, verbose=False):
threa... |
JeroenZegers/Nabu-MSSS | nabu/processing/feature_computers/sigproc.py | '''@file sigproc.py
contains the signal processing functionality
The MIT License (MIT)
Copyright (c) 2013 James Lyons
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, includi... |
0ip/pymarkview | pymarkview/ui/editor.py | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from urllib.parse import urlparse
from urllib.request import url2pathname
class LineNumberEditor(QFrame):
def __init__(self, settings, *args):
super().__init__(*args)
self._editor = self.Editor(settings)
s... |
fjacob21/MAX | service/src/state_scheduler/states/salon_entry_light_state/on_state.py | import MAX
import time
class on_state(object):
def __init__(self, machine):
self._machine = machine
self._lasttime = time.time()
def event(self, event, source, params):
if source.name == 'WeMo Motion':
dt = (time.time() - self._lasttime) / 60
if event == 'motion... |
ownaginatious/mixpanel-export-stream | examples/example.py | from collections import Counter
from mixpanel_export import EventStream
api_key = '...'
api_secret = '...'
es = EventStream(api_key, api_secret)
params = {
'event': ["A"],
'from_date': '...',
'to_date': '...',
'where': 'property["B"] == "2"'
}
count = Counter()
def do_count(e):
count[e['proper... |
rizar/ift6266h16 | main.py | #!/usr/bin/env python
"""Convolutional network example.
Run the training for 50 epochs with
```
python __init__.py --num-epochs 50
```
It is going to reach around 0.8% error rate on the test set.
"""
from __future__ import print_function
import sys
import logging
import numpy
import os
import subprocess
from argpars... |
iwschris/ezodf2 | tests/test_whitespaces.py | #!/usr/bin/env python
#coding:utf-8
# Purpose: test append text
# Created: 06.01.2011
# Copyright (C) 2011, Manfred Moitzi
# License: MIT
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
# Standard Library
import unittest
# trusted or separately teste... |
AbhiAgarwal/prep | python/avl_rotation.py | class AVLNode(object):
def __init__(self, key):
self.key=key
self.right_child=None
self.left_child=None
self.parent=None
self.height=0
self.balance=0
def update_height(self, upwards=True):
#If upwards we go up the tree correcting heights and balances,
... |
DingKe/nn_playground | gcnn/data/imdb_preprocess_semi.py | """
This script is what created the dataset pickled.
1) You need to download this file and put it in the same directory as this file.
https://github.com/moses-smt/mosesdecoder/raw/master/scripts/tokenizer/tokenizer.perl . Give it execution permission.
2) Get the dataset from http://ai.stanford.edu/~amaas/data/sentime... |
hfeeki/cmdln | test/test_doctests.py | #!/usr/bin/env python
# Copyright (c) 2005 Trent Mick
# License: MIT License
"""Run doctests in various files in this project."""
import sys
from os.path import dirname, abspath
import unittest
import doctest
def suite():
"""Return a unittest.TestSuite to be used by test.py."""
suite = unittest.TestSuite()
... |
yayoiukai/signalserver | fileuploads/migrations/0034_auto_20161209_2108.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.dev20160107235441 on 2016-12-10 02:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fileuploads', '0033_result_group_id'),
]
operations = [
migrations.... |
linkhub-sdk/popbill.fax.example.py | cancelReserve.py | # -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import FaxService, PopbillException
faxService = FaxService(testValue.LinkID, testValue.SecretK... |
I-sektionen/i-portalen | wsgi/iportalen_django/exchange_portal/migrations/0002_auto_20170124_1858.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import exchange_portal.models
class Migration(migrations.Migration):
dependencies = [
('exchange_portal', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_... |
yoneken/gaze_arm | scripts/controller.py | #!/usr/bin/python
# -*- coding:utf-8 -*-
import roslib; roslib.load_manifest('gaze_arm')
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import Float64
from ros_gpio.srv import *
angles = [0., 0.]
gazebo_joint1 = None
gazebo_joint2 = None
def callback(msg):
global angles
angles[0] = angles[0... |
KiraHG/kiramath | kiramath/spec.py | # -*- coding: utf-8 -*-
from . import calc
from . import const
from . import elem
def bernoulli(n):
A = [0] * (n+1)
for m in range(n+1):
A[m] = 1/(m+1)
for j in range(m, 0, -1):
A[j-1] = j*(A[j-1] - A[j])
return A[0]
def erf(x):
expquad = lambda t: elem.exp(-t**2)
pi =... |
rjw57/rbc | rbc/codegen/__init__.py | """
LLVM code generation.
"""
from __future__ import print_function
import contextlib
import functools
import future.moves.collections as collections
from future.builtins import bytes
from llvmlite import ir
import rbc.exception as exc
# HACK: make sure all the AST node types are imported and registered
from . imp... |
stczhc/neupy | neupy/algorithms/associative/hebb.py | from neupy.core.properties import BoundedProperty
from .base import BaseStepAssociative
__all__ = ('HebbRule',)
class HebbRule(BaseStepAssociative):
""" Hebbian Learning Unsupervised Neural Network.
Network can learn associations from data and emulate similar behaviour
as dog in Pavlov experiment.
... |
Azure/azure-sdk-for-python | sdk/confidentialledger/azure-mgmt-confidentialledger/azure/mgmt/confidentialledger/aio/_configuration.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
lnsongxf/Python_for_everybody | new9.py | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 20:43:01 2016
@author: songxf
"""
astr="Hello Bob"
try:
istr=int(astr)
except:
istr=-1
print('First',istr)
astr='123'
try:
istr=int(astr)
except:
istr=-1
print('Second',istr) |
alunduil/etest | etest/lexers/bash.py | import logging
import os
from typing import Any, Optional
import click
import ply.lex
logger = logging.getLogger(__name__)
reserved = (
"CASE",
"COPROC",
"DO",
"DONE",
"ELIF",
"ELSE",
"ESAC",
"FI",
"FOR",
"FUNCTION",
"IF",
"IN",
"SELECT",
"THEN",
"TIME",
... |
NorfolkDataSci/presentations | building-bayes/prepare_data.py | import re
import string
def remove_punctuation(s):
table = string.maketrans("","")
return s.translate(table, string.punctuation)
def tokenize(text):
text = remove_punctuation(text)
text = text.lower()
return re.split("\W+", text)
def get_counts(words):
counts = {}
for word in words:
... |
ONSdigital/eq-survey-runner | tests/app/validation/test_mutually_exclusive_validator.py | import unittest
from wtforms.validators import ValidationError
from app.validation.error_messages import error_messages
from app.validation.validators import MutuallyExclusiveCheck
class TestMutuallyExclusive(unittest.TestCase):
def setUp(self):
self.validator = MutuallyExclusiveCheck()
def test_m... |
DevinGeo/moviepy | docs/conf.py | # -*- coding: utf-8 -*-
#
# MoviePy documentation build configuration file, created by
# sphinx-quickstart on Sat Jul 13 14:47:48 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... |
forrest-mao/python-sdk | qiniu/config.py | # -*- coding: utf-8 -*-
from qiniu import zone
RS_HOST = 'http://rs.qiniu.com' # 管理操作Host
RSF_HOST = 'http://rsf.qbox.me' # 列举操作Host
API_HOST = 'http://api.qiniu.com' # 数据处理操作Host
UC_HOST = 'https://uc.qbox.me' # 获取空间信息Host
_BLOCK_SIZE = 1024 * 1024 * 4 # 断点续上传分块大小,该参数为接口规格,暂不支持修改
_config = {
'default_zone... |
noelevans/sandpit | naive_bayes_hand_rolled.py | """ Example of Gaussian Naive Bayes classifier implemented from scratch
Originally taken from
http://machinelearningmastery.com/naive-bayes-classifier-scratch-python/
"""
import operator
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
def separate_by_class(tr... |
philvoyer/ANI2012A17 | Module07/EXE07/ANI2012A17_GenerateSphere.py | # ANI2102A17_GenerateSphere.py | Programmation Python avec Maya | coding=utf-8
# Création d'une sphère par programmation
import maya
# paramètres du programme
diameter = 10
divisionX = 12
divisionY = 8
print "<generate a new sphere of diameter: %s divisionX: %s divisionY: %s>" % (diameter, divisionX, divisionY)
sph... |
IntSPstudio/it8c | library/encryption.py | #|==============================================================|#
# Made by IntSPstudio
# Thank you for using this library!
# Plugin: Encryption
#|==============================================================|#
#IMPORT
import hashlib
#SHA1
def cpd51249(string):
hasht = hashlib.sha1()
hasht.update(string.encode("ut... |
benwilburn/fitist | FITist_project/FITist_project/settings.py | """
Django settings for FITist_project project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
im... |
karel-brinda/prophyle | prophyle/prophyle_assignment.py | #! /usr/bin/env python3
"""ProPhyle assignment algorithm (reference implementation).
Example: ./prophyle/prophyle_index/prophyle_index query -k 5 -u -b _index_test/index.fa tests/simulation_bacteria.1000.fq |./prophyle/prophyle_assignment.py -m h1 -f sam _index_test/tree.nw 5 -
Author: Karel Brinda <kbrinda@hsph.har... |
ingenieroariel/pinax | apps/misc/management/commands/build_media.py | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from optparse import make_option
import os
import sys
import glob
import shutil
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback
# Based on the collectmedia management command by Brian... |
sirmdub/stravaNotifier | sampleCode/samples.py | #!/bin/python
import ConfigParser
import json
import io
from stravalib.client import Client
config = ConfigParser.ConfigParser()
client = Client()
config.read('config.ini')
client.access_token = config.get("access","access_token")
app_friends = config.get("app","friends")
redis_host = config.get("access", "redis_host... |
ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/142_Linked_List_Cycle_II.py | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None or head.next.next is None:
r... |
raviolli77/machineLearning_breastCancer_Python | dash_dashboard/app.py | #!/usr/bin/env python3
import sys
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import global_vars as gv
import pandas as pd
sys.path.insert(0, '../src/python/')
from data_extraction import breast_cancer, names
sys.path.pop(0)
# T... |
ALECoin/ALECoin | share/qt/clean_mac_info_plist.py | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the ALECoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inF... |
erigones/ludolph-ansible | ludolph_ansible/playbook_callbacks.py | # -*- coding: utf-8 -*-
"""
This file is part of Ludolph: Ansible plugin
Copyright (C) 2015 Erigones, s. r. o.
See the LICENSE file for copying permission.
"""
from __future__ import absolute_import
import fnmatch
from six import text_type, iteritems
from ansible import constants
from ansible import utils
from ansib... |
mattloper/opendr | opendr/test_camera.py | #!/usr/bin/env python
# encoding: utf-8
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
import unittest
import numpy as np
from .camera import *
import chumpy as ch
class TestCamera(unittest.TestCase):
def get_cam_params(self):
v_raw = np.sin(np.arange(90... |
gersolar/goescalibration | goescalibration/instrument.py | from datetime import datetime
from netcdf import netcdf as nc
from channels import channel_01
short = (lambda f, start=2, end=-2:
".".join((f.split('/')[-1]).split('.')[start:end]))
get_datetime = lambda f: datetime.strptime(short(f, 1), '%Y.%j.%H%M%S')
channels = {
1: channel_01,
}
def calibration(dat... |
ahlusar1989/geocoder | geocoder/bing.py | #!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
from geocoder.base import Base
from geocoder.keys import bing_key
import re
class Bing(Base):
"""
Bing Maps REST Services
=======================
The Bing™ Maps REST Services Application Programming Interface (API)
provides a... |
bourdibay/EbayAlertor | Alertor/UnitTest/TestResultsDiskIO.py |
import sys
import os
import datetime
# import in ../
sys.path.append(os.path.join(os.path.split(__file__)[0], os.pardir))
import unittest
from Results.ResultsDiskIO import ResultsDiskIO
from Alerts.Alert import Alert
from Results.Result import Result, Interval, Price
class TestResultsDiskIO(unittest.TestCase):
... |
djrrb/drawbotlab | glyph.py | from fontTools.pens.basePen import BasePen
from robofab.objects.objectsRF import RFont, RGlyph
from drawBot import *
class DrawBotPen(BasePen):
"""
A pen that draws a glyph into a drawbot.
I don't think this can deal with components or anything so be careful.
"""
def _moveTo(self, coordina... |
brendanator/predictron | predictron/predictron.py | import tensorflow as tf
from . import util
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('batch_size', 100, 'Batch size')
tf.app.flags.DEFINE_integer('input_height', None, 'Height of input')
tf.app.flags.DEFINE_integer('input_width', None, 'Width of input')
tf.app.flags.DEFINE_integer('input_channels', None, ... |
Rivefount/estudos | basic/list2.py | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic list exercises
# D. Given a list of numbers, return a list where
# a... |
EdinburghGenomics/clarity_scripts | scripts/generate_hamilton_input_qpcr_1to24.py | #!/usr/bin/env python
import re
from operator import itemgetter
from EPPs.common import GenerateHamiltonInputEPP, InvalidStepError
class GenerateHamiltonInputQPCR(GenerateHamiltonInputEPP):
""""Generate a CSV containing the necessary information to for the Make QPCR 1 to 24 samples Hamilton method"""
_use_l... |
babbel/floto | tests/unit/decider/test_dynamic_decider.py | import pytest
import floto.decider
from floto.specs.task import ActivityTask
from floto.specs import DeciderSpec
@pytest.fixture
def task():
return ActivityTask(domain='d', name='activity2', version='v1')
@pytest.fixture
def decider_spec(task):
activity_tasks = [task]
decider_spec = DeciderSpec(domain='d... |
Axiologue/DjangoRestMultipleModels | tests/test_object_view.py | from django.test import override_settings
from django.core.exceptions import ValidationError
from django.conf.urls import url
from django.core.cache import cache
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework import status, filters
from .utils import MultipleModelTestCase
from .models... |
GingerNinja23/programming-questions | max_in_the_pool.py | '''
You'll be given a number n, which would be followed by n lines of
numbers A1, A2, .... , An.
If
Ai == 0 : You have to print the maximum amongst all the numbers seen till now.
Ai == -1 : Delete the last element. (i.e this element wouldn't be considered from
now on)
Note that 0, -1, wouldn't be added to the pool o... |
8enmann/model-based-rl | misc_util.py | import numpy as np
import random
def explained_variance(ypred,y):
"""
Computes fraction of variance that ypred explains about y.
Returns 1 - Var[y-ypred] / Var[y]
interpretation:
ev=0 => might as well have predicted zero
ev=1 => perfect prediction
ev<0 => worse than just ... |
xuru/pyvisdk | pyvisdk/do/type_description.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def TypeDescription(vim, *args, **kwargs):
'''Static strings used for describing an objec... |
taeguk/github_listener | examples/ex_notification.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
from github_listener import (
GithubAccount,
GithubListener,
)
account = GithubAccount("username", "password")
listener = GithubListener(account)
@listener.notification
def on_notification(change):
print("[*] notification occurs!")
for group in change.n_grou... |
fishstamp82/moltools | moltools/test/test_read_dal.py | import unittest
import numpy as np
import warnings
warnings.simplefilter('error')
from nose.plugins.attrib import attr
from moltools import read_dal
HF_FILE = """
************************************************************************
*************** Dalton - An Electronic Structure Program ************... |
pickleshare/pickleshare | test_pickleshare.py | from __future__ import print_function
import os
from pickleshare import PickleShareDB
def test_pickleshare(tmpdir):
db = PickleShareDB(tmpdir)
db.clear()
print("Should be empty:",db.items())
assert len(db) == 0
db['hello'] = 15
assert db['hello'] == 15
db['aku ankka'] = [1,2,313]
asser... |
Serag8/Bachelor | google_appengine/google/appengine/tools/devappserver2/http_runtime.py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
carthage-college/django-djequis | djequis/core/schoology/tests/test_views.py | from django.conf import settings
from django.test import TestCase
from django.core.urlresolvers import reverse
from djequis.core.schoology.sql import SELECT_GRADE, UPDATE_GRADE
from djtools.utils.logging import seperator
from djzbar.utils.informix import get_session
import json
import logging
logger = logging.getLo... |
vinokurov/salty_tickets | salty_tickets/mts_controllers.py | import itertools
from flask import url_for
from salty_tickets.controllers import EventController, OrderSummaryController
from salty_tickets.models import RegistrationGroup, OrderProduct, Order, Product, Registration
from salty_tickets.products import WORKSHOP_OPTIONS, FESTIVAL_TICKET, FestivalGroupDiscountProduct
from ... |
ahartz1/python_koans | python3/koans/about_iteration.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutIteration(Koan):
def test_iterators_are_a_type(self):
it = iter(range(1,6))
fib = 0
for num in it:
fib += num
self.assertEqual(15, fib)
def test_iterating_with_next(self):
... |
matoxxx/django-angularjs-webpack | djangoangularwebpack/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep th... |
sergey-dryabzhinsky/dedupsqlfs | dedupsqlfs/db/migrations/m20171103001.py | # -*- coding: utf8 -*-
#
# DB migration 001 by 2017-11-03
#
# New statistics for subvolume - root diff in blocks / bytes
#
__author__ = 'sergey'
__NUMBER__ = 20171103001
def run(manager):
"""
:param manager: Database manager
:type manager: dedupsqlfs.db.sqlite.manager.DbManager|dedupsqlfs.db.mysql.manage... |
diffeo/py-nilsimsa | version.py | # -*- coding: utf-8 -*-
# Author: Douglas Creager <dcreager@dcreager.net>
# This file is placed into the public domain.
# Calculates the current version number. If possible, this is the
# output of “git describe”, modified to conform to the versioning
# scheme that setuptools uses. If “git describe” returns an erro... |
Azure/azure-sdk-for-python | sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2019_08_01/aio/operations/_resource_health_metadata_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
Derfies/wxnodegraph | wxnodegraph/plug.py | import math
import wx
from constants import *
from wire import Wire
class Plug( object ):
def __init__( self, text, pos, radius, type_, node ):
self._text = text
self._node = node
self._pos = wx.Point( pos[0], pos[1] ) # In node space
self.radius = radius
self._type = t... |
itdxer/neupy | neupy/algorithms/minsearch/wolfe.py | """
Main source code from Pylearn2 library:
https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/\
optimization/linesearch.py
"""
import tensorflow as tf
from neupy.utils import asfloat
def sequential_or(*conditions):
"""
Use ``or`` operator between all conditions. Function is just
a syntax sugar th... |
sonusz/PhasorToolBox | phasortoolbox/parser/cfg_2.py | # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
import array
import struct
import zlib
from enum import Enum
from pkg_resources import parse_version
from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
if parse_version(ks_version)... |
FreddieV4/DailyProgrammerChallenges | Easy Challenges/Challenge 0261 Easy - verifying 3x3 magic squares/solutions/solution.py | <<<<<<< HEAD
=======
# @Author: Ouss4
# @Github : github.com/Ouss4
# @Date: 29/04/2016
# @Description: Solution to Easy #261.
>>>>>>> master
from math import sqrt
def getLines(square, N):
return [square[i:i + N] for i in range(0, len(square), N)]
def getColumns(square, N):
return getLines([square[i+j] for j ... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_available_private_endpoint_types_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
piotrmaslanka/systemy | examples/ipcExample.py | from yos.rt import BaseTasklet
from yos.tasklets import Tasklet, Profile
from yos.io import NetworkSocket
class WorkerTasklet(BaseTasklet):
def on_message(self, source, number):
Tasklet.send_to(source, number ** 2)
class IPCTasklet(BaseTasklet):
def on_startup(self):
Tasklet.st... |
bburan/psiexperiment | tests/test_output.py | import pytest
import numpy as np
from psi.token.primitives import Cos2EnvelopeFactory, ToneFactory
@pytest.fixture()
def tb1(epoch_output):
tone = ToneFactory(fs=epoch_output.fs, level=0, frequency=100,
calibration=epoch_output.calibration)
envelope = Cos2EnvelopeFactory(fs=epoch_outp... |
nrudenko/anarcho | anarchoApp/anarcho/models/user.py | import time
from sqlalchemy import Column, Integer, String
from anarcho import db
from sqlalchemy.orm import relationship
from werkzeug.security import generate_password_hash, check_password_hash
class User(db.Model):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(20... |
thelazier/dash | test/functional/wallet_keypool_hd.py | #!/usr/bin/env python3
# Copyright (c) 2014-2015 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 keypool, and interaction with wallet encryption/locking
# Add python-bitcoinrpc to... |
luanrafael/pygame-site | FlaskApp/src/views/login.py | # coding: utf-8
from flask_login import login_user, logout_user
from flask import Blueprint, request, redirect, render_template
from src.models.user import User
__author__ = 'iury'
view = Blueprint('login', __name__)
@view.route('/login', methods=["GET", "POST"])
def login():
if len(request.form) == 0:
... |
51reboot/actual_13_homework | 03/peter/homework8.py | #!/usr/bin/env python
# coding: utf-8
log_file = open("access.log", "r")
ip_dict = {}
for line in log_file:
ip = line.split(" ")[0]
ip_dict[ip] = ip_dict.get(ip, 0) + 1
ip_dict = ip_dict.items()
for i in range(len(ip_dict)-1, 0, -1):
for j in range(0, i):
if ip_dict[y][1] > ip_dict[y+1][1]:
... |
mccarrion/python-practice | crash_course/chapter14/ship.py | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self, ai_settings, screen):
"""Initialize the ship and set its starting position."""
super(Ship, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
# Load the ship image and ... |
thunderhoser/GewitterGefahr | gewittergefahr/gg_utils/grids.py | """Processing methods for gridded data.
DEFINITIONS
"Grid point" = center of grid cell (as opposed to edges of the grid cell).
"""
import pickle
import os.path
import numpy
from gewittergefahr.gg_utils import general_utils
from gewittergefahr.gg_utils import longitude_conversion as lng_conversion
from gewittergefahr... |
Azure/azure-sdk-for-python | sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/aio/operations/_pools_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
tribut/vdirsyncer | setup.py | # -*- coding: utf-8 -*-
'''
Vdirsyncer is a synchronization tool for vdir. See the README for more details.
'''
# Packagers: Vdirsyncer's version is automatically detected using
# setuptools-scm, but that one is not a runtime dependency.
#
# Do NOT use the GitHub's tarballs, those don't contain any version information... |
baverman/baito | baito/app.py | import imp
from urllib import urlencode
from routes.mapper import Mapper
from routes.util import URLGenerator, GenerationException
from webob import Request, Response
from webob.exc import HTTPException, HTTPNotFound, HTTPFound
from wsgiref.simple_server import make_server
from functools import wraps
from .utils im... |
hpparvi/Parviainen-2017-WASP-80b | src/core.py | from __future__ import division
import warnings
import os
import sys
import math as m
import logging
import astropy.io.fits as pf
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib.pyplot as pl
from collections import namedtuple
from glob import glob
from os.path import join, exists, basen... |
anthrotype/extractor | Lib/extractor/formats/opentype.py | import time
from fontTools.ttLib import TTFont, TTLibError
from fontTools.ttLib.tables._h_e_a_d import mac_epoch_diff
from fontTools.misc.textTools import num2binary
from fontTools.pens.boundsPen import ControlBoundsPen
from extractor.exceptions import ExtractorError
from extractor.tools import RelaxedInfo, copyAttr
#... |
YeoLab/gscripts | gscripts/structure/conserved_structure.py | import itertools
import structure
from subprocess import call, PIPE, Popen
from collections import defaultdict
import pybedtools
import math
import numpy as np
import sys
from optparse import OptionParser
## Define structural elements across evolution.
#input: human "links" and a list of species to compare to
#outpu... |
Frederick-S/quiz | tests/test_quiz.py | import unittest
import json
from datetime import datetime
from flask import current_app, url_for
from app.bootstrap import create_app
from app.models.user import User
from app.models.category import Category
from app.models.quiz import Quiz
from app.models.quiz_section import QuizSection
from app.models.question import... |
WmHHooper/aima-python | submissions/Colburn/myNN.py | # References:
#
# https://www.tensorflow.org/guide/low_level_intro
#
# only needed for python 2.7
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
import numpy as np
from numpy import array
from numpy import float32
# a complete input set on 7 bits
# ... |
nirenjan/pysemver | libsemver/semver.py | """
SemVer management class
"""
from .semver_core import SemVerCore
class SemVer(SemVerCore):
def format(self, format_string):
"""
Format the SemVer object using the following format specifiers
{major}, {minor}, {patch}, {prerelease}, {build_metadata}
"""
prerelease_format... |
andrewchenshx/vnpy | vnpy/gateway/binance/binance_gateway.py | """
Gateway for Binance Crypto Exchange.
"""
import urllib
import hashlib
import hmac
import time
from copy import copy
from datetime import datetime
from enum import Enum
from threading import Lock
from vnpy.api.rest import RestClient, Request
from vnpy.api.websocket import WebsocketClient
from vnpy.trader.constant ... |
vardis/pano | src/pano/control/__init__.py | '''
Copyright (c) 2008 Georgios Giannoudovardis, <vardis.g@gmail.com>
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,... |
rafaelasantos/Estrutura-de-Dados | min_max.py | def min_max(lista, maximo, minimo, k):
maximo = maior
minimo = menor
if(k <= len(lista)):
return maior, menor
if (maximo < lista[k]):
maximo = lista[k]
if (minimo > lista[k]):
minimo = lista[k]
k = k + 1
return maximo_minimo(lista, maior, menor... |
compas-dev/compas | src/compas_rhino/utilities/misc.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
try:
basestring
except NameError:
basestring = str
import os
import sys
import ast
from compas_rhino.forms import TextForm
from compas_rhino.forms import ImageForm
import System
import rhinoscriptsy... |
davisd50/sparc.db | sparc/db/splunk/testing.py | import warnings
import xml.etree.ElementTree as ET
from zope import component
from sparc.testing.testlayer import SparcZCMLFileLayer
import sparc.testing
from sparc.utils.requests.request import Request
from kvstore import current_kv_names
class SparcDBSplunkLayer(SparcZCMLFileLayer, Request):
"""Tuple of K... |
github/codeql | python/ql/test/query-tests/Metrics/lines/lines.py | line = 1
line = 2
line = 3
line = 4
line = 5
line = 6
line = 7
line = 8
line = 9
line = 10
line = 11
line = 12
line = 13
#comment 1
line = 14
line = 15
line = 16
line = 17
line = 18
line = 19
line = 20
line = 21
line = 22
#comment 2
#comment 3
#comment 4
line = 23
line = 24
line = 25
line = 26
line = 27
line =... |
aldwyn/effigia | apps/portfolios/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django_prometheus.models import ExportModelOperationsMixin
from ordered_model.models import OrderedModel
from ordered_model.models import OrderedModelManager
... |
peterwilletts24/Monsoon-Python-Scripts | rain/land_sea_diurnal/rain_mask_save_lat_lon_bay_of_bengal.py | import os, sys
import datetime
import iris
import iris.unit as unit
import iris.analysis.cartography
import numpy as np
from iris.coord_categorisation import add_categorised_coord
diag = 'avg.5216'
cube_name_explicit='stratiform_rainfall_rate'
cube_name_param='convective_rainfall_rate'
pp_file_path='/projects/casc... |
DailyActie/Surrogate-Model | 01-codes/tensorflow-master/tensorflow/python/util/protobuf/compare_test.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
tmthydvnprt/Monopoly | monopoly/Player.py | """
Player.py - File for defining a Player class.
"""
import logging
import numpy as np
from monopoly.Constants import CARD_WIDTH, MAX_LEVEL, MAX_HOUSE_LEVEL, MAX_DOUBLES, JAIL_COST, NUM_PROPERTIES, INIT_CASH
from monopoly.Constants import COLOR_COUNTS, COLOR_PROPERTIES, PROPERTY_PRICES, PROPERTY_NAMES, SPACE
from mo... |
cliffano/swaggy-jenkins | clients/python-legacy/generated/test/test_label1.py | # coding: utf-8
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unitte... |
carletes/libcloud-vagrant | samples/cluster.py | # Copyright (c) 2014 Carlos Valiente
#
# 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, dis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.