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 item_06_bytes_vs_str_vs_unicode import to_str, to_bytes
class TestBytesVsStr(unittest.TestCase):
def test_str(self):
"""Test converting stuff to unicode (str in python 3)"""
s = 'abcdefg' # string stays the same
self.assertTrue(isinstance(s, str))
s2 = to_st... | totoro72/pt1 | ep/tests/test_item_06_bytes_vs_str_vs_unicode.py | Python | mit | 852 |
from scrapy.contrib.spiders import CrawlSpider , Rule
from scrapy.contrib.linkextractors import LinkExtractor
from LocName.items import LocNameItem
class LocNameSpider(CrawlSpider):
name = 'ExternalLinkExtractor'
def __init__(self, *args, **kwargs):
super(LocNameSpider, self).__init__(*args, **kwargs)
... | chiragmatkar/web_scrappers | LocName/LocName/spiders/ExternalLinkExtractor.py | Python | gpl-2.0 | 697 |
from odoo import api, models
from odoo.exceptions import ValidationError
class TodoTask(models.Model):
_inherit = 'todo.task'
@api.model
def website_form_input_filter(self, request, values):
if 'name' in values:
values['name'] = values['name'].strip()
if len(values['name']... | dreispt/todo_app | todo_website/models/todo_task.py | Python | agpl-3.0 | 451 |
from __future__ import absolute_import, unicode_literals
import logging
from mopidy import backend, local, models
logger = logging.getLogger(__name__)
class LocalLibraryProvider(backend.LibraryProvider):
"""Proxy library that delegates work to our active local library."""
root_directory = models.Ref.dire... | ali/mopidy | mopidy/local/library.py | Python | apache-2.0 | 1,704 |
from lxml.etree import Element, SubElement, tostring
from pymets import XLINK, XSI, NSMAP
class MetsStructureException(Exception):
"""Base exception for the METS Python structure."""
def __init__(self, value):
self.value = value
def __str__(self):
return "%s" % (self.value,)
def create... | unt-libraries/pymets | pymets/mets_structure.py | Python | bsd-3-clause | 13,620 |
# Copyright 2013 Huawei Technologies Co.,LTD
# 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
#
# Unle... | queria/my-tempest | tempest/api/volume/admin/test_snapshots_actions.py | Python | apache-2.0 | 5,572 |
"""
Tests for Course API views.
"""
from hashlib import md5
from django.core.urlresolvers import reverse
from django.test import RequestFactory
from nose.plugins.attrib import attr
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase
from ..views import CourseDetailView
f... | miptliot/edx-platform | lms/djangoapps/course_api/tests/test_views.py | Python | agpl-3.0 | 8,978 |
# -*- coding: utf-8 -*-
# Copyright 2016 Savoir-faire Linux
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions import ValidationError
class PartnerAction(models.Model):
_name = 'partner.action'
_description = 'Partner Action'
... | acsone/partner-contact | partner_tag_actions/models/partner_action.py | Python | agpl-3.0 | 5,777 |
from DocumentClass import Document,DocumentSet,Sentence, Summary
__all__ = ['Document','DocumentSet','Sentence','Summary']
| vighneshbirodkar/summarize | summarize/Base/__init__.py | Python | mit | 124 |
#
# Classes for building disk device xml
#
# Copyright 2006-2008, 2012-2014 Red Hat, Inc.
# Jeremy Katz <katzj@redhat.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 t... | Akasurde/virt-manager | virtinst/devicedisk.py | Python | gpl-2.0 | 33,899 |
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
from datetime import datetime
import numpy as np
import time
import cv2
import cv2.cv as cv
kernel = np.ones((5,5),np.uint8)
def nothing(x):
pass
# initialize the camera and grab a reference to the raw camera cap... | laserlab/beamprofiler | beamprofiler.py | Python | gpl-2.0 | 2,422 |
import sqlite3
from airflow.hooks.dbapi_hook import DbApiHook
class SqliteHook(DbApiHook):
"""
Interact with SQLite.
"""
conn_name_attr = 'sqlite_conn_id'
default_conn_name = 'sqlite_default'
supports_autocommit = False
def get_conn(self):
"""
Returns a sqlite connectio... | mtustin-handy/airflow | airflow/hooks/sqlite_hook.py | Python | apache-2.0 | 459 |
import requests
import json
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
__client = None
class Client:
def __init__(self):
self.port = BuiltIn().get_variable_value('${CLICKHOUSE_PORT}', default=18123)
def get_query_string(self):
return "http://localhost:%d/?defaul... | moisseev/rspamd | test/functional/cases/210_clickhouse/clickhouse.py | Python | apache-2.0 | 2,615 |
#!/usr/bin/env python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the di... | realzzt/BitCoin2013 | contrib/seeds/generate-seeds.py | Python | mit | 4,520 |
from lib_oled96 import ssd1306
from PIL import ImageFont
from smbus import SMBus
import logging
import numpy as np
i2cBus = SMBus(1)
oled = ssd1306(i2cBus)
draw = oled.canvas
fnt = ImageFont.truetype('FreeMonoBold.ttf', 17)
width = 16
height = 16
pos = [[], [4, 26], [24, 26], [44, 26], [4, 46], [24, 46], [44, 46]]
... | qkitgroup/qkit | qkit/services/switchbox/switch.py | Python | gpl-2.0 | 4,312 |
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from ccgallery.models import Category, get_model
def category(request, slug):
try:
category = Category.objects.visible().get(sl... | designcc/django-ccgallery | ccgallery/views.py | Python | bsd-3-clause | 1,538 |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Puppet Catalog diff tool',
'author': 'Xavier Morales',
'url': 'https://github.com/xmorales/pcat_diff',
'download_url': 'https://github.com/xmorales/pcat_diff',
'author_email': '... | xmorales/pcat_diff | setup.py | Python | apache-2.0 | 496 |
# -*- coding: utf-8 -*-
#
# free_audio_books documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 configuration valu... | destos/free-audio-books | docs/conf.py | Python | bsd-3-clause | 7,899 |
# coding: utf-8
from pyhdf.SD import SD, SDC
ds = SD('regdayBS20141122085952-STAR-L2P_GHRSST-SST1m-GHRR_METOPA-v02.0-fv01.0.hdf', SDC.READ)
from matplotlib import pyplot as plt
import numpy as np
flags = ds.select('l2p_flags')
flags
flags = np.array(flags[:,:], dtype='uint16')
flags
plt.imshow(flags)
bit15_mask = np.bi... | DrkSephy/NOAA-Projects | idl/cwmath_session.py | Python | mit | 2,660 |
#! /usr/bin/env python
import os
import sys
import ghkey
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'ghkey',
]
requires = [
open('requirements.txt').r... | mafrosis/dote | setup.py | Python | mit | 1,321 |
"""Functions for processing order parameter files"""
import numpy as np
def read_ops_from_file(filename, tags, burn_in):
"""Read specified order parameters from file
Returns a dictionary of tags to values.
"""
with open(filename) as inp:
header = inp.readline().split(', ')
all_ops = np.... | acumb/LatticeDNAOrigami | origamipy/op_process.py | Python | mit | 2,955 |
#!/usr/bin/env python
# Find out all the unique numbers a^b for 2<=a<=1000 and 2<=b<=1000
aggro = 0
aggro2 = 0
s = set()
for a in range(2,101):
for b in range (2,101):
if a**b in s:
print "a = " + str(a) + " b = " + str(b) + " in s: " + str(a**b)
aggro2 +=1
next
else:
#print "a = " + str(a) + " b =... | nayrbnayrb/projecteuler | 0029/0029_2.py | Python | gpl-3.0 | 561 |
#
#
# Copyright (C) 2012 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | ribag/ganeti-experiments | lib/rapi/testutils.py | Python | gpl-2.0 | 10,214 |
# coding:utf8
from findTwoNum import find_two_numbers
'''
题目:一个整型数组里除了三个数字之外,其他的数字都出现了两次。请写程序找出这三个只出现一次的数字。
时间复杂度 O(n)
空间复杂度 O(1)
'''
# 解题思路:
# 跟前两个题目一样,如果我们能将数组的元素分成三堆, 每堆中的元素包含一个出现一次的数字以及其它若干的数字, 那么就回到最原始的问题
# 假设三个出现一次的数字为 x, y, z, 则对整个数组进行异或操作后 xors = x ^ y ^ z
# 这时候我们已经不能像找出两个数那样进行操作了, 通过观察我们可以发现 low_bit(x^y),... | happylindz/algorithms-tutorial | others/FindNumberInArray/findThreeNum.py | Python | mit | 2,371 |
#!/usr/bin/env python
import imp
import settings
from django.core.management import execute_manager
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears ... | iurisilvio/soapfish | examples/stock/manage.py | Python | bsd-3-clause | 506 |
from crypto.set_1.challenge_2 import xor_two_hex
HEX_1 = '1c0111001f010100061a024b53535009181c'
HEX_2 = '686974207468652062756c6c277320657965'
EXPECTED_XOR = '746865206b696420646f6e277420706c6179'
def test_xor_two_strings():
result = xor_two_hex(HEX_1, HEX_2)
assert result == EXPECTED_XOR
assert isins... | mthpower/matasano-crypto | src/tests/set_1/test_challenge_2.py | Python | mit | 339 |
# _*_coding: utf-8 _*_
# 如果有非ASIIC码的字符,比如中文,那么就需要加入这一行
import numpy as np
a = np.arange(10)
print "a=", a
print a[3:6]
# a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6)
# print a
# L = [1, 2, 3, 4, 5]
# print "L = ", L
# a = np.array(L)
# print "a = ", a
# print type(a), type(L)
# b = np.array([[1, 2, 3, 4... | jacobyan/Arduino_Demo | backup/I2C_data_sent/ml_1.py | Python | mit | 2,519 |
import datetime
from typing import List, Optional
from upcloud_api.api import API
from upcloud_api.object_storage import ObjectStorage
class ObjectStorageManager:
"""
Functions for managing Object Storages. Intended to be used as a mixin for CloudManager.
"""
api: API
def get_object_storages(se... | UpCloudLtd/upcloud-python-api | upcloud_api/cloud_manager/object_storage_mixin.py | Python | mit | 4,684 |
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from os.path import join
from django.conf import settings
from django.db import models, migrations
import django.db.models.deletion
import sorl.thumbnail.fields
imp... | fnp/wolnelektury | src/picture/migrations/0001_initial.py | Python | agpl-3.0 | 3,502 |
#!/usr/bin/env python
# a helper for gyp to do file globbing cross platform
# Usage: python glob.py root_dir pattern [pattern...]
from __future__ import print_function
import fnmatch
import os
import sys
root_dir = sys.argv[1]
patterns = sys.argv[2:]
for (dirpath, dirnames, files) in os.walk(root_dir):
for f in... | nlgcoin/guldencoin-official | src/unity/glob.py | Python | mit | 502 |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PySphinxcontribBibtex(PythonPackage):
"""A Sphinx extension for BibTeX style citations."""... | iulian787/spack | var/spack/repos/builtin/packages/py-sphinxcontrib-bibtex/package.py | Python | lgpl-2.1 | 1,234 |
"""
.. module:: algorithm
:synopsis: Base class Algorithm
.. moduleauthor:: Oscar Celma <ocelma@bmat.com>
"""
import sys
from scipy.cluster.vq import kmeans2 #for kmeans method
from random import randint #for kmeans++ (_kinit method)
#from scipy.linalg import norm #for kmeans++ (_kinit method)
from scipy import ar... | Mitali-Sodhi/CodeLingo | Dataset/python/baseclass.py | Python | mit | 9,017 |
#!/usr/bin/python3
# vim: set sts=4 expandtab:
#
import xml.etree.ElementTree as ET
import re
def search_retext(element, text, xpath=''):
retext = re.compile(text)
if xpath == '':
xpath = element.tag
subelements = element.findall('*')
tagcount = {}
if subelements != []:
for s in sub... | osamuaoki/fun2prog | xml/et/search-xpath.py | Python | mit | 1,184 |
# Copyright 2004-2015 Tom Rothamel <pytom@bishoujo.us>
#
# 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, m... | joxer/Baka-No-Voltron | tmp/android.dist/private/renpy/display/tts.py | Python | gpl-2.0 | 4,382 |
"""Entities: things that exist in the world."""
from .gfx import GraphicsGroup
from .util import ir
class Entity (object):
"""A thing that exists in the world.
Entity()
Currently, an entity is just a container of graphics.
"""
def __init__ (self):
#: The :class:`World <engine.game.World>` this en... | ikn/o | game/engine/entity.py | Python | gpl-3.0 | 884 |
#!/usr/bin/env python
import sys, os, numpy, random
ROOT = os.path.abspath('%s/../..' % os.path.abspath(os.path.dirname(__file__)))
sys.path.append(ROOT)
os.environ['DJANGO_SETTINGS_MODULE'] = 'qurkexp.settings'
from django.core.management import setup_environ
from django.conf import settings
from qurkexp.join.models ... | marcua/qurk_experiments | qurkexp/join/hybrid.py | Python | bsd-3-clause | 13,043 |
#! /usr/bin/python
# Copyright (C) GRyCAP - I3M - UPV
#
# 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 ... | grycap/scar | test/unit/test_scarcli.py | Python | apache-2.0 | 2,151 |
# proxy module
from __future__ import absolute_import
from blockcanvas.ui.hyperlink_editor import *
| enthought/etsproxy | enthought/block_canvas/ui/hyperlink_editor.py | Python | bsd-3-clause | 100 |
import numpy as np
import os
import dill
import tempfile
import tensorflow as tf
import zipfile
from absl import flags
import baselines.common.tf_util as U
from baselines import logger
from baselines.common.schedules import LinearSchedule
from baselines import deepq
from baselines.deepq.replay_buffer import ReplayBu... | chris-chris/pysc2-examples | defeat_zerglings/dqfd.py | Python | apache-2.0 | 13,760 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import warnings
from contextlib import contextmanager
from distutils.version import LooseVersion
import re
import numpy as np
from numpy.testing import assert_array_equal
from xarray.core.duck_array_ops import ... | jhamman/xray | xarray/tests/__init__.py | Python | apache-2.0 | 6,270 |
"""user nick
Revision ID: 35c6645bd687
Revises: 5a30a72ffdb7
Create Date: 2017-04-27 16:14:14.960330
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '35c6645bd687'
down_revision = '5a30a72ffdb7'
branch_labels = None
depends_... | Shortcutgg/learning-curve-server | migrations/versions/35c6645bd687_user_nick.py | Python | gpl-3.0 | 698 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import behave
import os
import parse
from common import *
@behave.step("I use the repository \"{repo}\"")
def step_repo_condition(context, repo):
if "repos" not in context.dnf:
context.dnf["repos"] = []... | kkaarreell/ci-dnf-stack | dnf-behave-tests/features/steps/repo.py | Python | gpl-3.0 | 3,594 |
from flask import Blueprint, request
bg5_40323217_1 = Blueprint('bg5_40323217_1', __name__, url_prefix='/bg5_40323217_1', template_folder='templates')
head_str = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>網際 2D 繪圖</title>
<!-- IE 9: display inline SVG -->
<meta http-equiv="X-UA-C... | hsungchang/cdw11_g5 | users/b/g5/bg5_40323217_1.py | Python | agpl-3.0 | 30,746 |
##
# Copyright 2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (... | bartoldeman/easybuild-easyblocks | easybuild/easyblocks/a/allinea.py | Python | gpl-2.0 | 4,495 |
# solev in 6 minutes !!!
def solve(ip):
res = 0
l = ip[0]
prev = ip[0]
for p in ip[1:]:
if p < prev:
res = res + 1
else:
prev = p
return res
if __name__ == "__main__":
t = int(input())
for tc in range(t):
n = int(input())
ip = []
... | subhrm/google-code-jam-solutions | solutions/2013/EuroPython/A/A.py | Python | mit | 460 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import sys
import copy
import random
import string
from argparse import ArgumentParser as ArgParser, _UNRECOGNIZED_ARGS_ATTR
from argparse import (_VersionAction, Action, A... | drwyrm/Flexget | flexget/options.py | Python | mit | 22,230 |
def task_compute():
def comp(x):
return {'x':x}
yield {'name': '5',
'actions': [ (comp, [5]) ]
}
yield {'name': '7',
'actions': [ (comp, [7]) ]
}
def show_getargs(values):
print values
assert sum(v['x'] for v in values) == 12
def task_args_dict():
ret... | swayf/doit | doc/tutorial/getargs_group.py | Python | mit | 442 |
#!/usr/bin/env python
from subprocess import Popen
import time
server = Popen(["cd ./app && python -m http.server"], shell=True,
stdin=None, stdout=None, stderr=None, close_fds=True)
tunnel = Popen(["ssh -R 80:localhost:8000 serveo.net"], shell=True,
stdin=None, stdout=None, stderr=None,... | lukas/ml-class | examples/mobile/tfjs-emotion/serve.py | Python | gpl-2.0 | 368 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from urlparse import urljoin
from datetime import datetime, timedelta
from flask import request, redirect, render_template, url_for, abort, flash, g, session
from flask import current_app, make_response
from flask.views import MethodView
# from flask.ext.login ... | 0x0004/LOFTER | app/main/views.py | Python | apache-2.0 | 13,893 |
# Copyright (C) 2018 Leandro Lisboa Penz <lpenz@lpenz.org>
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
'''perl checker'''
import subprocess
import re
from omnilint.error import Error
from omnilint.checkers import Checker
class Perl(Check... | lpenz/omnilint | container/omnilint/checkers/perl.py | Python | mit | 1,698 |
# Copyright (c) 2016 Cyso < development [at] cyso . com >
#
# This file is part of omniconf, a.k.a. python-omniconf .
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.... | cyso/omniconf | omniconf/tests/backends/test_env.py | Python | lgpl-3.0 | 2,916 |
from os.path import join, dirname
from example_standalone.settings import *
INSTALLED_APPS += (
# Add fluent pages with a simple page type:
'fluent_pages',
#'fluent_pages.pagetypes.fluentpage',
'fluent_pages.pagetypes.flatpage',
# Add the page type for adding the "blogs" root to the page tree.
... | edoburu/django-fluent-blogs | example/example_fluent_pages/settings.py | Python | apache-2.0 | 561 |
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
app.config.from_object(os.getenv('APP_SETTINGS'))
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| gitzart/word-frequency | manage.py | Python | mit | 312 |
# Copyright (c) 2016, Monash e-Research Centre
# (Monash University, Australia)
# 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... | NeCTAR-RC/nectar-images | community_image_tests/community_image_tests_tempest_plugin/services/v2/community_image_client.py | Python | apache-2.0 | 1,416 |
# -*- coding: utf-8 -*-
##
## This file is part of INSPIRE.
## Copyright (C) 2015 CERN.
##
## INSPIRE is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | ioannistsanaktsidis/inspire-next | inspire/base/format_elements/bfe_inspire_links.py | Python | gpl-2.0 | 5,821 |
import unittest
from initiate import StringInitiateScanner
class StringInitiateAllScannerTestCase(unittest.TestCase):
def setUp(self):
self._all_scanner = StringInitiateScanner(read_hidden=True)
def test_check_with_all_scanner_true1(self):
self.assertTrue(self._all_scanner.check_for_trigger(... | ZackYovel/initiate | test/string_initiate_scanner_test_case.py | Python | mit | 13,176 |
# -*- coding: utf-8 -*-
# standard
import os
import tempfile
import re
# 3rd party
from PyQt4 import QtGui, QtCore
# local
import model
CHESTCONF = {"hash": 128, "in": "input.txt", "out": "output.txt"}
CHESTSTIPULATION = re.compile('^([sh]?)([#=])(\d+)(\.5)?$', re.IGNORECASE)
def isOrthodox(fen):
... | tectronics/olive-gui | chest.py | Python | gpl-3.0 | 8,979 |
# Copyright 2017-2021 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | guildai/guild | guild/query/__init__.py | Python | apache-2.0 | 2,679 |
"""
5-fold cv - log loss 0.447489661199
"""
import graphlab as gl
import numpy as np
import logging
import os
from hyperopt import fmin, hp, tpe
from sklearn.base import BaseEstimator
from sklearn import ensemble
from otto_utils import consts, utils
MODEL_NAME = 'model_14_bagging_xgboost'
MODE = 'cv' # cv|submiss... | ahara/kaggle_otto | otto/model/model_14_bagging_xgboost/bagging_xgboost.py | Python | bsd-3-clause | 5,422 |
"""Support for Openhome Devices."""
import logging
from homeassistant.components.media_player import (
MediaPlayerDevice)
from homeassistant.components.media_player.const import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK,
SUPPORT_SELECT_SOURCE, SUPPORT_STOP, SUPPORT_TURN_OFF,... | MartinHjelmare/home-assistant | homeassistant/components/openhome/media_player.py | Python | apache-2.0 | 6,577 |
"""
pygments.lexers._postgres_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Self-updating data files for PostgreSQL lexer.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Autogenerated: please edit them if you like wasting your time.... | dscorbett/pygments | pygments/lexers/_postgres_builtins.py | Python | bsd-2-clause | 12,184 |
def mult(a, b):
return a * b
def div(a, b):
return a / b
| esquires/lvdb | test/temp2.py | Python | bsd-3-clause | 66 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2019 CERN.
# Copyright (C) 2018-2019 RERO.
#
# Invenio-Circulation is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Tests for loan states."""
from datetime import timedelta
import arro... | inveniosoftware/invenio-circulation | tests/test_transition_item_at_desk_to_item_on_loan.py | Python | mit | 2,309 |
# -*- coding: utf-8 -*-
from troubleshooting.framework.output.output import OutPut
from troubleshooting.framework.libraries.library import singleton
from troubleshooting.framework.modules.configuration import ConfigManagerInstance
@singleton
class welcome(object):
def __init__(self):
super(self.__class__... | gaoxiaofeng/troubleShooting | src/troubleshooting/framework/output/welcome.py | Python | apache-2.0 | 2,569 |
import os, sys
import gzip
import paddle.v2 as paddle
import numpy as np
import functools
def lambda_rank(input_dim):
"""
lambda_rank is a Listwise rank model, the input data and label must be sequences.
https://papers.nips.cc/paper/2971-learning-to-rank-with-nonsmooth-cost-functions.pdf
parameters :
... | zhaopu7/models | ltr/lambda_rank.py | Python | apache-2.0 | 4,131 |
from tkinter import *
class Help(Frame):
def __init__(self, parent):
self.parent = parent
Frame.__init__(self, self.parent)
self.zoneA = Frame(fenetre)
self.zoneB = Frame(fenetre)
self.zoneA.pack()
self.zoneB.pack()
Label(self.zoneA, text="Bouton Compiler... | Allain18/AtmegaGUI | test.py | Python | bsd-3-clause | 806 |
from proteus.default_n import *
import ls_p as physics
from proteus import (StepControl,
TimeIntegration,
NonlinearSolvers,
LinearSolvers,
LinearAlgebraTools)
from proteus.mprans import NCLS
from proteus import Context
ct = Context.get... | erdc-cm/air-water-vv | 2d/oscillating_cylinder/ls_n.py | Python | mit | 2,326 |
# Copyright 2013 NEC Corporation
#
# 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 ag... | JioCloud/horizon | openstack_dashboard/api/network.py | Python | apache-2.0 | 5,006 |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from future_builtins import zip
from functools import wraps
try:
from cs... | sharad/calibre | src/calibre/ebooks/oeb/normalize_css.py | Python | gpl-3.0 | 20,738 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
import uuid
import traceback
import hashlib
import simplejson
from kindo.kindo_core import KindoCore
from kindo.utils.config_parser import ConfigParser
from kindo.utils.functions import unzip_to_folder
class PushModule(KindoCore):
def __init__(... | shenghe/kindo | kindo/modules/push_module.py | Python | apache-2.0 | 3,907 |
import pygame
from pygame.locals import *
from sys import exit
from random import *
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
screen.lock()
for count in range(10):
random_color = (randint(0,255), randint(0,255), randint(0,255))
random_pos = (randint(0,639), randint(0,479))
random... | MaxWayne/Beginning-Game-Development-with-Python-and-Pygame | Chapter 4/4-9.py | Python | mit | 635 |
from energenie import switch_on, switch_off
from time import sleep
print ("Turning off")
switch_off()
sleep(5)
print ("Turning on")
switch_on()
| fergalmoran/energenie | socket.py | Python | apache-2.0 | 147 |
"""Gradient Boosted Regression Trees.
This module contains methods for fitting gradient boosted regression trees for
both classification and regression.
The module structure is the following:
- The ``BaseGradientBoosting`` base class implements a common ``fit`` method
for all the estimators in the module. Regressi... | ndingwall/scikit-learn | sklearn/ensemble/_gb.py | Python | bsd-3-clause | 72,022 |
# encoding: utf-8
#
from __future__ import absolute_import, division, unicode_literals
import random
import string
builtin_range = range
SIMPLE_ALPHABET = string.ascii_letters + string.digits
SEED = random.Random()
def set_seed(seed):
global SEED
SEED = random.Random(seed)
def string(length, alphabet=SIM... | klahnakoski/ActiveData | vendor/mo_math/randoms.py | Python | mpl-2.0 | 1,607 |
from .tokenize import tokenize
def token_to_string(token_id):
return TOKEN_MAP[token_id]
TOKEN_MAP = [
'NOTHING',
'module',
'Generated',
'where',
',',
'::',
'->',
'=',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'function0',
'function1',
'fun... | coopie/huzzer | huzzer/tokenizing/__init__.py | Python | mit | 689 |
#!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
... | bastibl/gnuradio | gr-digital/python/digital/qa_ofdm_txrx.py | Python | gpl-3.0 | 7,038 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = "0.5.0"
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel upload')
print(" git tag -a %s -m 'version %s'" % (... | pydanny/webhooks | setup.py | Python | bsd-3-clause | 1,570 |
# Copyright 2016 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... | beomyeol/models | inception/inception/inception_distributed_train.py | Python | apache-2.0 | 14,026 |
from django.core import urlresolvers
from django.conf import settings
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.contrib import messages
from django.contrib.auth.models import User, Group
class CatmaidView(TemplateView):
""" This view adds extra context t... | aschampion/CATMAID | django/applications/catmaid/views/__init__.py | Python | gpl-3.0 | 4,588 |
# 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 ... | lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/topology.py | Python | mit | 1,821 |
#
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | hustodemon/spacewalk | client/tools/rhnpush/test/testRhnpushCache.py | Python | gpl-2.0 | 4,327 |
# Author: Tom Pauwaert
# Date: 31 March 2015
# Challenge: Algorithms/Warmup/The-Love-Letter-Mystery
T = input()
counter = 0
# For each word, figure out edit length to palindrome
for _ in range(T):
counter += 1
word = raw_input()
word_len = len(word) #stored for efficiency
index = 0
sum_edits = 0
... | tompauwaert/hackerrank | warmup/the-love-letter-mystery/python/code.py | Python | mit | 670 |
# Copyright 2001-2014 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permissio... | svanschalkwyk/datafari | windows/python/Lib/logging/__init__.py | Python | apache-2.0 | 61,148 |
# coding=utf-8
from django.contrib import admin
from elections.models import Election, VotaInteligenteMessage, VotaInteligenteAnswer, CandidatePerson
from flatpages_i18n.admin import FlatpageForm, FlatPageAdmin
from flatpages_i18n.models import FlatPage_i18n
## OOPS this is a custom widget that works for initializing
#... | adtidiane/Nouabook | elections/admin.py | Python | gpl-3.0 | 8,437 |
import numpy as np
from chainercv.visualizations.vis_image import vis_image
def vis_bbox(img, bbox, label=None, score=None, label_names=None,
instance_colors=None, alpha=1., linewidth=3.,
sort_by_score=True, ax=None):
"""Visualize bounding boxes inside image.
Example:
>>> ... | chainer/chainercv | chainercv/visualizations/vis_bbox.py | Python | mit | 5,273 |
# -*- coding: utf-8 -*-
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic import ListView
from django.utils.decorators import method_decorator
from django.urls import reverse
from catmaid.control.authentication import requires_superuser
from catmaid.control.comm... | catmaid/CATMAID | django/applications/catmaid/views/admin.py | Python | gpl-3.0 | 1,416 |
from django.db.models import Q
from contacts.models import Contact
from contacts.serializer import ContactSerializer
from common.models import User, Attachments, Comment, Profile
from common.custom_auth import JSONWebTokenAuthentication
from common.serializer import (
ProfileSerializer,
CommentSerializer,
... | MicroPyramid/Django-CRM | events/views.py | Python | mit | 22,067 |
import sys
# Server config
SERVER_NAME = None
DEBUG = False
for arg in sys.argv:
if arg == '-d':
DEBUG = True
SECRET_KEY = 'secret-key'
# available languages
LANGUAGES = {
'en': 'English',
'zh': '中文'
}
# SQL config
SQLALCHEMY_DATABASE_URI = 'mysql+mysqldb://icourse:eDuTieudXcfk@... | JING-TIME/ustc-course | config/default.py | Python | agpl-3.0 | 1,372 |
######################################################################
# The ATCA Sensitivity Calculator
# Common execution handlers.
# Copyright 2015 Jamie Stevens, CSIRO
#
# This file is part of the ATCA Sensitivity Calculator.
#
# The ATCA Sensitivity Calculator is free software: you can
# redistribute it and/or mod... | ste616/atca-sensitivity-calculator | code/atsenscalc_main.py | Python | gpl-3.0 | 59,429 |
#!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
from mininet.cli import CLI
from mininet.node import Controller
from mininet.node import RemoteController
import os ... | richardclegg/pox_firewall_setup | createSimple.py | Python | mpl-2.0 | 2,500 |
"""Change shape type, add parent and insee
Revision ID: 2e65dbaa935
Revises: 4190b0aefe23
Create Date: 2015-06-29 12:23:13.581187
"""
# revision identifiers, used by Alembic.
revision = '2e65dbaa935'
down_revision = '3183d344740d'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgr... | l-vincent-l/APITaxi | migrations/versions/2e65dbaa935_change_shape_type_add_parent_and_insee.py | Python | agpl-3.0 | 1,065 |
from django.conf.urls import patterns, include, url
from .views import IndexView
urlpatterns = patterns('',
# Examples:
# url(r'^blog/', include('blog.urls')),
url(r'^$', IndexView.as_view()),
)
| herrera10/inteligencia_artificial2 | apps/home/urls.py | Python | gpl-3.0 | 210 |
import errno
import fnmatch
import json
import os
import os.path
import shutil
import subprocess
import sys
import tarfile
import requests
import stat
import dbt.compat
import dbt.exceptions
import dbt.utils
from dbt.logger import GLOBAL_LOGGER as logger
def find_matching(root_path,
relative_paths... | nave91/dbt | dbt/clients/system.py | Python | apache-2.0 | 6,204 |
import lb_loader
import pandas as pd
import simtk.openmm.app as app
import numpy as np
import simtk.openmm as mm
from simtk import unit as u
from openmmtools import hmc_integrators, testsystems, integrators
precision = "mixed"
testsystem = testsystems.DHFRExplicit(nonbondedCutoff=1.1*u.nanometers, nonbondedMethod=app... | kyleabeauchamp/HMCNotes | code/misc/testing_force_group_speed.py | Python | gpl-2.0 | 1,760 |
# -*- coding: utf-8 -*-
# Copyright 2022 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... | googleapis/python-bigtable | google/cloud/bigtable_admin_v2/services/bigtable_table_admin/transports/grpc.py | Python | apache-2.0 | 40,888 |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
#
import codecs
from FabLabKasse import scriptHelper
from ConfigParser import ConfigParser
import sqlite3
from datetime import datetime
from decimal import Decimal
from PyQt4 import QtCore, Qt, QtGui
from MagPosLog import MagPosLog
from ..UI.FAUcardPaymentDialogCode i... | fau-fablab/FabLabKasse | FabLabKasse/faucardPayment/faucard.py | Python | gpl-3.0 | 4,937 |
# -*- coding: utf-8 -*-
import tensorflow as tf
class AdversarialSets2:
"""
Utility class for generating Adversarial Sets for RTE.
"""
def __init__(self, model_class, model_kwargs,
scope_name='adversary', embedding_size=300, batch_size=1024, max_sequence_length=10,
... | uclmr/inferbeddings | inferbeddings/nli/regularizers/adversarial2.py | Python | mit | 15,002 |
import unittest
from fa import piping
class TestPiping(unittest.TestCase):
def test_csv_string_or_rows_to_records(self):
records = piping.csv_string_to_records(
"C6L.SI",
"Operating Income & Loss,Revenue\n100.0,200.0\n300.0,400.0\n"
)
self.assertEqual(list(records... | kakarukeys/algo-fa | tests/test_piping.py | Python | gpl-2.0 | 1,048 |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from zincutils.zinc_... | sameerparekh/pants | src/python/pants/backend/jvm/tasks/jvm_compile/zinc/zinc_analysis_parser.py | Python | apache-2.0 | 2,126 |
from scitools.sound import *
from scitools.std import *
def oscillations(N):
x = zeros(N+1)
for n in range(N+1):
x[n] = exp(-4*n/float(N))*sin(8*pi*n/float(N))
return x
def logistic(N):
x = zeros(N+1)
x[0] = 0.01
q = 2
for n in range(1, N+1):
x[n] = x[n-1] + q*x[n-1]*(1 - x... | qilicun/python | python3/src/diffeq/soundseq.py | Python | gpl-3.0 | 1,032 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.