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 |
|---|---|---|---|---|---|
# by convention.
import cStringIO
import numpy as np
import re
# copied from openearthtools/kmldap
def compress_kml(kml):
"""
Returns compressed KMZ from the given KML string.
>>> kml = "<kml>"
>>> # returns a zip file containing a doc.xml
>>> compress_kml(kml)[:2]
'PK'
"""
import cStri... | lizardsystem/lizard-kml | lizard_kml/jarkus/helpers.py | Python | gpl-3.0 | 2,654 |
"""
Generic parse method to parse either a .gct or a .gctx.
Takes in a file path corresponding to either a .gct or .gctx,
and parses to a GCToo instance accordingly.
Note: Supports GCT1.2, GCT1.3, and GCTX1.0 files.
"""
import logging
import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger
import cmapP... | cmap/cmapPy | cmapPy/pandasGEXpress/parse.py | Python | bsd-3-clause | 3,365 |
"""Support for LED numbers."""
from __future__ import annotations
from functools import partial
from homeassistant.components.number import NumberEntity, NumberEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ENTITY_CATEGORY_CONFIG
from homeassistant.core import H... | aronsky/home-assistant | homeassistant/components/wled/number.py | Python | apache-2.0 | 3,973 |
import inspect
import wsme.api
APIPATH_MAXLEN = 20
class expose(object):
def __init__(self, *args, **kwargs):
self.signature = wsme.api.signature(*args, **kwargs)
def __call__(self, func):
return self.signature(func)
@classmethod
def with_method(cls, method, *args, **kwargs):
... | stackforge/wsme | wsme/rest/__init__.py | Python | mit | 2,097 |
# Copyright (C) 2014 Universidad Politecnica de Madrid
# 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... | ging/horizon | openstack_dashboard/fiware_oauth2/urls.py | Python | apache-2.0 | 1,372 |
from . import source_navigation_steps
from . import journalist_navigation_steps
from . import functional_test
class TestSubmitAndRetrieveFile(
functional_test.FunctionalTest,
source_navigation_steps.SourceNavigationStepsMixin,
journalist_navigation_steps.JournalistNavigationStepsMixin):
d... | freedomofpress/securedrop | securedrop/tests/functional/test_submit_and_retrieve_file.py | Python | agpl-3.0 | 1,562 |
#!/usr/bin/env python3
import zmq
import sys
import redis
import json
import os
import time
from pathlib import Path
def check_pid(pid):
""" Check For the existence of a unix pid. """
if not pid:
return False
pid = int(pid)
try:
os.kill(pid, 0)
except OSError:
return Fal... | FIRSTdotorg/MISP | app/files/scripts/mispzmq/mispzmq.py | Python | agpl-3.0 | 4,612 |
# -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | rajul/tvb-framework | tvb/tests/framework/core/entities/file/file_tests_main.py | Python | gpl-2.0 | 2,176 |
#!/usr/bin/python
from gevent import monkey
monkey.patch_all()
import logging
import gevent
from gevent.coros import BoundedSemaphore
from kafka import KafkaClient, KeyedProducer, SimpleConsumer, common
from uveserver import UVEServer
import os
import json
import copy
class PartitionHandler(gevent.Greenlet):
def ... | srajag/contrail-controller | src/opserver/partition_handler.py | Python | apache-2.0 | 9,307 |
from flask import jsonify, request, current_app, url_for
from . import api
from ..models import User, Post
@api.route('/users/<int:id>')
def get_user(id):
user = User.query.get_or_404(id)
return jsonify(user.to_json())
@api.route('/users/<int:id>/posts/')
def get_user_posts(id):
user = User.query.get_or... | frankiecjunle/yunblog | app/api_1_0/users.py | Python | mit | 1,860 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-13 03:20
from __future__ import unicode_literals
import django.contrib.postgres.fields.ranges
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('climate_data',... | qubs/data-centre | climate_data/migrations/0020_annotation.py | Python | apache-2.0 | 1,145 |
# -*- coding: utf-8 -*-
# (c) 2009-2022 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Wrapper for ``server_cli``, that restarts the server when source code is
modified.
"""
import os
import sys
from su... | mar10/wsgidav | wsgidav/server/run_reloading_server.py | Python | mit | 1,388 |
import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... | xaxa89/mitmproxy | mitmproxy/tools/console/overlay.py | Python | mit | 3,855 |
from typing import Dict
class Parent:
def overridable_method(self, param: str) -> Dict[str, str]:
pass
class Child(Parent):
def overridable_method(self, param: str) -> Dict[str, str]: | smmribeiro/intellij-community | python/testData/completion/superMethodWithAnnotation.after.py | Python | apache-2.0 | 202 |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... | lintzc/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/pg_twophase/switch_ckpt_serial/cleanup_sql/test_cleanup.py | Python | apache-2.0 | 845 |
# coding: utf-8
name = "KSP Reference Manual(6.5.0).txt"
| r-koubou/vscode-ksp | data/ExtractManualNameConfig.py | Python | mit | 57 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The crimson Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Exercise API with -disablewallet.
#
from test_framework.test_framework import crimsonTestFramework
f... | CrimsonDev14/crimsoncoin | qa/rpc-tests/disablewallet.py | Python | lgpl-3.0 | 1,820 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | rackerlabs/horizon | openstack_dashboard/dashboards/project/stacks/urls.py | Python | apache-2.0 | 1,687 |
#!/usr/bin/env python
#
import femagtools.job
import tempfile
import os
def test_condor():
workdir = tempfile.mkdtemp()
job = femagtools.job.CondorJob(workdir)
task = job.add_task()
task.add_file('femag.fsl', ['exit_on_end=True'])
try:
job.prepareDescription()
with open(os.pat... | SEMAFORInformatik/femagtools | tests/test_job.py | Python | bsd-2-clause | 981 |
from pyramid import testing
from pytest import fixture
from pytest import mark
from pytest import raises
from unittest.mock import Mock
import pytest
from substanced.workflow import WorkflowError
@fixture
def registry(registry_with_content):
return registry_with_content
class TestACLocalRolesState:
def mak... | liqd/adhocracy3.mercator | src/adhocracy_core/adhocracy_core/workflows/test_init.py | Python | agpl-3.0 | 15,368 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-10-23 14:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('storage', '0014_auto_20161023_1340'),
]
operations = [
migrations.RemoveFiel... | Nictec/nictec_website2.0 | nictecsite/storage/migrations/0015_auto_20161023_1414.py | Python | gpl-3.0 | 883 |
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = "mobile-city-history",
version = "1.0.0b2",
author = "Jan-Christopher Pien",
author_email = "jan_christopher.pien@fokus.fraunhofer.de",
url = "http://www.foo.bar",
license = "MIT",
descripti... | jessepeng/coburg-city-memory | setup.py | Python | mit | 1,161 |
import numpy as np
import matplotlib.pyplot as plt
import warnings
def plot_venn_diagram():
fig, ax = plt.subplots(subplot_kw=dict(frameon=False, xticks=[], yticks=[]))
ax.add_patch(plt.Circle((0.3, 0.3), 0.3, fc='red', alpha=0.5))
ax.add_patch(plt.Circle((0.6, 0.3), 0.3, fc='blue', alpha=0.5))
ax.add... | ML4DS/ML4all | U1.KMeans/fig_code/figures.py | Python | mit | 8,787 |
from couchdb.mapping import *
from couchdb.http import ResourceNotFound, PreconditionFailed
from hashlib import sha1
from random import choice
from string import digits
ROLE_ADMIN = 'radar:role:admin'
PERM_CREATE = 'radar:perm:create'
PERM_READ = 'radar:perm:read'
PERM_UPDATE = 'radar:perm:update'
PERM_DELETE = 'ra... | ltucker/radarpost | radarpost/user.py | Python | gpl-2.0 | 3,223 |
########
# Copyright (c) 2014 GigaSpaces Technologies 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
#
# Unless... | fogelomer/cloudify-filebeat-plugin | filebeat_plugin/tasks.py | Python | apache-2.0 | 7,991 |
#!/usr/bin/env python3
import sys
# import fileinput
words = []
reversed_words = []
with open(sys.argv[1], 'r') as outfile:
for line in outfile:
word = line.rstrip()
if word[::-1] != word:
words.append(word)
reversed_words.append(word[::-1])
''' O nieco pom... | Joozty/FIT-VUT | 2. Semester/ISJ - Scripting Languages/3. Project/xharag01_nonpalindrom_words_existing_reversed.py | Python | gpl-3.0 | 571 |
import itertools
import unittest
from parameterized import parameterized
import torch
import torch.nn as nn
from nsoltChannelConcatenation2dLayer import NsoltChannelConcatenation2dLayer
nchs = [ [3, 3], [4, 4] ]
datatype = [ torch.float, torch.double ]
nrows = [ 4, 8, 16 ]
ncols = [ 4, 8, 16 ]
class NsoltChannelConca... | shodimaggio/SaivDr | appendix/torch_nsolt/test_nsoltChannelConcatenation2dLayer.py | Python | bsd-2-clause | 7,477 |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
self.prev = None
self.first = None
... | JiaminXuan/leetcode-python | recover_binary_search_tree/solution.py | Python | bsd-2-clause | 934 |
import codecs
import pydotplus
import sadisplay
from os import path
from labbookdb.db.query import ALLOWED_CLASSES
from labbookdb.db.common_classes import *
def generate(
extent="all",
save_dotfile="",
save_plot="",
label="",
linker_tables=False
):
"""Retreive the LabbookDB schema and save either a DOT file, or... | TheChymera/LabbookDB | labbookdb/introspection/schema.py | Python | bsd-3-clause | 2,296 |
import os
import os.path
import sys
import signal
import argparse
import time
import threading
import requests
import webbrowser
import traceback
import pkg_resources
import socks
import socket
from io import BytesIO
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.api import *
... | NghiaTranUIT/rainbowstream | rainbowstream/rainbow.py | Python | mit | 63,714 |
import os
import platform
from twisted.internet import defer
from .. import data, helper
from p2pool.util import pack
P2P_PREFIX = 'fab5e8db'.decode('hex')
P2P_PORT = 19934
ADDRESS_VERSION = 22
RPC_PORT = 13435
RPC_CHECK = defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
'asiccoinaddress' in (yi... | ptcrypto/p2pool-adaptive | p2pool/bitcoin/networks/asiccoin.py | Python | gpl-3.0 | 1,108 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | reneploetz/mesos | src/python/cli_new/lib/cli/plugins/base.py | Python | apache-2.0 | 5,461 |
import numpy as np
# set default value of tolerance of block average unless argparse does not support default
# input: tol is a float or integer
# deafult is default value you want to set (depends on your program)
# output: convert to a float value of tolerance, otherwise default value
# Example: args.tol = default_... | jht0664/Utility_python_gromacs | python/hjung/blockavg.py | Python | mit | 6,126 |
# encoding: utf-8
# module PyKDE4.kio
# from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KDesktopFileActions(): # skipped bases: ... | ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kio/KDesktopFileActions.py | Python | gpl-2.0 | 940 |
# Copyright (c) 2011-2013 Mick Thomure
# All rights reserved.
#
# Please see the file LICENSE.txt in this distribution for usage terms.
from pprint import pformat
__all__ = [
'Node'
]
class Node(object):
id_ = 0
depends = []
def __init__(self, id_, depends = None):
if not (depends is None or hasat... | mthomure/glimpse-project | glimpse/util/dataflow/node.py | Python | mit | 929 |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 30, transform = "Fisher", sigma = 0.0, exog_count = 20, ar_order = 12); | antoinecarme/pyaf | tests/artificial/transf_Fisher/trend_MovingAverage/cycle_30/ar_12/test_artificial_128_Fisher_MovingAverage_30_12_20.py | Python | bsd-3-clause | 267 |
from HTMLComponent import HTMLComponent
from GUIComponent import GUIComponent
from skin import parseFont
from Tools.FuzzyDate import FuzzyTime
from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_VALIGN_CENTER, RT_VALIGN_TOP, RT_VALIGN_BOTTOM
from Tools.Alternatives impo... | Open-Plus/opgui | lib/python/Components/TimerList.py | Python | gpl-2.0 | 8,250 |
#!/usr/bin/env python
#
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Founda... | arseneyr/essentia | test/src/unittest/filters/test_dcremoval.py | Python | agpl-3.0 | 2,538 |
# -*- coding: utf-8 -*-
from functools import partial
from commons import base_repo
from .models import Task
def create(title, bucket_id, is_archived, is_completed, owner_id, due_date,
reminder):
kwargs = locals()
return base_repo.create(model=Task, **kwargs)
get = partial(base_repo.get, model=... | pombredanne/drf_tada | task/task_repo.py | Python | bsd-3-clause | 517 |
import logging
import csv
import os
from os.path import exists, join as pjoin
from StringIO import StringIO
from shutil import rmtree
from projects.exceptions import ProjectImportError
from vcs_support.backends.github import GithubContributionBackend
from vcs_support.base import BaseVCS, VCSVersion
log = logging.getL... | ojii/readthedocs.org | readthedocs/vcs_support/backends/git.py | Python | mit | 5,588 |
# Authors: Rob Zinkov, Mathieu Blondel
# License: BSD 3 clause
from ._stochastic_gradient import BaseSGDClassifier
from ._stochastic_gradient import BaseSGDRegressor
from ._stochastic_gradient import DEFAULT_EPSILON
class PassiveAggressiveClassifier(BaseSGDClassifier):
"""Passive Aggressive Classifier
Read ... | shyamalschandra/scikit-learn | sklearn/linear_model/_passive_aggressive.py | Python | bsd-3-clause | 17,641 |
# -*- 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-recommender | samples/generated_samples/recommender_v1beta1_generated_recommender_mark_recommendation_failed_async.py | Python | apache-2.0 | 1,597 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-25 10:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mamasemedia', '0007_auto_20160517_1341'),
]
operations = [
migrations.RemoveField(
... | Upande/MaMaSe | apps/mamasemedia/migrations/0008_auto_20160525_1056.py | Python | apache-2.0 | 506 |
# Copyright 2016 The Science and Technology Facilities Council
#
# 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 applic... | tofu-rocketry/apel | test/test_norm_sum_record.py | Python | apache-2.0 | 9,799 |
from django import forms
from .models import Page
class PageForm (forms.ModelForm): # PageCreate & PageEdit in admin
url = forms.CharField (required=False, help_text='Leave empty to auto-create from the title.')
# Do custom permission check
def clean_url (self):
url = self.cleaned_data['url']
... | normalnorway/normal.no | django/apps/cms/forms.py | Python | gpl-3.0 | 795 |
# -*- coding: UTF-8 -*-
# http://hu.wikipedia.org/wiki/Sakkmegnyit%C3%A1sok_list%C3%A1ja
import xml.etree.ElementTree as ET
def local2eng(text):
text = text.replace("0-0-0", "O-O-O").replace("0-0", "O-O")
text = text.replace("B", "R").replace("V", "Q").replace("H", "N").replace("F", "B")
return text
if... | pychess/pychess | utilities/eco-hu.py | Python | gpl-3.0 | 1,515 |
# Copyright 2013-2021 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)
'''Deprecate one Spack install in favor of another
Spack packages of different configurations cannot be installed to the s... | LLNL/spack | lib/spack/spack/cmd/deprecate.py | Python | lgpl-2.1 | 4,870 |
from __future__ import print_function
from __future__ import print_function
from unittest import TestCase
from torch.autograd import Variable
from torch import nn
import torch
import numpy as np
import qelos as q
class TestGRU(TestCase):
def test_gru_shapes(self):
batsize = 5
q.GRUCell.debug = Tru... | lukovnikov/qelos | test/test_rnn.py | Python | mit | 16,455 |
# DEFINITION:
# Reads Igor's (Wavemetric) binary wave format, .ibw, files.
#
# ALGORITHM:
# Parsing proper to version 2, 3, or version 5 (see Technical notes TN003.ifn:
# http://mirror.optus.net.au/pub/wavemetrics/IgorPro/Technical_Notes/) and data
# type 2 or 4 (non complex, single or double precision vector, real val... | awakenting/gif_fitting | fitgif/ReadIBW.py | Python | gpl-3.0 | 6,915 |
from django.contrib import auth
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.contrib.messages import get_messages, INFO
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from myhpom.models import State
class SignupTe... | ResearchSoftwareInstitute/MyHPOM | myhpom/tests/test_signup_view.py | Python | bsd-3-clause | 4,721 |
import json
from datetime import datetime
from sqlalchemy import create_engine, Column, DateTime, Integer
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from flask import current_app
engine = create_engine(current_app.config['DATABASE_URI'], convert_u... | flreey/private-navigation | models/base.py | Python | mit | 1,696 |
#!/usr/bin/python
# Copyright (C) 2010-2013 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 l... | opozo/web-endpoints | tictactoe_api.py | Python | apache-2.0 | 4,763 |
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenot... | kapilgarg1996/mp3wav | tests/apptest.py | Python | mit | 1,126 |
# 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 the Li... | openstack/manila | manila/db/migrations/alembic/versions/fdfb668d19e1_add_gateway_to_network_allocations_table.py | Python | apache-2.0 | 1,178 |
#!/usr/bin/env python3
# @author slandau3
import unittest
from square import reorder
class Tests(unittest.TestCase):
def test1(self):
"""
Test to make sure the program can handle a simple, ordinary input with negatives, 0 and positives
:return:
"""
self.assertEqual(reorde... | DakRomo/2017Challenges | challenge_9/python/slandau3/test.py | Python | mit | 1,251 |
# -*- coding: utf-8 -*-
"""
gdown.modules.crocko
~~~~~~~~~~~~~~~~~~~
This module contains handlers for crocko.
"""
import re
from datetime import datetime
from ..module import browser, acc_info_template
def getApikey(username, passwd):
r = browser()
content = re.search('<content type="text">(.+)</content... | oczkers/gdown | gdown/modules/crocko.py | Python | gpl-3.0 | 1,644 |
#!/usr/bin/env python
#
# Copyright 2015 Troy Mullins
# Licensed under MIT (https://github.com/Mullinst/fullstack-nanodegree-vm/blob/master/LICENSE)
#
# Test cases for tournament.py
from tournament import *
def testDeleteMatches():
deleteMatches()
print "1. Old matches can be deleted."
def testDelete():
... | Mullinst/fullstack-nanodegree-vm | vagrant/tournament/tournament_test.py | Python | mit | 4,697 |
"""
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... | Kankroc/pdf2image | pdf2image/pdf2image.py | Python | mit | 8,412 |
#!/usr/bin/env python
"""
Runs a Django management command.
Avoids the double-settings-import and extra sys.path additions of Django's
default manage.py.
"""
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moztrap.settings.default")
from django.core.management im... | mozilla/moztrap | manage.py | Python | bsd-2-clause | 392 |
from pyzabbix import zabbixapi
import json
url="http://10.210.71.145/zabbix/api_jsonrpc.php"
#log in
zb=zabbixapi(url=url,user="admin",password="zabbix")
response=zb.host.get(
{
"output":"extend",
"filter":
{
"host":"all-summary"
}
})
pri... | xluren/pyzabbix | get_host.py | Python | mit | 515 |
import sys
import traceback
import unittest
from contextlib import contextmanager
from unittest import expectedFailure
from unittest import mock # pylint:disable=unused-import # NOQA
from typing import Any, Callable, List, Iterator, Optional, Tuple, Type, TYPE_CHECKING
from salesforce.dbapi import driver
from salesf... | django-salesforce/django-salesforce | salesforce/dbapi/test_helpers.py | Python | mit | 5,470 |
# Copyright 2017 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... | eaplatanios/tensorflow | tensorflow/python/data/kernel_tests/dataset_from_generator_op_test.py | Python | apache-2.0 | 14,304 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-02 00:17
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0029_unicode_slug... | lang-uk/lang.org.ua | languk/home/migrations/0006_staticpage.py | Python | mit | 1,374 |
# -*- coding: utf-8 -*-
# rdiffweb, A web interface to rdiff-backup repositories
# Copyright (C) 2012-2021 rdiffweb contributors
#
# 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 ... | ikus060/rdiffweb | rdiffweb/controller/pref_sshkeys.py | Python | gpl-3.0 | 4,645 |
import numpy as np
from pax import plugin
class PosRecWeightedSum(plugin.PosRecPlugin):
"""Reconstruct x,y positions as the charge-weighted average of PMT positions in the top array.
"""
def reconstruct_position(self, peak):
hitpattern = peak.area_per_channel[self.pmts]
return np.average(s... | XENON1T/pax | pax/plugins/posrec/WeightedSum.py | Python | bsd-3-clause | 367 |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
class ProjectMemberIndexTest(APITestCase):
def test_simple(self):
user_1 = self.create_user('foo@localhost', username='foo')
user_2 = self.create_user('bar@localhost', use... | BayanGroup/sentry | tests/sentry/api/endpoints/test_project_member_index.py | Python | bsd-3-clause | 1,222 |
from ..core import Add, Expr, Integer, Mul, count_ops, diff
from ..core.assumptions import StdFactKB
from ..core.decorators import _sympifyit, call_highest_priority
from ..integrals import Integral
from ..polys import factor
from ..simplify import simplify, trigsimp
class BasisDependent(Expr):
"""
Super class... | skirpichev/omg | diofant/vector/basisdependent.py | Python | bsd-3-clause | 9,621 |
"""Templatetags for date parsing"""
import dateutil.parser
from django.template import Library
from django.template.defaultfilters import stringfilter
register = Library()
@stringfilter
def parse_iso_datetime(date_string):
"""
Args:
date_string (str): An ISO 8601-formatted datetime string
Returns... | mitodl/bootcamp-ecommerce | main/templatetags/parse_date.py | Python | bsd-3-clause | 561 |
"""Test for RFLink light components.
Test setup of RFLink lights component/platform. State tracking and
control of RFLink switch devices.
"""
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.rflink import EVENT_BUTTON_PRESSED
from homeassistant.const import (
ATTR_ENTITY_I... | Cinntax/home-assistant | tests/components/rflink/test_light.py | Python | apache-2.0 | 17,751 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Michael Dawson-Haggerty
# Distributed under the MIT License.
# Copied from the trimesh project.
# See https://github.com/mikedh/trimesh for more information.
# See https://github.com/mikedh/trimesh/blob/master/LICENSE.md for
# the license.
import numpy as np
class HeaderE... | Eric89GXL/vispy | vispy/io/stl.py | Python | bsd-3-clause | 5,942 |
from cnab240.tipos import EventoBase
class EventoInclusao(EventoBase):
def __init__(self, banco, **kwargs):
super(EventoInclusao, self).__init__(banco, 1)
args = self.clean_kwargs(kwargs)
seg_p = self.banco.registros.SegmentoP(**args)
self.adicionar_segmento(seg_p)
... | TracyWebTech/cnab240 | cnab240/eventos/cobranca.py | Python | mit | 539 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | wscullin/spack | var/spack/repos/builtin/packages/bucky/package.py | Python | lgpl-2.1 | 2,297 |
"""The AccuWeather component."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, Dict
from accuweather import AccuWeather, ApiError, InvalidApiKeyError, RequestsExceededError
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnecto... | kennedyshead/home-assistant | homeassistant/components/accuweather/__init__.py | Python | apache-2.0 | 4,256 |
#!/usr/bin/env python
# encoding: utf-8
import urllib
from config import USERNAME, EXTENSION, PASSWORD, APP_KEY, APP_SECRET, SERVER, MOBILE
from ringcentral import SDK
def main():
sdk = SDK(APP_KEY, APP_SECRET, SERVER)
platform = sdk.platform()
platform.login(USERNAME, EXTENSION, PASSWORD)
to_number... | ringcentral/python-sdk | demo_sms.py | Python | mit | 609 |
#
# This source file is part of appleseed.
# Visit https://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2017-2018 Francois Beaune, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining ... | Biart95/appleseed | sandbox/samples/python/studio/plugins/basicenumerator/__init__.py | Python | mit | 2,107 |
#!/usr/bin/env python3
# Copyright 2014-2015 The Meson development team
# 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... | jroivas/meson | mesonintrospect.py | Python | apache-2.0 | 6,700 |
from django.core.validators import RegexValidator
"""
This regex assumes that you have a clean string,
you should clean the string for spaces and other characters
"""
isAlphaNumeric = RegexValidator(
r"^[\w]*$", message="name must be alphanumeric", code="Invalid name"
)
| ebmdatalab/openprescribing | openprescribing/frontend/validators.py | Python | mit | 276 |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | epssy/hue | desktop/libs/libsentry/src/libsentry/api.py | Python | apache-2.0 | 8,127 |
# Copyright (c) 2016 OpenIO SAS
#
# 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, s... | open-io/oio-swift | oioswift/common/ring.py | Python | apache-2.0 | 2,218 |
# Copyright (c) 2012 OpenStack Foundation
# Copyright (c) 2012 Cloudscaling
# 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/l... | qwefi/nova | nova/scheduler/filters/aggregate_instance_extra_specs.py | Python | apache-2.0 | 2,950 |
"""Abstract tensor product."""
from __future__ import print_function, division
from sympy import Expr, Add, Mul, Matrix, Pow, sympify
from sympy.core.compatibility import range
from sympy.core.trace import Tr
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError... | kaushik94/sympy | sympy/physics/quantum/tensorproduct.py | Python | bsd-3-clause | 14,725 |
from unittest import TestCase
from nose.tools import assert_raises
from nose.tools import assert_not_equal, assert_in
from ..helpers.integration_test_helper import IntegrationTestHelper
class TestNameplaceFunctions(TestCase):
def setUp(self):
self.env_variables = IntegrationTestHelper.get_environment_var... | CartoDB/dataservices-api | test/integration/test_namedplace_functions.py | Python | bsd-3-clause | 2,305 |
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework.status import (
is_informational, is_success, is_redirect, is_client_error, is_server_error
)
class TestStatus(TestCase):
def test_status_categories(self):
self.assertFalse(is_informational(99))
self.a... | GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/rest_framework/tests/test_status.py | Python | agpl-3.0 | 1,159 |
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Index
import pandas._testing as tm
@pytest.mark.parametrize(
"interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
)
@pytest.mark.parametrize(
"a_vals,b_vals",
[
# Ints
([1, 2, 3, 4, 5], [5,... | jreback/pandas | pandas/tests/groupby/test_quantile.py | Python | bsd-3-clause | 9,272 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-18 16:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('workshops', '0096_change_help_text_in_training_request'),
]
operations = [
migration... | vahtras/amy | workshops/migrations/0097_auto_20160618_1132.py | Python | mit | 442 |
async def f(x):
async for i in await x:
pass
# comment before
async with x:
pass
[ x async for x in await x] | Microsoft/PTVS | Python/Tests/TestData/FormattingTests/async.py | Python | apache-2.0 | 153 |
import png
import sys
##GLOBALS
ELEMENT_WIDTH = 50
REGION_WIDTH_IN_ELEMENTS = 200
REGION_WIDTH = ELEMENT_WIDTH * REGION_WIDTH_IN_ELEMENTS
## Identifies all regions in a given square
## Returns list of coordinates of lower left corner of all regions
def findRegions(x,y,w):
xll = x/REGION_WIDTH * REGION_WIDTH
y... | oscarrobertson/Uk-Heightmap-Generator | main.py | Python | mit | 7,818 |
# © 2012 KMEE INFORMATICA LTDA
# @author Luiz Felipe do Divino Costa <luiz.divino@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class L10nBrCNABReturnEvent(models.Model):
"""
The class is used to register the Events of CNAB return fil... | kmee/l10n-brazil | l10n_br_account_payment_order/models/l10n_br_cnab_event.py | Python | agpl-3.0 | 3,785 |
from __future__ import absolute_import
from qgis.PyQt.QtCore import *
from .variablesview import custom_class_handlers, make_item
def handle_QModelIndex(value, parent):
make_item('valid', value.isValid(), parent)
if value.isValid():
make_item('row', value.row(), parent)
make_item('column', v... | wonder-sk/qgis-first-aid-plugin | handlers_qt.py | Python | gpl-2.0 | 453 |
#!/usr/bin/python3.5
#Author: Sasan Bahadaran
#Date: 5/1/17
#Organization: Commerce Data Service
#Description: This is a bot script for getting Census data from the Census
#Bureau API's and writing it to Wikipedia.
import pywikibot, json, os, requests, argparse, logging, time, json, sys
import mwpa... | CommerceDataService/census-wikidata-bot | wikipedia_bot.py | Python | mit | 14,594 |
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import re
def remove_short_words(words):
return [i for i in words if len(i) >= 2]
def get_cppkeywords(filename):
# print('Getting cpp_keywords for', filename)
remove_comments(filename)
cpp_words = remove_short_words(
... | MarinaMeyta/WhoseCppCode | core/cpp_keywords.py | Python | mit | 1,371 |
import unittest
from baseapptest import BaseAppTestCase
class AppTestCase(BaseAppTestCase):
def setUp(self):
super(AppTestCase, self).setUp()
self.privatePages = {
'/navigation': (200, 'application/json'),
'/hosted_party': (302, None),
'/current_campaign': (302... | SebastiaanPasterkamp/dnd-machine | app/tests/test_app.py | Python | gpl-3.0 | 5,542 |
from client import Client
from server import Server
host = str(input('Connect to [host]: '))
port = int(input('Connect to [port]: '))
user = str(input('Username: '))
s = Server('', port, user)
r = Client(host, port)
s.start()
r.start()
# s.connect((HOST, PORT))
# s.sendall(bytearray('Hello, world', 'utf8'))
# data = ... | MalteT/secure-chat-py | chat.py | Python | mit | 371 |
"""Test win32 shortcut script
"""
from twisted.trial import unittest
import os
if os.name == 'nt':
skipWindowsNopywin32 = None
try:
from twisted.python import shortcut
except ImportError:
skipWindowsNopywin32 = ("On windows, twisted.python.shortcut is not "
... | skycucumber/Messaging-Gateway | webapp/venv/lib/python2.7/site-packages/twisted/test/test_shortcut.py | Python | gpl-2.0 | 804 |
""" smashlib.plugins.history_completer
"""
from smashlib.plugins import Plugin
from smashlib.util.events import receives_event
from smashlib.channels import C_POST_RUN_INPUT
from smashlib._logging import smash_log, completion_log
from goulash.parsing import smart_split
from IPython.core.completerlib import TryNext
c... | mattvonrocketstein/smash | smashlib/plugins/history_completer.py | Python | mit | 1,752 |
from functools import partial
import inspect
class KVNest(str):
"""A subclass of str that allows namespacing keys for use in redis as well as provide partial methods into redis."""
def __new__(cls,*args,**kwargs):
"""Override's str's __new__ so we can store the redis connection if one is provided"""
if 'connect... | anateus/kvnest | src/kvnest.py | Python | mit | 992 |
# The Nexus software is licensed under the BSD 2-Clause license.
#
# You should have recieved a copy of this license with the software.
# If you did not, you can find one at the following link.
#
# http://opensource.org/licenses/bsd-license.php
from core.plugins import ProtocolPlugin
from core.decorators import *
fro... | TheArchives/Nexus | core/plugins/physcontrol.py | Python | bsd-2-clause | 3,219 |
# Release information about stickum
version = "0.1"
# description = "Your plan to rule the world"
# long_description = "More description about your plan"
# author = "Your Name Here"
# email = "YourEmail@YourDomain"
# copyright = "Vintage 2006 - a good year indeed"
# if it's open source, you might want to specify the... | chikatambun/stickum | stickum/release.py | Python | mit | 422 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from ureport.jobs.views import JobSourceCRUDL
urlpatterns = JobSourceCRUDL().as_urlpatterns()
| rapidpro/ureport | ureport/jobs/urls.py | Python | agpl-3.0 | 203 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import autocomplete_light
from django.utils.encoding import force_text
from .settings import USER_MODEL
from .utils.module_loading import get_real_model_class
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = [
... | luzfcb/django_documentos | django_documentos/autocomplete_light_registry.py | Python | bsd-3-clause | 1,391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.