code stringlengths 3 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int64 3 1.05M |
|---|---|---|---|---|---|
import unittest
from tempfile import mkdtemp, mkstemp
import shutil
from .. import OECDatabase, load_db_from_url # load from root
from ..database import LoadDataBaseError
from .patches import TestCase
from .. import astroquantities as aq
class TestDataBaseLoading(TestCase):
def setUp(self):
# create t... | ryanvarley/ExoData | exodata/tests/test_database.py | Python | mit | 6,272 |
from .generate_detachment_ltd_erosion import DetachmentLtdErosion
from .generate_erosion_by_depth_slope import DepthSlopeProductErosion
__all__ = ["DetachmentLtdErosion", "DepthSlopeProductErosion"]
| landlab/landlab | landlab/components/detachment_ltd_erosion/__init__.py | Python | mit | 200 |
from datetime import datetime
__author__ = 'Gengyu Shi'
class Ticker(object):
def __init__(self, **kwargs):
self.mid = kwargs.get("mid")
self.bid = kwargs.get("bid")
self.ask = kwargs.get("ask")
self.last_price = kwargs.get("last_price")
self.low = kwargs.get("low")
... | shigengyu/bitfinex-python | bitfinex/ticker.py | Python | mit | 556 |
import os
import pysam
import unittest
from TestUtils import checkFieldEqual
import copy
SAMTOOLS = "samtools"
WORKDIR = "pysam_test_work"
DATADIR = "pysam_data"
class ReadTest(unittest.TestCase):
def buildRead(self):
'''build an example read.'''
a = pysam.AlignedSegment()
a.query_name ... | nlhepler/pysam | tests/AlignedSegment_test.py | Python | mit | 17,059 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | openstack/keystone | keystone/common/policies/base.py | Python | apache-2.0 | 3,791 |
import unicodedata
# Returns the description of the last purchase
# Of none if none is found
def get_last_purchase_description(last_purchase):
if last_purchase:
description = _('last purchase: %(last_sub)s on %(date_joined)s') % {
'last_sub': last_purchase.customer.get_short_name(),
... | flavoi/diventi | diventi/products/utils.py | Python | apache-2.0 | 1,004 |
# Copyright (c) 2013 Neil Domalik
#
# 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 distribute... | makerplane/pyEfis | pyefis/instruments/pa/__init__.py | Python | gpl-2.0 | 3,922 |
import json
import os
import sys
import numpy as np
from scipy.io import loadmat
from scipy.io.matlab.mio4 import VarReader4
VARIABLE_INDICES = set()
VARIABLES = {}
## helper functions
def load_info_from_mat(data_file,
filter=[],
gather_desc=False):
... | mandersondesign/SimViz-1.0 | simviz/public/simviz/scripts/mat_conversion_v2.py | Python | gpl-2.0 | 14,758 |
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Sebastian Bechtel
# Copyright (c) 2013 Tao Sauvage
# Copyright (c) 2014 Sebastian Kricner
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Tycho Andersen
# Copyright (c) 2014 Craig Barnes
# Copyright (c) 2015 farebord
# Copyright (c) 2015 Jörg Thalheim (Mic92)
# Copyright ... | zordsdavini/qtile | libqtile/widget/wlan.py | Python | mit | 3,124 |
# Copyright (C) 2006 Douglas Gregor <doug.gregor -at- gmail.com>.
# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test scatter() collective.
from __future__ import print_function
... | davehorton/drachtio-server | deps/boost_1_77_0/libs/mpi/test/python/scatter_test.py | Python | mit | 1,318 |
#!/usr/bin/env python3
import sys
import argparse
from pprint import pprint
# from grabber.search import BOORU_AWAILABLE, print_sites
# from grabber.grabber import Grabber
import grabber.parsers.common as common
from grabber.grabber_new import Grabber
def site_alias(alias):
if alias == "sankaku":
return... | sora7/kiririn-grabber | src/kiririn-cli.py | Python | gpl-2.0 | 6,447 |
"""
********************************************************************************
* Name: utilities.py
* Author: Scott Christensen
* Created On: 2015
* Copyright: (c) Brigham Young University 2015
* License: BSD 2-Clause
********************************************************************************
"""
import jso... | tethysplatform/tethys | tethys_compute/graveyard.py | Python | bsd-2-clause | 5,270 |
import logging
import pytest
from flexmock import flexmock
from borgmatic.borg import extract as module
from ..test_verbosity import insert_logging_mock
def insert_execute_command_mock(command, working_directory=None):
flexmock(module).should_receive('execute_command').with_args(
command, working_direc... | witten/borgmatic | tests/unit/borg/test_extract.py | Python | gpl-3.0 | 10,002 |
"""
Support for LIFX Cloud scenes.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scene.lifx_cloud/
"""
import asyncio
import logging
import voluptuous as vol
import aiohttp
import async_timeout
from homeassistant.components.scene import Scene
from h... | MungoRae/home-assistant | homeassistant/components/scene/lifx_cloud.py | Python | apache-2.0 | 2,931 |
import collections
import datetime
import gc
import sys
from django.conf import settings
from django.http import Http404
from elasticsearch import Elasticsearch, NotFoundError
from simple_elasticsearch.search import Result
from . import settings as es_settings
from .signals import post_indices_create, post_indices_reb... | jaddison/django-simple-elasticsearch | simple_elasticsearch/utils.py | Python | bsd-3-clause | 7,968 |
__author__ = 'Administrator'
import ConfigParser
def getValue(ini_file_path, section, key):
with open(ini_file_path, "rb") as fp:
config = ConfigParser.ConfigParser()
config.readfp(fp)
return config.get(section, key) | xiaomogui/lulu | lulu/lulu/python/parseIniFile.py | Python | apache-2.0 | 224 |
__version__ = '0.6.18'
from exporters.export_managers import BasicExporter # NOQA
| scrapinghub/exporters | exporters/__init__.py | Python | bsd-3-clause | 85 |
# -*- encoding: utf-8 -*-
import subprocess
import re
import os
import shutil
import configurer
import common
from src.utils.logger import log
def remove_dirs(dirs):
for path_dir in dirs:
if os.path.exists(path_dir):
shutil.rmtree(path_dir)
def remove_file(filepath):
os.remove(filepath)
... | QProjectOrg/QRepo | src/utils/commonscript.py | Python | mit | 5,400 |
#!/usr/bin/env python
import os
import sys
from datetime import datetime
sys.path.insert(0, os.path.join(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))), 'src'))
from epidb_client import EpiDBClient
import config
api_key = config.api_key
user_id = config.user_id
profile_survey_id = co... | pfhm/epidb-client-python | examples/update_profile.py | Python | agpl-3.0 | 1,006 |
# Copyright 2012-2016 Ryan "ZDBioHazard" Turner <zdbiohazard2@gmail.com>
# 2016-2020 Nick Boultbee
#
# 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... | Meriipu/quodlibet | quodlibet/ext/playorder/playcounteq.py | Python | gpl-2.0 | 1,860 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This test check the realms and the tree feature of realms (children)
"""
from __future__ import print_function
import os
import time
import shlex
import subprocess
import copy
import requests
import unittest2
class TestRealms(unittest2.TestCase):
"""
This cla... | Alignak-monitoring-contrib/alignak-backend | test/test_realms.py | Python | agpl-3.0 | 24,701 |
# -*- coding: utf-8 -*-
"""
sphinx.builders.mobi
~~~~~~~~~~~~~~~~~~~~
Build mobi files.
Originally derived from epub.py.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import shutil
import sys
import time
import... | EronHennessey/sphinx-mobi-builder | sphinx/builders/mobi.py | Python | bsd-3-clause | 21,095 |
from tkinter import *
import time
import random
height = 600
width = 1200
dialog = Tk()
tk = None
canvas = None
players_label = Label(dialog, text="How many players, 2 or 3: ")
players_label.pack()
players_entry = Entry(dialog)
players_entry.pack()
players_entry.insert(0,"2")
num_players = 2
snake1 = None
snake2 = ... | caw13/CCSUTechItOutPiTop | python/sample_programs/slither_big_worm.py | Python | gpl-3.0 | 13,393 |
from flask import render_template, jsonify, request
from maraschino.tools import requires_auth, get_setting_value, convert_bytes
from maraschino import app, logger
from maraschino.models import NewznabSite
from maraschino.database import db_session
from xmltodict import xmltodict
import urllib
# Newznab Category Lis... | gugahoi/maraschino | modules/search.py | Python | mit | 6,152 |
#!/usr/bin/env python
##########################################################################
## Sequence Files Concate ##
## Author: Tyghe Vallard ##
## Date: 5/25/2012 ##
## Version: 1.0 ... | demis001/bio_pieces | bio_pieces_old/sequence_files_concat.py | Python | gpl-2.0 | 8,594 |
"""
Settings used when generating static assets for use in tests.
For example, Bok Choy uses two different settings files:
1. test_static_optimized is used when invoking collectstatic
2. bok_choy is used when running CMS and LMS
Note: it isn't possible to have a single settings file, because Django doesn't
support bo... | caesar2164/edx-platform | cms/envs/test_static_optimized.py | Python | agpl-3.0 | 1,825 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from pagseguro.models import Checkout, Transaction, TransactionHistory
class CheckoutAdmin(admin.ModelAdmin):
list_display = ('id', 'code', 'date', 'success',)
list_display_links = ('id', )
search_fields = [... | vintasoftware/django-pagseguro2 | pagseguro/admin.py | Python | mit | 1,054 |
import time
import itarget_connection
import iserial_like
class SerialConnection(itarget_connection.ITargetConnection):
"""
ITargetConnection implementation for generic serial ports.
Designed to utilize SerialConnectionLowLevel (see __init__).
Since serial ports provide no default functionality for s... | jtpereyda/sulley | sulley/serial_connection.py | Python | gpl-2.0 | 5,073 |
from django.conf.urls.defaults import *
from twistranet.core.views import AsView
from views import *
urlpatterns = patterns('sharing',
url(r'^like_toggle_by_id/(\d+)$', AsView(LikeToggleView, lookup = 'id'), name=LikeToggleView.name),
url(r'^like_toggle_by_slug/(\d+)$', AsView(LikeToggleView, lookup = 'slug')... | numericube/twistranet | twistranet/sharing/urls.py | Python | agpl-3.0 | 351 |
import pytest
import json
from libnacl.secret import SecretBox
from hashlib import sha256
from indy_client.test.cli.constants import INVALID_SYNTAX
from indy_client.test.cli.helper import createUuidIdentifier, addNym
attrib_name = 'dateOfBirth'
secretBox = SecretBox()
enc_data = secretBox.encrypt(json.dumps({'name... | spivachuk/sovrin-node | indy_client/test/cli/test_send_get_attr.py | Python | apache-2.0 | 4,813 |
from BinPy.Algorithms.QuineMcCluskey import QM
from BinPy.Algorithms.MooreOptimizer import *
from BinPy.Algorithms.AnalogFormulas import *
| coder006/BinPy | BinPy/Algorithms/__init__.py | Python | bsd-3-clause | 139 |
# Copyright 2019 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... | chemelnucfin/tensorflow | tensorflow/contrib/distribute/python/keras_multi_worker_correctness_test.py | Python | apache-2.0 | 7,922 |
import pygame
from fish import Fish
from seaweed import Seaweed
class Water:
def __init__(self):
# color, pos_x, pos_y, width, height
self.mOrangeFish = Fish((255, 152, 0), 50, 175, 175, 100)
self.mGreyFish = Fish((96, 125, 139), 350, 130, 125, 200)
self.mRedFish = Fish((183, 28, 28), 200, 300, 175, 50... | joshl8n/school-projects | illustrate/water.py | Python | gpl-3.0 | 1,287 |
# storage.py
#
# Copyright (C) 2013 Yi-Wei Ci <ciyiwei@hotmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... | sitian/wing | services/whub/dev/storage.py | Python | gpl-2.0 | 1,265 |
"""
Created on Oct 19, 2016
@author: Jafar Taghiyar (jtaghiyar@bccrc.ca)
"""
import os
#===========================
# Django imports
#---------------------------
from django import forms
# from django.forms.extras.widgets import SelectDateWidget
#===========================
# App imports
#--------------------------... | jtaghiyar/single_cell_lims | apps/khayyam/forms.py | Python | mit | 2,439 |
#!/usr/bin/python
# this is the example script to use xgboost to train
import numpy as np
import xgboost as xgb
test_size = 550000
# path to where the data lies
dpath = 'data'
# load in training data, directly use numpy
dtrain = np.loadtxt( dpath+'/training.csv', delimiter=',', skiprows=1, converters={32: lambda x:... | dmlc/xgboost | demo/kaggle-higgs/higgs-numpy.py | Python | apache-2.0 | 1,714 |
"""
Copyright (C) 2015 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful... | MediaKraken/MediaKraken_Deployment | source/database/db_base_metadata.py | Python | gpl-3.0 | 15,516 |
#!/usr/bin/python
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Softw... | kevinpdavies/pycsw | tests/run_tests.py | Python | mit | 12,173 |
#!/usr/bin/env python2.7
import logging
import unittest
import clients
# keep logging output to a minumim for testing
logging.basicConfig(level=logging.ERROR)
################################################################################
class CommonInternetServices(unittest.TestCase):
#---------------------... | jheddings/indigo-netdev | test/test_clients.py | Python | mit | 3,574 |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import chainer
from chainer import training
from chainer.training import extensions
from net import Discriminator
from net import Generator
from updater import DCGANUpdater
from visualize import out_generated_image
import chainerm... | rezoo/chainer | examples/chainermn/dcgan/train_dcgan.py | Python | mit | 6,763 |
import os, time, urllib2, cookielib, json
root_network_address = 'http://ieeexplore.ieee.org/'
figures_network_address_prefix = root_network_address + 'rest/xpls/Figures/amsid/'
figures_network_address_prefix_dict = {'2007': 'ielx5/4269955/4269956/',
'2008': 'ielx5/4558014/4587335/'... | lidalei/IR-Project | src/CrawlDataset/CVPR_Download_Figures.py | Python | gpl-2.0 | 2,232 |
#pylint: disable=no-init,invalid-name
from __future__ import (absolute_import, division, print_function)
import mantid
import mantid.api
import mantid.simpleapi
import mantid.kernel
import numpy
class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm):
""" Class to generate grouping file
"""
def ca... | dymkowsk/mantid | Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py | Python | gpl-3.0 | 3,422 |
import urllib2
import hashlib
import sys
import os
if sys.platform == 'linux-i386' or sys.platform == 'linux2':
os.system("clear")
elif sys.platform == 'win32':
os.system("cls")
else:
os.system("cls")
print "==========================================================="
print u"Malware MD5 Hash... | zekicanozoktas/AVturk | AV_exec.py | Python | gpl-2.0 | 3,706 |
#!/usr/bin/env python
# Inspired by https://github.com/ayust/kitnirc/blob/master/kitnirc/contrib/healthcheck.py
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyr... | serbyy/MozDef | bot/modules/zilla.py | Python | mpl-2.0 | 3,046 |
# -*- coding: utf-8 -*-
"""Provides marker interfaces."""
from zope.interface import Interface
class IEmail(Interface):
pass
class IRole(Interface):
pass
class IUser(Interface):
pass
| thruflo/pyramid_simpleauth | src/pyramid_simpleauth/interfaces.py | Python | unlicense | 203 |
import gc
import os
import signal
from datetime import datetime
from errbot import BotPlugin, botcmd, arg_botcmd
from errbot.plugin_manager import global_restart
from errbot.utils import format_timedelta
class Health(BotPlugin):
@botcmd(template='status')
def status(self, mess, args):
""" If I am ali... | mrshu/err | errbot/core_plugins/health.py | Python | gpl-3.0 | 3,841 |
# file findingaids/fa/tests/models.py
#
# Copyright 2012 Emory University Library
#
# 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
... | emory-libraries/findingaids | findingaids/fa/tests/models.py | Python | apache-2.0 | 16,453 |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import alerts
import json
import random
import string
import unittest
import webtest
from google.appengine.api import memcache
from google.appengine.ext imp... | smilusingjavascript/blink | Tools/GardeningServer/alerts_test.py | Python | bsd-3-clause | 11,527 |
from __future__ import unicode_literals
from __future__ import absolute_import
from rest_framework.resources import ModelResource
from croisee.models import Puzzle, Dictionary
class PuzzleResource(ModelResource):
allowed_methods = ('GET', 'PUT', 'DELETE')
fields = ('code', 'title', 'owner', 'language', 'text'... | fiee/croisee | croisee/croisee/resources.py | Python | bsd-3-clause | 569 |
###############################################################################
# Name: ChoiceDialogDemo.py #
# Purpose: Test and demo file for eclib.ChoiceDialog #
# Author: Cody Precord <cprecord@editra.org> #
... | iut-ibk/P8-WSC-GUI | 3dparty/Editra/tests/controls/ChoiceDialogDemo.py | Python | gpl-2.0 | 3,688 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
"""
Todo:
1. sukurti aruodai.Vietos irasus:
A) Su pavadinimu Vilnius, ir sinonimu Wilno
B) Su pav... | justinasjaronis/hpn | united_geonames/tests.py | Python | gpl-3.0 | 562 |
"""cairo_museum.py"""
from lib.stage import Stage
class CairoMuseum(Stage):
"""Cairo Museum stage"""
def desc(self):
"""Describe action"""
action = """
After getting the first replicant, you call some old friends and some of them
mentions something about a hippie woman that likes no jokes. ... | brunitto/python-runner | lib/stages/cairo_museum.py | Python | mit | 1,374 |
import os
import unittest
from unittest import mock
from tests.recipes.recipe_ctx import RecipeCtx
from pythonforandroid.recipes.icu import ICURecipe
from pythonforandroid.util import build_platform
class TestIcuRecipe(RecipeCtx, unittest.TestCase):
"""
An unittest for recipe :mod:`~pythonforandroid.recipes.... | PKRoma/python-for-android | tests/recipes/test_icu.py | Python | mit | 4,719 |
import sys, thread, time, traceback, Queue, os
import pymedia
import pymedia.muxer as muxer
import pymedia.audio.acodec as acodec
import pymedia.video.vcodec as vcodec
import pymedia.audio.sound as sound
if os.environ.has_key( 'PYCAR_DISPLAY' ) and os.environ[ 'PYCAR_DISPLAY' ]== 'directfb':
import pydfb as pygame... | pymedia/pymedia | examples/v.py | Python | lgpl-2.1 | 15,168 |
#!/usr/bin/env python2.7
# Licensed to the StackStorm, Inc ('StackStorm') 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 "Lice... | tonybaloney/st2 | tools/generate_spec.py | Python | apache-2.0 | 1,091 |
"""CS 234 Assignment 2 Question 1a - Testing assumptions: Stock.py
"""
class Stock:
"""
A data type representing a single stock
Fields: name - str: the company name as a string
symbol - str: a string uniquely identifying the stock
price - non-negative float: last/current price
... | bcso/CS_234_Assignments | Assignment 2/Stock.py | Python | apache-2.0 | 3,006 |
from __future__ import unicode_literals
from django.apps import AppConfig
class NeuropowertoolboxConfig(AppConfig):
name = 'neuropowertoolbox'
| neuropower/neuropower | neuropower/apps/neuropowertoolbox/apps.py | Python | mit | 148 |
config = {
# mozconfig file to use, it depends on branch and platform names
"platform": "macosx64",
"update_platform": "Darwin_x86_64-gcc3",
"mozconfig": "%(branch)s/browser/config/mozconfigs/macosx-universal/l10n-mozconfig",
"bootstrap_env": {
"SHELL": '/bin/bash',
"MOZ_OBJDIR": "ob... | simar7/build-mozharness | configs/single_locale/macosx64.py | Python | mpl-2.0 | 2,755 |
### Definitely not pretty ###
import re
with open('10.in') as input:
lines = input.readlines()
bots = {}
output = {}
class Bot:
v1 = 0
v2 = 0
low = None
high = None
output = 0
def setlh(self,low,high):
self.low = low
self.high = high
def act(self):
if(self.v1 != 0 and self.v2 !=0):
if self.output % 2... | ghlmtz/advent16 | 10/10.py | Python | gpl-3.0 | 1,412 |
"""Module to define error types."""
USERNAME = (0, "Username must be a string")
PASSWORD = (1, "Password must be a string")
AUTHENTICATE = (
2,
"Cannot authenticate since either password or username has not been set",
)
AUTH_TOKEN = (
3,
"Authentication header incorrect. Are you sure you rec... | fronzbot/blinkpy | blinkpy/helpers/errors.py | Python | mit | 440 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""".. currentmodule:: migrate.versioning.util"""
import warnings
import logging
from decorator import decorator
from pkg_resources import EntryPoint
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.pool import StaticPool
from migr... | davidvon/pipa-pay-server | site-packages/migrate/versioning/util/__init__.py | Python | apache-2.0 | 5,327 |
import unittest
from unittest.mock import patch
from taiga.models import IssueStatus, IssueStatuses
from taiga.requestmaker import RequestMaker
class TestIssueStatuses(unittest.TestCase):
@patch("taiga.models.base.ListResource._new_resource")
def test_create_issue_status(self, mock_new_resource):
rm ... | nephila/python-taiga | tests/test_issue_statuses.py | Python | mit | 559 |
"""
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
"""
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
n = len(... | Ahmed--Mohsen/leetcode | Trapping_Rain_Water.py | Python | mit | 1,420 |
from kubeflow import fairing
from kubeflow.fairing import http_utils
from kubeflow.fairing.constants import constants
EXPECTED_UA = constants.DEFAULT_USER_AGENT.format(VERSION=fairing.__version__)
class HTTPMock:
def request(self, *args, **kwargs):
if args and len(args) >= 4:
return args[3]['... | kubeflow/fairing | tests/unit/test_http_utils.py | Python | apache-2.0 | 1,450 |
from __future__ import print_function
from testfixtures import LogCapture
from twisted.trial import unittest
from twisted.python.failure import Failure
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from scrapy.http import Request, Response
from scrapy.spiders import ... | agreen/scrapy | tests/test_pipeline_media.py | Python | bsd-3-clause | 10,529 |
import pyspark
import peachbox.pipeline
import peachbox
import ujson as json
raw = peachbox.Spark.Instance().context().textFile('movies.json')
json_parser = peachbox.pipeline.JSONParser()
validator = peachbox.pipeline.Validator(['user_id', 'product_id', 'review', 'summary', 'profile_name',
... | PeachstoneIO/peachbox | scripts/stubs/sort_by_time.py | Python | apache-2.0 | 664 |
#!/usr/bin/python
import datetime
import time
print 'Starting logfLife at %s' % time.ctime()
f = open('logfLife.log','a')
f.write( 'Starting logLife at %s \n' % time.ctime() )
f.close()
while 1 :
try:
f = open('logfLife.log','a')
f.write( 'Alive at: %s \n' % time.ctime() )
f.close()
print 'Aliv... | slowrunner/RWPi | rwpilib/battery/logfLife.12bit.py | Python | gpl-3.0 | 542 |
from ddcz.tavern import LIST_ALL
from ..cases import SeleniumTestCase, MainPage
from ...model_generator import get_alphabetic_user_profiles, get_tavern_tables
from .pages_tavern import TavernTableListPage
class TestTavernListing(SeleniumTestCase):
def setUp(self):
super().setUp()
(
se... | dracidoupe/graveyard | ddcz/tests/test_ui/test_tavern/test_listing.py | Python | mit | 3,213 |
"""Discover and load entry points from installed packages."""
# Copyright (c) Thomas Kluyver and contributors
# Distributed under the terms of the MIT license; see LICENSE file.
from contextlib import contextmanager
import glob
from importlib import import_module
import io
import itertools
import os.path as osp
import... | sserrot/champion_relationships | venv/Lib/site-packages/entrypoints.py | Python | mit | 8,262 |
from django.urls import reverse
def test_perf_tags_get(authorized_sheriff_client, test_perf_tag, test_perf_tag_2):
resp = authorized_sheriff_client.get(reverse('performance-tags-list'))
assert resp.status_code == 200
assert len(resp.json()) == 2
assert resp.json()[0]['id'] == test_perf_tag.id
as... | jmaher/treeherder | tests/webapp/api/test_performance_tags.py | Python | mpl-2.0 | 483 |
"""
Tests for verify_student utility functions.
"""
import unittest
from datetime import timedelta
from unittest import mock
from unittest.mock import patch
import ddt
from django.conf import settings
from django.utils import timezone
from pytest import mark
from common.djangoapps.student.tests.factories import Use... | eduNEXT/edx-platform | lms/djangoapps/verify_student/tests/test_utils.py | Python | agpl-3.0 | 6,882 |
###################################################################################
## MODULE : spell.lang.helpers.usrhelper
## DATE : Mar 18, 2011
## PROJECT : SPELL
## DESCRIPTION: Helpers for user management
## --------------------------------------------------------------------------------
##
## Copy... | Spacecraft-Code/SPELL | src/spell/spell/lang/helpers/usrhelper.py | Python | lgpl-3.0 | 6,256 |
"""
Pexpect is a Python module for spawning child applications;
controlling them; and responding to expected patterns in their output.
Pexpect can be used for automating interactive applications such as
ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts
for duplicating software package installati... | blackPantherOS/packagemanagement | smartpm/smart/util/pexpect.py | Python | apache-2.0 | 42,546 |
import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
AuthUserFactory,
PreprintProviderFactory,
)
from osf.utils import permissions
@pytest.mark.enable_quickfiles_creation
class ProviderModeratorDetailTestClass:
@pytest.fixture()
def admin(self, provider):
... | mfraezz/osf.io | api_tests/providers/preprints/views/test_preprint_provider_moderator_detail.py | Python | apache-2.0 | 8,147 |
# I needed a string object that had the write function
class IOString: # todo subclass str?
# For a file like object, writes to the file while keeping
# a local buffer.
def __init__(self, fileObject=None):
self.f = fileObject
self.s = ""
def write(self, s):
... | TheChymera/matrix2latex | matrix2latex/IOString.py | Python | gpl-3.0 | 590 |
from authomatic import Authomatic
from authomatic.adapters import WerkzeugAdapter
from flask import Blueprint, flash, jsonify, make_response, redirect, render_template, request, session
from google.appengine.api import users
from todo.client import make_client
from todo.config import AUTH_SECRET, AUTH_SERVICES
from tod... | slackpad/hashtagtodo-open | todo/blueprints/new_user.py | Python | mit | 1,877 |
from FTD_classification import run
import os.path as osp
from itertools import product
PARENT_DIR = '/data/shared/bvFTD/Machine_Learning/'
DATA_DIR = osp.join(PARENT_DIR, 'data')
SAVE_FOLDER = osp.join(PARENT_DIR, 'results')
CLASSIFICATIONS = ['FTDvsNeurol', 'FTDvsPsych', 'FTDvsRest', 'NeurolvsPsych']
SMOOTHING = [Fal... | PaulZhutovsky/ftd_project | run_classification.py | Python | apache-2.0 | 1,004 |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | tensorflow/data-validation | tensorflow_data_validation/statistics/stats_options.py | Python | apache-2.0 | 23,974 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-21 06:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('net', '0001_initial'),
]
operations = [
mi... | dehu4ka/lna | net/migrations/0002_auto_20170621_1114.py | Python | mit | 1,783 |
# -*- coding: utf-8 -*-
import inspect
import logging
import math
import unicodedata
import re
import urlparse
import hashlib
from sys import maxint
import werkzeug
# optional python-slugify import (https://github.com/un33k/python-slugify)
try:
import slugify as slugify_lib
except ImportError:
slugify_lib = N... | hieukypc/ERP | openerp/addons/website/models/website.py | Python | gpl-3.0 | 31,488 |
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Sequence,
TypeVar,
overload,
)
import numpy as np
from pandas._libs import (
lib,
missing as libmissing,
)
from pandas._typing import (
ArrayLike,
AstypeArg,
NpDtype,
PositionalIndexer,
Scalar,... | dsm054/pandas | pandas/core/arrays/masked.py | Python | bsd-3-clause | 16,779 |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from django.db import migrations
def populate_message_case(apps, schema_editor):
Case = apps.get_model('cases', 'Case')
Message = apps.get_model('msgs', 'Message')
cases = list(Case.objects.select_related('initial_message').... | xkmato/casepro | casepro/cases/migrations/0032_populate_message_case.py | Python | bsd-3-clause | 1,224 |
import cherrypy
cherrypy.config.update({'server.socket_port': 9090})
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
class Root(object):
@cherrypy.expose
def index(self):
return "Hello World! From Python"
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/') | miketheprogrammer/dkxyz14 | hello-python/web.py | Python | mit | 296 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0003_auto_20151019_1555'),
]
operations = [
migrations.CreateModel(
name='Category',
fiel... | MahdiZareie/PyShop | product/migrations/0004_auto_20151026_1435.py | Python | mit | 774 |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_wtf.csrf import CsrfProtect
from flask_login import LoginManager
# Init app
app = Flask(__name__)
app.config.from_object('config')
# Init login manager
login = LoginManager()
login.init_app(app)
login.login_view... | WarwickArcheryClub/uwac-records | app/__init__.py | Python | mit | 1,176 |
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length = 255)
def __str__(self):
return self.name | jojoriveraa/titulacion-NFCOW | NFCow/categories/models.py | Python | apache-2.0 | 170 |
# -*- coding: utf-8 -*-
"""sysdescrparser.brocade_ironware."""
import re
from brocade import Brocade
# pylint: disable=no-member
class BrocadeIronWare(Brocade):
"""Class BrocadeIronWare.
SNMP sysDescr for Brocade IronWare.
"""
def __init__(self, raw):
"""Constructor."""
super(Br... | mtoshi/sysdescrparser | sysdescrparser/brocade_ironware.py | Python | mit | 1,394 |
import disjointSetForest as dsj
import cv2
import numpy as np
def toRowMajor(cols, i, j):
return i * cols + j
def fromRowMajor(cols, idx):
return (idx / cols, idx % cols)
class ObjectsSegmentation:
""" Disjoint set forest, with the additional semantic element of an image to segment
into backgroun... | alexisVallet/anime-bgrm | objectSegmentation.py | Python | gpl-2.0 | 3,095 |
#!/usr/bin/python
# Half-scale coil measurements data routines
from polynomial import *
from LinFitter import *
from StudyPlotter import *
def LF_from_poly(P):
"""Generate a linear fitter from a polynomial"""
return LinearFitter(terms=P.getTerms(True))
def poly_from_LF(LF):
"""Re-assemble a linear fitte... | mpmendenhall/rotationshield | Scripts/Halfscale_Meas.py | Python | gpl-3.0 | 7,688 |
# -*- coding: utf-8
# Copyright: 2011, Grigoriy Petukhov
# Author: Grigoriy Petukhov (http://lorien.name)
# License: BSD
from urlparse import urlsplit
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.utils.http import urle... | mjhea0/feedzilla | feedzilla/admin.py | Python | bsd-3-clause | 2,384 |
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Tests for user profile page (also tests user identity access)
"""
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2014, G. Klyne"
__license__ = "MIT (http://opensource.org/licens... | gklyne/annalist | src/annalist_root/annalist/tests/test_user_profile.py | Python | mit | 5,141 |
# 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... | zycdragonball/tensorflow | tensorflow/python/ops/variables.py | Python | apache-2.0 | 50,401 |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | zozo123/buildbot | master/buildbot/test/unit/test_util_poll.py | Python | gpl-3.0 | 9,991 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('beer', '0007_auto_20150123_1623'),
]
operations = [
migrations.RemoveField(
model_name='beer',
name=... | OckiFals/crud-django | beer/migrations/0008_auto_20150123_1650.py | Python | mit | 695 |
# salvaging
#
# Used by:
# Modules from group: Salvager (2 of 2)
type = "active"
def handler(fit, module, context):
pass
| Ebag333/Pyfa | eos/effects/salvaging.py | Python | gpl-3.0 | 127 |
""" Auction completion task runner """
from celery.signals import task_postrun
from datetime import datetime
from penelophant import crud, celery
from penelophant.database import db
from penelophant.models.Auction import Auction as Auction_model
from penelophant.models.Invoice import Invoice as Invoice_model
@celery.... | kevinoconnor7/penelophant | penelophant/tasks.py | Python | apache-2.0 | 1,245 |
from PyQt4.QtAssistant import *
| enthought/pyside | tests/util/module_wrapper/PySide/QtAssistant.py | Python | lgpl-2.1 | 33 |
#-*-coding-utf-8-*-
from django.contrib.auth.models import User
from rest_framework import serializers
from biz.idc.models import UserDataCenter
from biz.floating.models import Floating
from biz.instance.serializer import InstanceSerializer
class FloatingSerializer(serializers.ModelSerializer):
user = serialize... | bluven/eonboard | eoncloud_web/biz/floating/serializer.py | Python | apache-2.0 | 1,228 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import base64
import requests
import datetime
from time import sleep
import simplejson as json
from yaml import load, dump
from kafka import KafkaProducer
from kafka.errors import KafkaError
def get_auth(ckey, csecret):
c_key_secret_base64 = base64.b64encode(':'.... | mysbupt/RTPS | 0_user_profiling/crawler/crawl_twitter/crawl_sports_distinct_former/crawl_sports_former.py | Python | gpl-3.0 | 3,199 |
#-*- coding:utf-8 -*-
""" :mod:`reliure.utils`
======================
.. toctree::
reliure.utils.log
reliure.utils.i18n
reliure.utils.cli
"""
import re
import logging
import json
def parse_bool(value):
""" Convert a string to a boolean
>>> parse_bool(None)
False
>>> parse_bool("tru... | kodexlab/reliure | reliure/utils/__init__.py | Python | lgpl-3.0 | 4,515 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.