commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
8798381c93c49d6f7a83320c3ae27c348e95b8ff | testhook/templatetags/testhook.py | testhook/templatetags/testhook.py | import sys
from django.template import Library, TemplateSyntaxError
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.text import slugify
if sys.version_info[0] == 2:
str = basestring
register = Library()
@register.simple_tag
def testhook(name, *args):
if not g... | import sys
from django.template import Library, TemplateSyntaxError
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.text import slugify
if sys.version_info[0] == 2:
str = basestring
register = Library()
@register.simple_tag
def testhook(name, *args):
if not g... | Simplify exception handling of required argument | Simplify exception handling of required argument
| Python | apache-2.0 | jjanssen/django-testhook |
790442eb5523f6992e8943ee1db5817cb27abdea | lingvo/jax/base_model_params.py | lingvo/jax/base_model_params.py | # Lint as: python3
# Copyright 2021 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 ... | # Lint as: python3
# Copyright 2021 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 ... | Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. | Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded.
PiperOrigin-RevId: 413779472
| Python | apache-2.0 | tensorflow/lingvo,tensorflow/lingvo,tensorflow/lingvo,tensorflow/lingvo |
fe6c924532750f646303fe82728795717b830819 | piper/version.py | piper/version.py | from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
... | from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
... | Remove argument defaulting from Version() | Remove argument defaulting from Version()
It was moved to the ABC and subsequently the check was left behind.
| Python | mit | thiderman/piper |
cd68d5bf444385334841a5ce07058cddb314ff82 | lobster/cmssw/data/merge_cfg.py | lobster/cmssw/data/merge_cfg.py | import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys
options = VarParsing('analysis')
options.register('chirp', default=None, mytype=VarParsing.varType.string)
options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsin... | import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys
options = VarParsing('analysis')
options.register('chirp', default=None, mytype=VarParsing.varType.string)
options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsin... | Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data. | Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
5da32c725200d9f3b319be40ae5c2d302dc72249 | cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py | cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | Update resource group unit test | Update resource group unit test
| Python | mit | gvlproject/libcloudbridge,gvlproject/cloudbridge |
afc18ff91bde4e6e6da554c7f9e520e5cac89fa2 | streams.py | streams.py | import praw
r = praw.Reddit(user_agent='nba_stream_parser')
submissions = r.get_subreddit('nbastreams').get_hot(limit=10)
for submission in submissions:
print(submission.selftext_html)
| from bs4 import BeautifulSoup
import html
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
def get_streams_for_team(teams):
teams.append('Game Thread')
submissions = r.get_subreddit('nbastreams').get_hot(limit=20)
streams = []
for submission in submissions:
if all(team in submissio... | Add comment parser; get stream links for any (2) team(s) | Add comment parser; get stream links for any (2) team(s)
| Python | mit | kshvmdn/NBAScores,kshvmdn/nba.js,kshvmdn/nba-scores |
46a376698851957813287fcb8deb1e7ebc222914 | alfred_listener/__main__.py | alfred_listener/__main__.py | #!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
def with_app(func):
@wraps(func)
@arg('--config', help='Path to config file', required=True)
def wrapper(*args, **kwargs):
config = args[0].config
from alfred_listener import create_app
ap... | #!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
def with_app(func):
@wraps(func)
@arg('--config', help='Path to config file', required=True)
def wrapper(*args, **kwargs):
config = args[0].config
from alfred_listener import create_app
ap... | Add an option to disable code reloader to runserver command | Add an option to disable code reloader to runserver command
| Python | isc | alfredhq/alfred-listener |
d37631451ad65588fdd8ab6cb300769deca3d043 | modules/roles.py | modules/roles.py | import discord
import shlex
from modules.botModule import BotModule
class Roles(BotModule):
name = 'Roles'
description = 'Allow for the assignment and removal of roles.'
help_text = ''
trigger_string = '!role' # String to listen for as trigger
async def parse_command(self, message, client):
... | import discord
import shlex
from modules.botModule import BotModule
class Roles(BotModule):
name = 'Roles'
description = 'Allow for the assignment and removal of roles.'
help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.'
' Executing it when you already ... | Add help text for Roles module. | Add help text for Roles module.
| Python | mit | suclearnub/scubot |
ba42df4296a02396e823ee9692fb84eb0deb8b7c | corehq/messaging/smsbackends/start_enterprise/views.py | corehq/messaging/smsbackends/start_enterprise/views.py | from __future__ import absolute_import
from corehq.apps.sms.views import IncomingBackendView
from corehq.messaging.smsbackends.start_enterprise.models import (
StartEnterpriseBackend,
StartEnterpriseDeliveryReceipt,
)
from datetime import datetime
from django.http import HttpResponse, HttpResponseBadRequest
c... | from __future__ import absolute_import
import logging
from corehq.apps.sms.views import IncomingBackendView
from corehq.messaging.smsbackends.start_enterprise.models import (
StartEnterpriseBackend,
StartEnterpriseDeliveryReceipt,
)
from datetime import datetime
from django.http import HttpResponse, HttpRespons... | Add logging to delivery receipt view | Add logging to delivery receipt view
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
1999e66070b02a30460c76d90787c7c20905363a | kboard/board/tests/test_templatetags.py | kboard/board/tests/test_templatetags.py | from .base import BoardAppTest
from board.templatetags.url_parameter import url_parameter
class UrlParameterTest(BoardAppTest):
def test_contains_correct_string(self):
parameter = {
'a': 13,
'query': 'hello',
'b': 'This is a test'
}
url_string = url_para... | from .base import BoardAppTest
from board.templatetags.url_parameter import url_parameter
from board.templatetags.hide_ip import hide_ip
class UrlParameterTest(BoardAppTest):
def test_contains_correct_string(self):
parameter = {
'a': 13,
'query': 'hello',
'b': 'This is ... | Add test of hide ip template tag | Add test of hide ip template tag
| Python | mit | kboard/kboard,cjh5414/kboard,hyesun03/k-board,hyesun03/k-board,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board |
32e066988a902f19d171225891f0a52a13945526 | frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py | frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py | import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
''')
| import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
| Move files only from Home folder | fix(patch): Move files only from Home folder | Python | mit | mhbu50/frappe,frappe/frappe,vjFaLk/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,mhbu50/frappe,vjFaLk/frappe,vjFaLk/frappe,StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,vjFaLk/frappe,saurabh6790/frappe,mhbu5... |
fe3559103917f6e9b61d0f6515502e3e530896cf | inidiff/cli.py | inidiff/cli.py | from __future__ import print_function
from . import diff
import argparse
RED = '\033[1;31m'
GREEN = '\033[1;32m'
END = '\033[0m'
def format_option(opt):
"""Return a formatted option in the form name=value."""
return '{}={}\n'.format(opt.option, opt.value)
def format_output(first, second, color=True):
... | from __future__ import print_function
import argparse
import sys
from . import diff
RED = '\033[1;31m'
GREEN = '\033[1;32m'
END = '\033[0m'
def format_option(opt):
"""Return a formatted option in the form name=value."""
return '{}={}\n'.format(opt.option, opt.value)
def format_output(first, second, colo... | Exit with 1 if there's a difference | Exit with 1 if there's a difference
| Python | mit | kragniz/inidiff |
5227ef25d9944c5e33b4a4f7e58259e3646ae52a | interactive.py | interactive.py | #Main program executor
import pyRecipeBook
import FoodGroups
#Welcome screen
welcomeMessage = "Welcome to pyRecipeBook!\n"
welcomeMessage += "Enter a command below:\n"
print(welcomeMessage)
#
pre = '# '
on = True
#Keep asking for inpyt
while(on):
command = input(pre)
#Run command
#Exiting commands
"Thank you f... | #Main program executor
import pyRecipeBook
import FoodGroups
#Welcome screen
welcomeMessage = "Welcome to pyRecipeBook!\n"
welcomeMessage += "Enter a command below:\n"
print(welcomeMessage)
#Method to run commands
def runCommand(command):
if command.strip() == 'exit':
return False
else:
return True
#
pre = '#... | Update interacitve.py - Add a method to run predefined commands. | Update interacitve.py
- Add a method to run predefined commands.
| Python | mit | VictorLoren/pyRecipeBook |
aa65464c86c562a690ba42901fa9dc24f17ba714 | xbrowse_server/base/management/commands/add_project.py | xbrowse_server/base/management/commands/add_project.py | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
class Command(BaseCommand):
def handle(self, *args, **options):
project_id = args[0]
if Project.objects.filter(project_id=project_id).exists():
raise Exception("Project exists :(")
... | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
import sys
class Command(BaseCommand):
def handle(self, *args, **options):
project_id = args[0]
if "." in project_id:
sys.exit("ERROR: A '.' in the project ID is not supported")
... | Print error if dot in project ids | Print error if dot in project ids
| Python | agpl-3.0 | ssadedin/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,ssadedin/seqr |
1b7509d8bd624bbf33352f622d8c03be6f3e35f2 | src/sentry/api/serializers/models/organization_member.py | src/sentry/api/serializers/models/organization_member.py | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMember
@register(OrganizationMember)
class OrganizationMemberSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'id': str(obj.id),
... | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMember
from sentry.utils.avatar import get_gravatar_url
@register(OrganizationMember)
class OrganizationMemberSerializer(Serializer):
def serialize(self, obj, attrs, user):
... | Add avatarUrl to team member serializers | Add avatarUrl to team member serializers
Conflicts:
src/sentry/api/serializers/models/organization_member.py
src/sentry/api/serializers/models/release.py
cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9
| Python | bsd-3-clause | jean/sentry,gencer/sentry,looker/sentry,ngonzalvez/sentry,gg7/sentry,mvaled/sentry,nicholasserra/sentry,wong2/sentry,beeftornado/sentry,JamesMura/sentry,alexm92/sentry,JamesMura/sentry,korealerts1/sentry,wujuguang/sentry,BayanGroup/sentry,imankulov/sentry,fotinakis/sentry,JTCunning/sentry,kevinlondon/sentry,jean/sentry... |
91ea026fa0c354c81cf0a1e52dbbe626b83a00f8 | app.py | app.py | import feedparser
from flask import Flask, render_template
app = Flask(__name__)
BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml"
@app.route("/")
def index():
feed = feedparser.parse(BBC_FEED)
return render_template("index.html", feed=feed.get('entries'))
if __name__ == "__main__":
app.run() | import requests
from flask import Flask, render_template
app = Flask(__name__)
BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml"
API_KEY = "c4002216fa5446d582b5f31d73959d36"
@app.route("/")
def index():
r = requests.get(
f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}... | Use requests instead of feedparser. | Use requests instead of feedparser.
| Python | mit | alchermd/headlines,alchermd/headlines |
79e23159c308a69896c464eda13c043dbbc8086e | thezombies/management/commands/validate_all_data_catalogs.py | thezombies/management/commands/validate_all_data_catalogs.py | from django.core.management.base import NoArgsCommand
from thezombies.tasks.main import validate_data_catalogs
class Command(NoArgsCommand):
"""Validate all of the agency data catalogs"""
def handle_noargs(self):
validator_group = validate_data_catalogs.delay()
self.stdout.write(u"\nSpawned d... | from django.core.management.base import NoArgsCommand
from thezombies.tasks.main import validate_data_catalogs
class Command(NoArgsCommand):
"""Validate all of the agency data catalogs"""
def handle_noargs(self, **options):
validator_group = validate_data_catalogs.delay()
self.stdout.write(u"... | Fix options on NoArgsCommand. Huh. | Fix options on NoArgsCommand. Huh.
| Python | bsd-3-clause | sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies |
7ca17e79f8c3dba7bc04377e7746a383a281562d | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import dotenv
| # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
import os
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.j... | Add `load_envs` to take a base path and recurse up, looking for .envs | Add `load_envs` to take a base path and recurse up, looking for .envs
| Python | mit | serverless/serverless-helpers-py |
4d793c8790b714e7e923d276cc139d9ca70e5a7d | temba/msgs/migrations/0089_populate_broadcast_send_all.py | temba/msgs/migrations/0089_populate_broadcast_send_all.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations, models
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_cou... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations, models
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_cou... | Tweak order of operations in populate migration | Tweak order of operations in populate migration
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro |
cfbb2e479577cdc3bce8f5f61dcc5ff5042fab48 | api_tests/institutions/views/test_institution_detail.py | api_tests/institutions/views/test_institution_detail.py | from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from osf_tests.factories import InstitutionFactory
from api.base.settings.defaults import API_BASE
class TestInstitutionDetail(ApiTestCase):
def setUp(self):
super(TestInstitutionDetail, self).setUp()
self.institution = I... | import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import InstitutionFactory
@pytest.mark.django_db
class TestInstitutionDetail:
@pytest.fixture()
def institution(self):
return InstitutionFactory()
@pytest.fixture()
def url_institution(self):
def u... | Convert institutions detail to pytest | Convert institutions detail to pytest
| Python | apache-2.0 | HalcyonChimera/osf.io,cslzchen/osf.io,mfraezz/osf.io,leb2dg/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,sloria/osf.io,leb2dg/osf.io,cslzchen/osf.io,cslzchen/osf.io,adlius/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,pattisdr/osf... |
1082be09cee7d94a245d89469dea9ff347c2796e | app/routes/users/schemas.py | app/routes/users/schemas.py | from app.schema_validation.definitions import uuid, datetime
post_create_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for creating user",
"type": "object",
"properties": {
'email': {"type": "string"},
'name': {"type": "string"},
... | from app.schema_validation.definitions import uuid, datetime
post_create_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for creating user",
"type": "object",
"properties": {
'email': {"type": "string"},
'name': {"type": "string"},
... | Drop email as property from post_update_user_schema | Drop email as property from post_update_user_schema
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api |
a65d6ae9a6be0988bb74ecff7982c91be5273c58 | meinberlin/apps/bplan/management/commands/bplan_auto_archive.py | meinberlin/apps/bplan/management/commands/bplan_auto_archive.py | from django.core.management.base import BaseCommand
from meinberlin.apps.bplan import models as bplan_models
class Command(BaseCommand):
help = 'Archive finished bplan projects.'
def handle(self, *args, **options):
bplans = bplan_models.Bplan.objects.filter(is_draft=False)
for bplan in bplan... | from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from meinberlin.apps.bplan import models as bplan_models
class Command(BaseCommand):
help = 'Archive finished bplan projects and delete old statements.'
def handle(self, *args, **options):
... | Delete statements from archived bplans | Delete statements from archived bplans
After a bplan is archived it's related statements may be deleted.
For simpler development/deployment the auto_archive script is extended
to delete the statements, altough it may have been possible to add
another command.
To prevent from loosing statements that are created just b... | Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
1f2d0b0978d55d471322ec3e8a93464f9da4c59b | xlsxcompose.py | xlsxcompose.py | import argparse
__author__ = 'perks'
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Migrate columns from one spreadsheet to columns in a new spreadsheet.'
)
parser.add_argument(
'-i',
'--input',
help='Input .xlsx file',
... | __author__ = 'perks'
from xlutils.copy import copy
from xlrd import open_workbook
import xlsxwriter
def compose(input, output, mappings):
START_ROW = 501
END_ROW = 1000
rb = open_workbook(input)
r_sheet = rb.sheet_by_name("CLEAN")
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.a... | Load settings from file, fix logic | Load settings from file, fix logic
| Python | mit | perks/xlsxcompose |
d8f8d7d2e6b9c7537a4f5cdd2c3b7251017186a3 | xutils/util.py | xutils/util.py | # -*- coding: utf-8 -*-
from subprocess import check_output
def which(command, which="/usr/bin/which"):
"""Find and return the first absolute path of command used by `which`.
If not found, return "".
"""
try:
return check_output([which, command]).split("\n")[0]
except Exception:
... | # -*- coding: utf-8 -*-
from subprocess import check_output as _check_output
from xutils import PY3, to_unicode
if PY3:
def check_output(cmd, timeout=None, encoding=None, **kwargs):
return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs)
else:
def check_output(cmd, timeout=None, encod... | Add check_output to be compatible with Py2 and Py3 | Add check_output to be compatible with Py2 and Py3
| Python | mit | xgfone/xutils,xgfone/pycom |
b06f7fb883e3e5dd03aa86e2ad8646f1ed907ce1 | awx/fact/__init__.py | awx/fact/__init__.py | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
logger = logging.getLogger('awx.fact')
| # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
| Remove logging from fact init | Remove logging from fact init
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx |
28dd3f171fe422ba6e15530e7dc4f6d7d831ba09 | xbrowse_server/base/management/commands/reload_family.py | xbrowse_server/base/management/commands/reload_family.py | from django.core.management.base import BaseCommand
from xbrowse_server import xbrowse_controls
from xbrowse_server.base.models import Project
from xbrowse_server.mall import get_datastore
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
parser.... | from django.core.management.base import BaseCommand
from xbrowse_server import xbrowse_controls
from xbrowse_server.base.models import Project
from xbrowse_server.mall import get_datastore
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
parser.... | Fix reload command for projects where each chrom is in a different vcf | Fix reload command for projects where each chrom is in a different vcf
| Python | agpl-3.0 | ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse |
1acd2471f667abf78155ee71fe9c6d8487a284ee | sklearn/linear_model/tests/test_isotonic_regression.py | sklearn/linear_model/tests/test_isotonic_regression.py | import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.arra... | import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.arra... | FIX : fix LLE test (don't ask me why...) | FIX : fix LLE test (don't ask me why...)
| Python | bsd-3-clause | untom/scikit-learn,trungnt13/scikit-learn,nrhine1/scikit-learn,hrjn/scikit-learn,arjoly/scikit-learn,rohanp/scikit-learn,khkaminska/scikit-learn,ky822/scikit-learn,JosmanPS/scikit-learn,madjelan/scikit-learn,PatrickOReilly/scikit-learn,arjoly/scikit-learn,fabioticconi/scikit-learn,olologin/scikit-learn,saiwing-yeung/sc... |
7cdc7d1157f7bd37277115d378d76a1daf717b47 | source/run.py | source/run.py | # -*- coding: utf-8 -*-
from autoreiv import AutoReiv
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except KeyboardInterrupt:
bot.close()
finally:
print('* Bye!')
| # -*- coding: utf-8 -*-
import asyncio
import time
from autoreiv import AutoReiv
def main():
while True:
bot = AutoReiv()
bot.load()
try:
bot.run(bot.config.get('login'), bot.config.get('password'))
except Exception as e:
print('* Crashed with error: {}'.format(e))
finally:
print('* Disconnected.... | Fix the main loop & reconnecting | Fix the main loop & reconnecting
| Python | mit | diath/AutoReiv |
656e6bfb18212990fc33a0e5b4d394c807c8d3ab | photutils/utils/tests/test_colormaps.py | photutils/utils/tests/test_colormaps.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from astropy.tests.helper import pytest
from ..colormaps import random_cmap
def test_colormap():
cmap = random_cmap(100, random_state=12345)
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from astropy.tests.helper import pytest
from ..colormaps import random_cmap
try:
import matplotlib
HAS_MATPLOTLIB = True
except ImportErro... | Check for matplotlib in tests | Check for matplotlib in tests
| Python | bsd-3-clause | astropy/photutils,larrybradley/photutils |
f112e7754e4f4368f0a82c3aae3a58f5300176f0 | spacy/language_data/tag_map.py | spacy/language_data/tag_map.py | # encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
"ADV": {POS: ADV},
"NOUN": {POS: NOUN},
"ADP": {POS: ADP},
"PRON": {POS: PRON},
"SCONJ": {POS: SCONJ},
"PROPN": {POS: PROPN},
"DET": {POS: DET},
"SYM": {POS: ... | # encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
"ADV": {POS: ADV},
"NOUN": {POS: NOUN},
"ADP": {POS: ADP},
"PRON": {POS: PRON},
"SCONJ": {POS: SCONJ},
"PROPN": {POS: PROPN},
"DET": {POS: DET},
"SYM": {POS: ... | Add PART to tag map | Add PART to tag map
16 of the 17 PoS tags in the UD tag set is added; PART is missing. | Python | mit | banglakit/spaCy,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,ho... |
c38e6b497457886cf829111b89d3f102765f0eb3 | takeyourmeds/reminders/tasks.py | takeyourmeds/reminders/tasks.py | from __future__ import absolute_import
import traceback
from celery import shared_task
from celery.utils.log import get_task_logger
from django.contrib.staticfiles.storage import staticfiles_storage
from takeyourmeds.utils.dt import local_time
from takeyourmeds.telephony.utils import send_sms, make_call
from .mode... | from __future__ import absolute_import
import traceback
from celery import shared_task
from celery.utils.log import get_task_logger
from django.contrib.staticfiles.storage import staticfiles_storage
from takeyourmeds.utils.dt import local_time
from takeyourmeds.telephony.utils import send_sms, make_call
from .mode... | Split into own method for clariy and "return" support | Split into own method for clariy and "return" support
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web |
ee0922cecbce8617afe36e9555078d5a3ba21878 | src/django_future/management/commands/runscheduledjobs.py | src/django_future/management/commands/runscheduledjobs.py | """Run scheduled jobs."""
import datetime
from optparse import make_option
from django.core.management.base import NoArgsCommand
from django_future import run_jobs
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--delete-completed', '-d', action='store_true',
... | """Run scheduled jobs."""
import datetime
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django_future import run_jobs
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--delete-completed', '-d', action='stor... | Raise a nicer CommandError instead of showing the ValueError on the command line. | Raise a nicer CommandError instead of showing the ValueError on the command line.
| Python | mit | shrubberysoft/django-future |
79e4839c06d8a3ae8de0c9a7c0cf7b536016dde3 | pyglab/pyglab.py | pyglab/pyglab.py | _defaults = {
'api_url': 'api/v3',
}
from .apirequest import ApiRequest, RequestType
from .users import Users
class Pyglab(object):
def __init__(self, url, token, api_url=_defaults['api_url']):
self._base_url = url.rstrip('/') + '/' + api_url.strip()
self._token = token
self._user = No... | _defaults = {
'api_url': 'api/v3',
}
from .apirequest import ApiRequest, RequestType
from .users import Users
class Pyglab(object):
def __init__(self, url, token, api_url=_defaults['api_url']):
self._base_url = url.rstrip('/') + '/' + api_url.strip()
self._token = token
self._user = No... | Create exactly one users function. | Create exactly one users function.
| Python | mit | sloede/pyglab,sloede/pyglab |
01ade9ff21440aa0aedd7e32f2338003a256e912 | readux/books/tests/__init__.py | readux/books/tests/__init__.py | # import tests so django will discover and run them
from readux.books.tests.models import *
from readux.books.tests.views import *
from readux.books.tests.tei import *
from readux.books.tests.annotate import *
from readux.books.tests.markdown_tei import *
| # import tests so django will discover and run them
from readux.books.tests.models import *
from readux.books.tests.views import *
from readux.books.tests.tei import *
from readux.books.tests.annotate import *
from readux.books.tests.markdown_tei import *
from readux.books.tests.export import *
from readux.books.tests... | Include consumer and export tests when running testsuite | Include consumer and export tests when running testsuite
| Python | apache-2.0 | emory-libraries/readux,emory-libraries/readux,emory-libraries/readux |
8d24a632dde955a9e4e093fe8764bc598cf65f4c | dynamic_subdomains/defaults.py | dynamic_subdomains/defaults.py | from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
def patterns(*args):
subdomains = SortedDict()
for x in args:
name = x['name']
if name in subdomains:
raise ImproperlyConfigured("Duplicate subdomain name: %s" % name)
... | from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
def patterns(*args):
subdomains = SortedDict()
for x in args:
name = x['name']
if name in subdomains:
raise ImproperlyConfigured("Duplicate subdomain name: %s" % name)
... | Remove unnecessary protection against using "default" as a subdomainconf | Remove unnecessary protection against using "default" as a subdomainconf
Thanks to Jannis Leidel <jezdez@enn.io> for the pointer.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
| Python | bsd-3-clause | playfire/django-dynamic-subdomains |
9672bd20203bc4235910080cca6d79c3b8e126b1 | nupic/research/frameworks/dendrites/modules/__init__.py | nupic/research/frameworks/dendrites/modules/__init__.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | Add DendriticLayerBase to init to ease experimentation | Add DendriticLayerBase to init to ease experimentation
| Python | agpl-3.0 | mrcslws/nupic.research,subutai/nupic.research,numenta/nupic.research,subutai/nupic.research,numenta/nupic.research,mrcslws/nupic.research |
b49ecba8c0a8ca05351b3eff6c1c244064bb5081 | tests/test_vector2_equality.py | tests/test_vector2_equality.py | import ppb_vector
def test_equal():
test_vector_1 = ppb_vector.Vector2(50, 800)
test_vector_2 = ppb_vector.Vector2(50, 800)
assert test_vector_1 == test_vector_2
def test_not_equal():
test_vector_1 = ppb_vector.Vector2(800, 800)
test_vector_2 = ppb_vector.Vector2(50, 800)
assert test_vector_1 != test_ve... | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
def test_equal():
test_vector_1 = Vector2(50, 800)
test_vector_2 = Vector2(50, 800)
assert test_vector_1 == test_vector_2
@given(x=vectors(), y=vectors())
def test_not_equal_equivalent(x: Vector2, y: Vector2):
assert (x !=... | Replace test for != with an Hypothesis test | tests/equality: Replace test for != with an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
8f4a8c2d463f3ed1592fcd1655de6435b4f2a047 | dataproperty/type/_typecode.py | dataproperty/type/_typecode.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_T... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0 # delete in the future
INTEGER = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 <... | Add INTEGER type as alias of INT type | Add INTEGER type as alias of INT type
| Python | mit | thombashi/DataProperty |
0a19e2a0dd7bed604e5ddd402d2d9f47b2760d77 | bagpipe/bgp/engine/flowspec.py | bagpipe/bgp/engine/flowspec.py | from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow
from exabgp.bgp.message.update.nlri.nlri import NLRI
from exabgp.reactor.protocol import AFI
from exabgp.reactor.protocol import SAFI
import logging
log = logging.getLogger(__name__)
@NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True)
@NLRI.register... | from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow
from exabgp.bgp.message.update.nlri.nlri import NLRI
from exabgp.reactor.protocol import AFI
from exabgp.reactor.protocol import SAFI
import logging
log = logging.getLogger(__name__)
@NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True)
@NLRI.register... | Fix eq/hash for FlowSpec NLRI | Fix eq/hash for FlowSpec NLRI
Bogus eq/hash was preventing withdraws from behaving
properly.
| Python | apache-2.0 | openstack/networking-bagpipe,openstack/networking-bagpipe-l2,openstack/networking-bagpipe,stackforge/networking-bagpipe-l2,openstack/networking-bagpipe-l2,stackforge/networking-bagpipe-l2 |
20fa7e30e4658984a4057f5c99ef293216f57815 | base_phone/controllers/main.py | base_phone/controllers/main.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | Make click2dial work in real life | Make click2dial work in real life
| Python | agpl-3.0 | OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony |
78c96e56b46f800c972bcdb5c5aa525d73d84a80 | src/setuptools_scm/__main__.py | src/setuptools_scm/__main__.py | import sys
from setuptools_scm import _get_version
from setuptools_scm import get_version
from setuptools_scm.config import Configuration
from setuptools_scm.integration import find_files
def main() -> None:
files = list(sorted(find_files("."), key=len))
try:
pyproject = next(fname for fname in files... | import argparse
import os
import warnings
from setuptools_scm import _get_version
from setuptools_scm.config import Configuration
from setuptools_scm.discover import walk_potential_roots
from setuptools_scm.integration import find_files
def main() -> None:
opts = _get_cli_opts()
root = opts.root or "."
... | Add options to better control CLI command | Add options to better control CLI command
Instead of trying to guess the `pyprojec.toml` file by looking at the
files controlled by the SCM, use explicit options to control it.
| Python | mit | pypa/setuptools_scm,pypa/setuptools_scm,RonnyPfannschmidt/setuptools_scm,RonnyPfannschmidt/setuptools_scm |
ce2855d82331fc7bb1ffdb07761d6ad235a1c6c9 | transport/tests/test_models.py | transport/tests/test_models.py | from django.test import TestCase
from org.models import Organization
from ..models import Bus
class BusModelTest(TestCase):
def setUp(self):
self.org = Organization.objects.create(
name='Some Org',
logo='/media/logos/some-org-logo.jpg',
description='We are a familiar ... | from django.test import TestCase
from org.models import Organization
from ..models import Bus, Route
class BusModelTest(TestCase):
def setUp(self):
self.org = Organization.objects.create(
name='Some Org',
logo='/media/logos/some-org-logo.jpg',
description='We are a fa... | Add some Route model tests | Add some Route model tests
| Python | mit | arturfelipe/condobus,arturfelipe/condobus,arturfelipe/condobus,arturfelipe/condobus |
ce5e322367a15198bdbea9d32401b8c779d0e4bf | config.py | config.py | #! /usr/bin/env python
import os
import warnings
import yaml
class Config(object):
config_fname = "configuration.yaml"
def __init__(self, config_fname=None):
config_fname = config_fname or self.config_fname
fo = open(config_fname, "r")
blob = fo.read()
fo.close()
self... | #! /usr/bin/env python
import os
import warnings
import yaml
class Config(object):
config_fname = "configuration.yaml"
def __init__(self, config_fname=None):
config_fname = config_fname or self.config_fname
fo = open(config_fname, "r")
blob = fo.read()
fo.close()
self... | Add Config.get() to skip KeyErrors | Add Config.get() to skip KeyErrors
Adds common `dict.get()` pattern to our own Config class, to enable
use of fallbacks or `None`, as appropriate. | Python | apache-2.0 | rossrader/destalinator |
a138d7126acd1418e4bec47aeecf5a96076d1acf | djangae/contrib/backup/urls.py | djangae/contrib/backup/urls.py | from django.conf.urls import include, url
from . import views
urlpatterns = (
url(
'^create-datastore-backup$',
views.create_datastore_backup,
name="create_datastore_backup"
),
)
| from django.conf.urls import url
from . import views
urlpatterns = (
url(
'^create-datastore-backup/?$',
views.create_datastore_backup,
name="create_datastore_backup"
),
)
| Fix the backup url to match the docs (and retain backwards compatibility) | Fix the backup url to match the docs (and retain backwards compatibility)
| Python | bsd-3-clause | potatolondon/djangae,potatolondon/djangae |
9c2efa3df7d39ef6724fb031d0bb674eb7195b2e | tv-script-generation/helper.py | tv-script-generation/helper.py | import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
... | import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
... | Remove copyright notice during preprocessing | Remove copyright notice during preprocessing
| Python | mit | elenduuche/deep-learning,elenduuche/deep-learning |
6bc25787dec8530b20db0a43b754c04f0170b9d8 | symfit/api.py | symfit/api.py | # Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators
# Expose useful objects.
from symfit.core.fit import (
Fit, Model, Constraint, ODEModel, ModelError, CallableModel,
CallableNumericalModel
)
from symfit.core.fit_results import FitResults
from symfit.core.ar... | # Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators
# Expose useful objects.
from symfit.core.fit import (
Fit, Model, Constraint, ODEModel, ModelError, CallableModel,
CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from... | Add GradientModel to the API | Add GradientModel to the API
| Python | mit | tBuLi/symfit |
169b5ec57404360d0c9c1c438aa357f62f61b9cf | contrib/chatops/actions/format_result.py | contrib/chatops/actions/format_result.py | import jinja2
import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
class FormatResultAction(Action):
def __init__(self, config):
super(FormatResultAction, self).__init__(config)
api_url = os.environ.get('ST2_ACTION_API_URL', None)
tok... | import jinja2
import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
class FormatResultAction(Action):
def __init__(self, config):
super(FormatResultAction, self).__init__(config)
api_url = os.environ.get('ST2_ACTION_API_URL', None)
tok... | Return empty string if result output is disabled | Return empty string if result output is disabled
| Python | apache-2.0 | StackStorm/st2,pixelrebel/st2,emedvedev/st2,peak6/st2,Plexxi/st2,Plexxi/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,punalpatel/st2,emedvedev/st2,dennybaa/st2,punalpatel/st2,nzlosh/st2,nzlosh/st2,peak6/st2,peak6/st2,StackStorm/st2,armab/st2,StackStorm/st2,punalpatel/st2,emedvedev/st2,nzlosh/st2,Plexxi/st2,tonybaloney/st2,... |
42f2b69639b34644f42507bc65d399f423e348ef | tests/grammar_unified_tests.py | tests/grammar_unified_tests.py | from unittest import TestCase
from regparser.grammar.unified import *
class GrammarCommonTests(TestCase):
def test_depth1_p(self):
text = '(c)(2)(ii)(A)(<E T="03">2</E>)'
result = depth1_p.parseString(text)
self.assertEqual('c', result.p1)
self.assertEqual('2', result.p2)
... | # -*- coding: utf-8 -*-
from unittest import TestCase
from regparser.grammar.unified import *
class GrammarCommonTests(TestCase):
def test_depth1_p(self):
text = '(c)(2)(ii)(A)(<E T="03">2</E>)'
result = depth1_p.parseString(text)
self.assertEqual('c', result.p1)
self.assertEqual... | Add tests for marker_comment from ascott1/appendix-ref | Add tests for marker_comment from ascott1/appendix-ref
| Python | cc0-1.0 | grapesmoker/regulations-parser,willbarton/regulations-parser,adderall/regulations-parser |
bcf4f87e3690986827d8d34eea5e7edfc03485e2 | cassandra_migrate/test/test_cql.py | cassandra_migrate/test/test_cql.py | from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
['CREATE TABLE hello', 'CREATE TABLE world']),
# Two st... | from __future__ import unicode_literals
import pytest
from cassandra_migrate.cql import CqlSplitter
@pytest.mark.parametrize('cql,statements', [
# Two statements, with whitespace
('''
CREATE TABLE hello;
CREATE TABLE world;
''',
['CREATE TABLE hello', 'CREATE TABLE world']),
# Two st... | Add CQL-splitting test case for double-dollar-sign strings | Add CQL-splitting test case for double-dollar-sign strings
| Python | mit | Cobliteam/cassandra-migrate,Cobliteam/cassandra-migrate |
0f981d86802706edb78b7d76f6c4b68198876032 | tests/steps/express-install.py | tests/steps/express-install.py | #!/usr/bin/python
from __future__ import unicode_literals
import libvirt
from general import libvirt_domain_get_val, libvirt_domain_get_context
def libvirt_domain_get_install_state(title):
state = None
conn = libvirt.openReadOnly(None)
doms = conn.listAllDomains()
for dom in doms:
try:
... | #!/usr/bin/python
from __future__ import unicode_literals
import libvirt
from time import sleep
from general import libvirt_domain_get_val, libvirt_domain_get_context
def libvirt_domain_get_install_state(title):
state = None
conn = libvirt.openReadOnly(None)
doms = conn.listAllDomains()
for dom in do... | Add "Installation finished check" step | tests: Add "Installation finished check" step
Step that asks libvirt every minute if VM state is installed. Step
fails after specified amount of time, if not.
https://bugzilla.gnome.org/show_bug.cgi?id=748006
| Python | lgpl-2.1 | vbenes/gnome-boxes,vbenes/gnome-boxes |
46017b7c1f480f5cb94ca0ef380b0666f8b77d0f | helevents/models.py | helevents/models.py | from django.db import models
from helusers.models import AbstractUser
class User(AbstractUser):
def __str__(self):
return ' - '.join([super().__str__(), self.get_display_name(), self.email])
def get_display_name(self):
return '{0} {1}'.format(self.first_name, self.last_name).strip()
def ... | from django.db import models
from helusers.models import AbstractUser
class User(AbstractUser):
def __str__(self):
return ' - '.join([self.get_display_name(), self.email])
def get_display_name(self):
return '{0} {1}'.format(self.first_name, self.last_name).strip()
def get_default_organiz... | Remove uuid display from user string | Remove uuid display from user string
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents |
8eb4f1e660de74837c7d05b1ee9076a58a551093 | test/python_api/default-constructor/sb_stringlist.py | test/python_api/default-constructor/sb_stringlist.py | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.AppendString("another string")
obj.AppendList(None, 0)
obj.AppendList(lldb.SBStringList())
obj.GetSize()
obj.GetStringAtIndex(0xffffffff)
obj.Clear()
... | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.AppendString("another string")
obj.AppendString(None)
obj.AppendList(None, 0)
obj.AppendList(lldb.SBStringList())
obj.GetSize()
obj.GetStringAtIndex(0x... | Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. | Add fuzz call to SBStringList.AppendString(None). LLDB should not crash.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb |
ae00c60510e28c0852ac6ad14bab86563b5e1399 | mica/common.py | mica/common.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Common definitions for Mica subpackages
"""
import os
class MissingDataError(Exception):
pass
FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive')
# The MICA_ARCHIVE env. var can be a colon-delimited path, which allo... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Common definitions for Mica subpackages
"""
import os
class MissingDataError(Exception):
pass
FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive')
# The MICA_ARCHIVE env. var can be a colon-delimited path, which allo... | Use os.pathsep instead of ':' for windows compat | Use os.pathsep instead of ':' for windows compat
| Python | bsd-3-clause | sot/mica,sot/mica |
c04d8dfaf3b4fcbddedb0973a501609ffb9472f6 | simpleflow/settings/__init__.py | simpleflow/settings/__init__.py | import sys
from future.utils import iteritems
from . import base
def put_setting(key, value):
setattr(sys.modules[__name__], key, value)
_keys.add(key)
def configure(dct):
for k, v in iteritems(dct):
put_setting(k, v)
# initialize a list of settings names
_keys = set()
# look for settings a... | from pprint import pformat
import sys
from future.utils import iteritems
from . import base
def put_setting(key, value):
setattr(sys.modules[__name__], key, value)
_keys.add(key)
def configure(dct):
for k, v in iteritems(dct):
put_setting(k, v)
def print_settings():
for key in sorted(_ke... | Add utility method to print all settings | Add utility method to print all settings
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow |
db02cadeb115bf3f7a8dd9be40d8a62d75d3559f | corehq/apps/hqwebapp/middleware.py | corehq/apps/hqwebapp/middleware.py | from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from corehq.util.soft_assert import soft_assert
from django.conf import settings
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | import logging
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from django.conf import settings
logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | Revert "Revert "log to file, don't email"" | Revert "Revert "log to file, don't email""
This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.
| Python | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq |
eef7f3797a6228c9e06717c3be49801a10b457a5 | registries/views.py | registries/views.py | from django.http import HttpResponse
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from registries.models import Organization
from registries.serializers import DrillerListSerializer, DrillerSerializer
class APIDrillerListCreateView(Lis... | from django.http import HttpResponse
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from registries.models import Organization
from registries.serializers import DrillerListSerializer, DrillerSerializer
class APIDrillerListCreateView(Lis... | Add docstrings to view classes | Add docstrings to view classes
| Python | apache-2.0 | bcgov/gwells,rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells |
3902e8183a9b5aab416b3574c3c415d9cc5c1740 | src/test/test_location_info.py | src/test/test_location_info.py | import pytest
import pytz
from astral import LocationInfo
class TestLocationInfo:
def test_Default(self):
loc = LocationInfo()
assert loc.name == "Greenwich"
assert loc.region == "England"
assert loc.timezone == "Europe/London"
assert loc.latitude == pytest.approx(51.4733, ... | import pytest
import pytz
from astral import LocationInfo
class TestLocationInfo:
def test_Default(self):
loc = LocationInfo()
assert loc.name == "Greenwich"
assert loc.region == "England"
assert loc.timezone == "Europe/London"
assert loc.latitude == pytest.approx(51.4733, ... | Make sure we're testing the right function! | Make sure we're testing the right function!
| Python | apache-2.0 | sffjunkie/astral,sffjunkie/astral |
a31e62f2a981f7662aee8a35ad195252a542d08d | plugins/say.py | plugins/say.py | from motobot import command, action
@command('say')
def say_command(bot, message, database):
masters = [
"Moto-chan",
"Motoko11",
"Akahige",
"betholas",
"Baradium",
"Cold_slither",
"Drahken"
]
if message.nick.lower() not in [x.lower() for x in m... | from motobot import command, action
@command('say')
def say_command(bot, message, database):
masters = [
"Moto-chan",
"Motoko11",
"MotoNyan",
"Akahige",
"betholas",
"Baradium",
"Cold_slither",
"Drahken"
]
if message.nick.lower() not in [... | Add MotoNyan to mad hax | Add MotoNyan to mad hax
| Python | mit | Motoko11/MotoBot |
662101e89943fe62b7036894140272e2f9ea4f78 | ibmcnx/test/test.py | ibmcnx/test/test.py | import ibmcnx.test.loadFunction
loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| import ibmcnx.test.loadFunction
ibmcnx.test.loadFunction.loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| Customize scripts to work with menu | Customize scripts to work with menu
| Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
89b463c5ce29e89bfcf444de9a8d73bc1ad78fc8 | omop_harvest/migrations/0003_avocado_metadata_migration.py | omop_harvest/migrations/0003_avocado_metadata_migration.py | # -*- coding: utf-8 -*-
from south.v2 import DataMigration
class Migration(DataMigration):
def forwards(self, orm):
"Perform a 'safe' load using Avocado's backup utilities."
from avocado.core import backup
backup.safe_load(u'0001_avocado_metadata', backup_path=None,
using='defa... | # -*- coding: utf-8 -*-
from south.v2 import DataMigration
class Migration(DataMigration):
depends_on = (
("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"),
)
def forwards(self, orm):
"Perform a 'safe' load using Avocado's backup utilities."
from avocad... | Add avocado dependency to metadata migration. | Add avocado dependency to metadata migration.
Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com>
| Python | bsd-2-clause | chop-dbhi/omop_harvest,chop-dbhi/omop_harvest,chop-dbhi/omop_harvest |
7bb851e54b9cc245259809c828ddbef62239c210 | sensor_mqtt.py | sensor_mqtt.py | #!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open("config.yml", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = "sensor_mqtt_"+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqt... | #!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open("config.yml", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = "sensor_mqtt_"+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqt... | Handle sensors / types that aren't in config file | Handle sensors / types that aren't in config file
| Python | mit | sushack/pi_sensor_mqtt,OxFloodNet/pi_sensor_mqtt |
727702d6d5cf8d43ac9c4f8011ff2b6d78cfbe4c | account_constraints/model/account_move.py | account_constraints/model/account_move.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Use constraint decorator on account_constraints+ | [IMP] Use constraint decorator on account_constraints+
| Python | agpl-3.0 | pedrobaeza/account-financial-tools,VitalPet/account-financial-tools,amoya-dx/account-financial-tools,VitalPet/account-financial-tools,credativUK/account-financial-tools,lepistone/account-financial-tools,damdam-s/account-financial-tools,acsone/account-financial-tools,Pexego/account-financial-tools,raycarnes/account-fina... |
5a0659ed9e4f8085009c04ade4f66cbd5d3c94bd | openedx/core/djangoapps/user_api/accounts/permissions.py | openedx/core/djangoapps/user_api/accounts/permissions.py | """
Permissions classes for User accounts API views.
"""
from __future__ import unicode_literals
from rest_framework import permissions
USERNAME_REPLACEMENT_GROUP = "username_replacement_admin"
class CanDeactivateUser(permissions.BasePermission):
"""
Grants access to AccountDeactivationView if the requesting... | """
Permissions classes for User accounts API views.
"""
from __future__ import unicode_literals
from django.conf import settings
from rest_framework import permissions
USERNAME_REPLACEMENT_GROUP = "username_replacement_admin"
class CanDeactivateUser(permissions.BasePermission):
"""
Grants access to AccountD... | Replace group with static username | Replace group with static username
| Python | agpl-3.0 | appsembler/edx-platform,stvstnfrd/edx-platform,msegado/edx-platform,edx-solutions/edx-platform,eduNEXT/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,mitocw/edx-platform,msegado/edx-platform,eduNEXT/edx-platform,ESOedX/edx-platform,cpennington/edx-platform,stvstnfrd/edx-platform,jolyonb/edx-platform,eduNEXT... |
e3185bd059becaf83aaeed9951f695db4ac32511 | schema/remind.py | schema/remind.py | from asyncqlio.orm.schema.column import Column
from asyncqlio.orm.schema.table import table_base
from asyncqlio.orm.schema.types import BigInt, Serial, Text, Timestamp
Table = table_base()
class Reminder(Table): # type: ignore
id = Column(Serial, primary_key=True)
guild_id = Column(BigInt)
channel_id = ... | from asyncqlio.orm.schema.column import Column
from asyncqlio.orm.schema.table import table_base
from asyncqlio.orm.schema.types import BigInt, Serial, Text, Timestamp
Table = table_base()
class Reminder(Table): # type: ignore
id = Column(Serial, primary_key=True)
guild_id = Column(BigInt)
channel_id = ... | Allow topic to be nullable in schema | Allow topic to be nullable in schema
| Python | mit | BeatButton/beattie-bot,BeatButton/beattie |
6cf8bad4faa15bcbc149db678e2ec232ce82b72a | utils/efushell/SocketDriver.py | utils/efushell/SocketDriver.py | import string
import socket
import sys
import time
import threading
class SimpleSocket:
def __init__(self, hostname="localhost", port=8888, timeout=2):
self.access_semaphor = threading.Semaphore(1)
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket... | import string
import socket
import sys
import time
import threading
class SimpleSocket:
def __init__(self, hostname="localhost", port=8888, timeout=2):
self.access_semaphor = threading.Semaphore(1)
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket... | Move string formatting onto two lines for readability | Move string formatting onto two lines for readability
| Python | bsd-2-clause | ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit,ess-dmsc/event-formation-unit |
66970aed3876cdae30a77eb50960caf29118248f | lms/djangoapps/api_manager/management/commands/migrate_orgdata.py | lms/djangoapps/api_manager/management/commands/migrate_orgdata.py | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... | Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present | Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
| Python | agpl-3.0 | edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform |
60116f05c86658d4ae929e0f1fb7e4e039515298 | src/adhocracy/migration/versions/071_add_badge_impact.py | src/adhocracy/migration/versions/071_add_badge_impact.py | from sqlalchemy import MetaData, Table, Column
from sqlalchemy import Integer
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
table = Table('badge', meta, autoload=True)
col = Column('impact', Integer, default=0, nullable=False)
col.create(table)
| from sqlalchemy import MetaData, Table, Column
from sqlalchemy import Integer
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
table = Table('badge', meta, autoload=True)
col = Column('impact', Integer, default=0, server_default=u'0',
nullable=False)
col.create(table... | Fix badge impact migration if badges are present | Fix badge impact migration if badges are present
If badges are already present in the system, their impact value must be set to something other than NULL. (default=0 is misleading, since it just applies to newly created badges, see http://stackoverflow.com/q/16097149/35070).
| Python | agpl-3.0 | phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocra... |
03de222d2e9655606f3a8faedfc2293d138527bf | one_time_eval.py | one_time_eval.py | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... | Increase iterations. Add assertion of max board cards. | Increase iterations. Add assertion of max board cards.
| Python | mit | zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments |
0de213c88dcee2db8f8cd416ff928e6018329e68 | passwd_change.py | passwd_change.py | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 5:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
log_file = _args[4]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
... | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 8:
keys_file = _args[1]
passwd_orig = _args[2]
passwd_new = _args[3]
passwd_log = _args[4]
shadow_orig = _args[5]
shadow_new = _args[6]
shadow_log = _args[7]
... | Add shadow changing support according to our new passwd. | Add shadow changing support according to our new passwd.
| Python | mit | maxsocl/oldmailer |
99bb83abc18be1581735dc03c21a680060e9a14c | l10n_it_website_portal_fiscalcode/controllers/main.py | l10n_it_website_portal_fiscalcode/controllers/main.py | # Copyright 2019 Simone Rubino
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _
from odoo.addons.portal.controllers.portal import CustomerPortal
from odoo.http import request
CustomerPortal.OPTIONAL_BILLING_FIELDS.extend(['fiscalcode'])
class WebsitePortalFiscalCode(CustomerPortal... | # Copyright 2019 Simone Rubino
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _
from odoo.addons.portal.controllers.portal import CustomerPortal
from odoo.http import request
CustomerPortal.OPTIONAL_BILLING_FIELDS.extend(['fiscalcode'])
class WebsitePortalFiscalCode(CustomerPortal... | FIX l10n_it_website_portal_fiscalcode check after invoice issuing | FIX l10n_it_website_portal_fiscalcode check after invoice issuing
Steps:
- Create a partner (type company) and give them portal access
- With the new user, access to portal
- Edit partner details setting fiscal code with 11 digits
- Using admin, create an invoice for that partner and validate
- Using the new use... | Python | agpl-3.0 | OCA/l10n-italy,dcorio/l10n-italy,OCA/l10n-italy,dcorio/l10n-italy,dcorio/l10n-italy,OCA/l10n-italy |
fb58ecee7e3e71f0dbb202f7284c3af20ccbcdaa | shared/logger.py | shared/logger.py | import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
logging.basicConfig(format='%... | import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
console = logging.StreamHandl... | Allow logging to console as well as disk | Allow logging to console as well as disk
| Python | mit | Mo-Talha/Nomad,Mo-Talha/Nomad,Mo-Talha/Nomad,Mo-Talha/Nomad |
9358b4ebf433a1c23d7c12b99e0253f3741eed8c | contrail_provisioning/config/templates/contrail_api_conf.py | contrail_provisioning/config/templates/contrail_api_conf.py | import string
template = string.Template("""
[DEFAULTS]
ifmap_server_ip=$__contrail_ifmap_server_ip__
ifmap_server_port=$__contrail_ifmap_server_port__
ifmap_username=$__contrail_ifmap_username__
ifmap_password=$__contrail_ifmap_password__
cassandra_server_list=$__contrail_cassandra_server_list__
listen_ip_addr=$__con... | import string
template = string.Template("""
[DEFAULTS]
ifmap_server_ip=$__contrail_ifmap_server_ip__
ifmap_server_port=$__contrail_ifmap_server_port__
ifmap_username=$__contrail_ifmap_username__
ifmap_password=$__contrail_ifmap_password__
cassandra_server_list=$__contrail_cassandra_server_list__
listen_ip_addr=$__con... | Enable port list optimization by default for new install+provision | config-perf: Enable port list optimization by default for new install+provision
From R1.05 onwards port is created as child of project. This leads to
better list performance.
Change-Id: Id0acbd1194403c500cdf0ee5851ef6cf5dba1c97
Closes-Bug: #1441924
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning |
3f2b1fd9d8d7472323de24e971b004d177637c95 | php4dvd/model/application.py | php4dvd/model/application.py | Class Application(object):
def __init__(sefl, driver):
self.driver = driver
def go_to_homepage(self):
self.driver.get("http://hub.wart.ru/php4dvd/")
def login(self, user):
driver = self.driver
driver.find_element_by_id("username").clear()
driver.find_element_by_id(... | Class Application(object):
def __init__(sefl, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def go_to_homepage(self):
self.driver.get("http://hub.wart.ru/php4dvd/")
def login(self, user):
driver = self.driver
driver.find_element_by_id("usernam... | Set wait variable to 10 seconds. | Set wait variable to 10 seconds.
| Python | bsd-2-clause | bsamorodov/selenium-py-training-samorodov |
69890f36b1853b3845ff29ec15ccde11f7ac86f2 | zerver/migrations/0306_custom_profile_field_date_format.py | zerver/migrations/0306_custom_profile_field_date_format.py | from django.db import migrations
class Migration(migrations.Migration):
"""
We previously accepted invalid ISO 8601 dates like 1909-3-5 for
date values of custom profile fields. Correct them by adding the
missing leading zeros: 1909-03-05.
"""
dependencies = [
("zerver", "0305_realm_d... | from django.db import migrations
class Migration(migrations.Migration):
"""
We previously accepted invalid ISO 8601 dates like 1909-3-5 for
date values of custom profile fields. Correct them by adding the
missing leading zeros: 1909-03-05.
"""
dependencies = [
("zerver", "0305_realm_d... | Enforce evaluation order in 0306 WHERE clause. | migrations: Enforce evaluation order in 0306 WHERE clause.
Depending on PostgreSQL’s query plan, it was possible for the value
condition to be evaluated before the field_type condition was checked,
leading to errors like
psycopg2.errors.InvalidDatetimeFormat: invalid value "stri" for "YYYY"
DETAIL: Value must be an ... | Python | apache-2.0 | zulip/zulip,eeshangarg/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,rht/zulip,kou/zulip,rht/zulip,andersk/zulip,punchagan/zulip,hackerkid/zulip,kou/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,punchagan/zulip,kou/zulip,andersk/zulip,punchagan/zulip,rht/zulip,hackerkid/zulip,andersk/zulip,rht/zulip,rht/zulip,ees... |
72a9dd0f0cff3fc6dcc97a4068b82e4b13bbc127 | accounts/management/__init__.py | accounts/management/__init__.py | from django.db.models.signals import post_syncdb
from django.conf import settings
from accounts import models
def ensure_core_accounts_exists(sender, **kwargs):
create_source_account()
create_sales_account()
create_expired_account()
def create_sales_account():
name = getattr(settings, 'ACCOUNTS_SAL... | from django.db.models.signals import post_syncdb
from django.conf import settings
from accounts import models
def ensure_core_accounts_exists(sender, **kwargs):
create_source_account()
create_sales_account()
create_expired_account()
def create_sales_account():
name = getattr(settings, 'ACCOUNTS_SAL... | Remove print statements for syncdb receivers | Remove print statements for syncdb receivers
| Python | bsd-3-clause | django-oscar/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,amsys/django-account-balances,carver/django-account-balances,Jannes123/django-oscar-accounts,machtfit/django-oscar-accounts,michaelkuty/django-oscar-accounts,amsys/django-account-balances,django-oscar/django-oscar-acc... |
4aa11073a551c8a026daea9175336b63dd9780b2 | src/poliastro/twobody/events.py | src/poliastro/twobody/events.py | from astropy import units as u
from numpy.linalg import norm
class LithobrakeEvent:
"""Terminal event that detects impact with the attractor surface.
Parameters
----------
R : float
Radius of the attractor.
"""
def __init__(self, R):
self._R = R
self._last_t = None
... | from astropy import units as u
from numpy.linalg import norm
class LithobrakeEvent:
"""Terminal event that detects impact with the attractor surface.
Parameters
----------
R : float
Radius of the attractor.
"""
def __init__(self, R):
self._R = R
self._last_t = None
... | Add altitude cross event detector | Add altitude cross event detector
| Python | mit | poliastro/poliastro |
3d1625e5e9a6a90cec1f2e18739462b006905c88 | game.py | game.py | from deuces import Card, Deck
class Game():
"""
Contains a deck of cards that can be accessed by players to play
various card games.
"""
def __init__(self, name='kiwi'):
self.players = []
self.name = name
self.deck = Deck()
self.visible_cards = []
def add_play... | from deuces import Card, Deck
class Game():
"""
Contains a deck of cards that can be accessed by players to play
various card games.
"""
def __init__(self, name='kiwi'):
self.players = []
self.name = name
self.deck = Deck()
self.visible_cards = []
def add_play... | Fix behavioural bug in shuffling | Fix behavioural bug in shuffling
Previously shuffling would create a new deck, implying that all the
cards had been "picked up" and were being shuffled for a new hand.
However, this did not pick up the visible cards from the game, so the
visible cards would just continue to grow unchecked. This clears the
visible card... | Python | bsd-2-clause | dramborleg/text-poker |
4ec2672dc22c3477984e335e3678f3a2e69ecbd2 | wger/exercises/migrations/0018_delete_pending_exercises.py | wger/exercises/migrations/0018_delete_pending_exercises.py | # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exer... | # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_bases(apps, schema_editor):
"""
Delete all pending bases
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Base = apps.... | Delete both pending bases and translations | Delete both pending bases and translations
| Python | agpl-3.0 | wger-project/wger,wger-project/wger,wger-project/wger,wger-project/wger |
513b23b169e87a92b2fdf0bd6b33778ea68b9b24 | imagekit/management/commands/ikcachevalidate.py | imagekit/management/commands/ikcachevalidate.py | from optparse import make_option
from django.core.management.base import BaseCommand
from django.db.models.loading import cache
from ...utils import validate_app_cache
class Command(BaseCommand):
help = ('Validates the image cache for a list of apps.')
args = '[apps]'
requires_model_validation = True
... | from optparse import make_option
from django.core.management.base import BaseCommand
from django.db.models.loading import cache
from ...utils import validate_app_cache
class Command(BaseCommand):
help = ('Validates the image cache for a list of apps.')
args = '[apps]'
requires_model_validation = True
... | Rename force flag to force-revalidation | Rename force flag to force-revalidation
| Python | bsd-3-clause | pcompassion/django-imagekit,FundedByMe/django-imagekit,tawanda/django-imagekit,tawanda/django-imagekit,pcompassion/django-imagekit,pcompassion/django-imagekit,FundedByMe/django-imagekit |
af2f7338c2c9bdddbb90af2ce96866af98482215 | concurrency/test_get_websites.py | concurrency/test_get_websites.py | import unittest
from unittest.mock import patch
from concurrency.get_websites import load_url as load_url
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.get_websites.requests')
def test_load_url(self, m):
""" Check that we're getting the data from a request object """
m.get = l... | import unittest
from unittest.mock import patch, MagicMock
from concurrency.get_websites import load_url as load_url
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.get_websites.requests')
def test_load_url_returns_data(self, m):
""" Check that we're getting the data from a request obje... | Add a test case to see that we're making a request with the url we pass in | Add a test case to see that we're making a request with the url we pass in
| Python | mit | b-ritter/python-notes,b-ritter/python-notes |
a09cf20b13c82b8521e2e36bbd8802a4578cefac | csunplugged/tests/topics/models/test_curriculum_integration.py | csunplugged/tests/topics/models/test_curriculum_integration.py | from model_mommy import mommy
from tests.BaseTestWithDB import BaseTestWithDB
from topics.models import CurriculumIntegration
from topics.models import CurriculumArea
from topics.models import Lesson
from tests.topics import create_topics_test_data
class CurriculumIntegrationModelTest(BaseTestWithDB):
def __init... | from model_mommy import mommy
from tests.BaseTestWithDB import BaseTestWithDB
from topics.models import CurriculumIntegration
from topics.models import CurriculumArea
from topics.models import Lesson
from tests.topics import create_topics_test_data
class CurriculumIntegrationModelTest(BaseTestWithDB):
def __init... | Remove many to many key generation in test | Remove many to many key generation in test
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged |
a00a657eff2b5ffc4453ef751b1d146ca386fd6a | app/views/create_user.py | app/views/create_user.py | from flask import request, flash, render_template
import bcrypt
from app import app, helpers
@app.route('/create_user', methods=['GET', 'POST'])
def create_user():
if request.method == 'POST':
username = request.form.get('username', None).strip() # Aa09_.- allowed
password = request.form.get('pa... | from flask import request, flash, render_template
import re
import bcrypt
from app import app, helpers
@app.route('/create_user', methods=['GET', 'POST'])
def create_user():
if request.method == 'POST':
username = request.form.get('username', None).strip() # Aa09_.- allowed
password = request.fo... | Add re import for regex | Add re import for regex
| Python | agpl-3.0 | kylemh/UO_CIS322,kylemh/UO_CIS322,kylemh/UO_CIS322 |
a7e22ba37a529ef8997cf252a715abd8dffaf763 | solutions/generalsolution.py | solutions/generalsolution.py | '''generalsolution.py
Holds the general solution base class
Created on 22 Apr 2010
@author: Ian Huston
'''
import numpy as np
class GeneralSolution(object):
"""General solution base class."""
def __init__(self, fixture, srcclass):
"""Create a GeneralSolution object."""
self.srceqns = sr... | '''generalsolution.py
Holds the general solution base class
Created on 22 Apr 2010
@author: Ian Huston
'''
import numpy as np
class GeneralSolution(object):
"""General solution base class."""
def __init__(self, fixture, srcclass):
"""Create a GeneralSolution object."""
self.srceqns = sr... | Remove unused functions from general solution. | Remove unused functions from general solution.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation |
191ce5f1918ec5a9652475d19d806c5ffc8f0f1b | djstripe/__init__.py | djstripe/__init__.py | """
dj-stripe - Django + Stripe Made Easy
"""
import pkg_resources
from django.apps import AppConfig
__version__ = pkg_resources.require("dj-stripe")[0].version
default_app_config = "djstripe.DjstripeAppConfig"
class DjstripeAppConfig(AppConfig):
"""
An AppConfig for dj-stripe which loads system checks
... | """
dj-stripe - Django + Stripe Made Easy
"""
import pkg_resources
from django.apps import AppConfig
__version__ = pkg_resources.get_distribution("dj-stripe").version
default_app_config = "djstripe.DjstripeAppConfig"
class DjstripeAppConfig(AppConfig):
"""
An AppConfig for dj-stripe which loads system check... | Use pkg_resources.get_distribution instead of .require for version | Use pkg_resources.get_distribution instead of .require for version
| Python | mit | dj-stripe/dj-stripe,pydanny/dj-stripe,pydanny/dj-stripe,dj-stripe/dj-stripe |
786903e417c7dfd8773db10fcc7cd5fa1130272a | candidates/tests/test_caching.py | candidates/tests/test_caching.py | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def test_unauth_user_cache_heade... | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def test_unauth_user_cache_heade... | Make a test of multiple header values insensitve to their order | Make a test of multiple header values insensitve to their order
This test sometimes failed on Python 3 because the values in the header
were ordered differently - splitting them and comparing as a set should
fix that.
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
17078f38c61fd012121aacb12683864592f31e79 | bqueryd/util.py | bqueryd/util.py | import netifaces
def get_my_ip():
eth_interfaces = [ifname for ifname in netifaces.interfaces() if ifname.startswith('eth')]
if len(eth_interfaces) < 1:
ifname = 'lo'
else:
ifname = eth_interfaces[0]
for x in netifaces.ifaddresses(ifname)[netifaces.AF_INET]:
# Return first addr ... | import netifaces
import zmq
import random
def get_my_ip():
eth_interfaces = [ifname for ifname in netifaces.interfaces() if ifname.startswith('eth')]
if len(eth_interfaces) < 1:
ifname = 'lo'
else:
ifname = eth_interfaces[0]
for x in netifaces.ifaddresses(ifname)[netifaces.AF_INET]:
... | Add binding to random port with identity | Add binding to random port with identity
| Python | bsd-3-clause | visualfabriq/bqueryd |
b73b8797c3c9c6c9aa92bd6873e15a5b717f4142 | test/test_nap.py | test/test_nap.py | """
Tests for nap module.
These tests only focus that requests is called properly.
Everything related to HTTP requests should be tested in requests' own tests.
"""
import unittest
import requests
from nap.api import Api
class TestNap(unittest.TestCase):
def test_unallowed_method(self):
"""Tries to use... | """
Tests for nap module.
These tests only focus that requests is called properly.
Everything related to HTTP requests should be tested in requests' own tests.
"""
from mock import MagicMock, patch
import unittest
import requests
from nap.api import Api
class TestNap(unittest.TestCase):
def test_unallowed_met... | Add tests which test default parameters for nap api | Add tests which test default parameters for nap api
| Python | mit | kimmobrunfeldt/nap |
30c875e1ba1dec3bcbd22850cd703198bcc5a1fb | peeringdb/migrations/0013_auto_20201207_2233.py | peeringdb/migrations/0013_auto_20201207_2233.py | # Generated by Django 3.1.3 on 2020-12-07 21:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("peeringdb", "0012_peerrecord_visible"),
]
def flush_peeringdb_tables(apps, schema_editor):
apps.get_model("peeringdb", "Contact").objects.all().dele... | # Generated by Django 3.1.3 on 2020-12-07 21:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("peeringdb", "0012_peerrecord_visible"),
]
def flush_peeringdb_tables(apps, schema_editor):
apps.get_model("peeringdb", "Contact").objects.all().dele... | Remove PeeringDB sync records on migrate | Remove PeeringDB sync records on migrate
| Python | apache-2.0 | respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager |
bfe49055d0e63e37041bf99ecfb36a5584c263c6 | sale_properties_easy_creation/mrp_property_formula.py | sale_properties_easy_creation/mrp_property_formula.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | Add compute_formula method to MrpPropertyFormula to use in modules which depending on it | Add compute_formula method to MrpPropertyFormula to use in modules which depending on it
| Python | agpl-3.0 | acsone/sale-workflow,thomaspaulb/sale-workflow,factorlibre/sale-workflow,Eficent/sale-workflow,diagramsoftware/sale-workflow,jabibi/sale-workflow,akretion/sale-workflow,brain-tec/sale-workflow,ddico/sale-workflow,acsone/sale-workflow,brain-tec/sale-workflow,open-synergy/sale-workflow,akretion/sale-workflow,fevxie/sale-... |
a8e8c8c33075c4e60467da4e1f8e05e35351b07f | url_shortener/default_config.py | url_shortener/default_config.py | # -*- coding: utf-8 -*-
''' Default configuration for the application
This data must be supplemented with custom configuration to which
URL_SHORTENER_CONFIGURATION environment variable points, overriding
some of the values specified here.
:var SQLALCHEMY_DATABASE_URI: uri of database to be used by the application.
T... | # -*- coding: utf-8 -*-
''' Default configuration for the application
This data must be supplemented with custom configuration to which
URL_SHORTENER_CONFIGURATION environment variable points, overriding
some of the values specified here.
:var SQLALCHEMY_DATABASE_URI: uri of database to be used by the application.
T... | Add configuration values for length of newly generated aliases | Add configuration values for length of newly generated aliases
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener |
c42e0974424d056e306e3f51e8345f2a9600b2dc | extract_language_package.py | extract_language_package.py | import optparse
import os
import glob
optparser = optparse.OptionParser()
optparser.add_option("-f", "--filename", dest="filename", help="Language package file")
optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder")
optparser.add_option("-l", "--language", dest="language", hel... | import optparse
import os
import glob
optparser = optparse.OptionParser()
optparser.add_option("-f", "--filename", dest="filename", help="Language package file")
optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder")
optparser.add_option("-l", "--language", dest="language", hel... | Update extract language package to use inner delete commands to reduce the amount of space used at any given point in time. | Update extract language package to use inner delete commands to reduce the
amount of space used at any given point in time.
| Python | mit | brendandc/multilingual-google-image-scraper |
fa518cdae22c1a762a593f3c4c67fadb04beb5e6 | corehq/apps/reports/standard/cases/case_list_explorer.py | corehq/apps/reports/standard/cases/case_list_explorer.py | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
class CaseListExplorer(CaseListReport):
name = _('Case List Explorer')
slug... | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from corehq.apps.es.case_search import CaseSearchES
from corehq.apps.reports.standard.cases.basic import CaseListReport
from corehq.apps.reports.standard.cases.filters import (
XpathCaseSearchFilter,
)... | Add XPath Query filter to report | Add XPath Query filter to report
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
0e807b46ba044e1accb8fb767f6f2ed4ffb2d0ba | dataportal/tests/test_broker.py | dataportal/tests/test_broker.py | import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '201... | import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..examples.sample_data import temperature_ramp
from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
swi... | Add coverage for basic broker usage. | TST: Add coverage for basic broker usage.
| Python | bsd-3-clause | danielballan/dataportal,ericdill/datamuxer,danielballan/dataportal,NSLS-II/dataportal,NSLS-II/datamuxer,ericdill/datamuxer,tacaswell/dataportal,ericdill/databroker,danielballan/datamuxer,tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,ericdill/databroker |
8857ab5642e49761cc65093132352071ec28dba2 | dataviva/utils/upload_helper.py | dataviva/utils/upload_helper.py | import boto3
from boto3.s3.transfer import S3Transfer
from config import AWS_ACCESS_KEY, AWS_SECRET_KEY
def delete_s3_file(file_id):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
return client.delete_object(
Bucket='d... | import boto3
from boto3.s3.transfer import S3Transfer
from config import AWS_ACCESS_KEY, AWS_SECRET_KEY
def delete_s3_file(file_id):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
return client.delete_object(
Bucket='d... | Fix s3 upload file extra_args named paramether | Fix s3 upload file extra_args named paramether
| Python | mit | DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site |
315a5c25429b3910446714238c28382ba727add8 | copywriting/urls.py | copywriting/urls.py | from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w+)/$', 'views.withTag'),
... | from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),... | Allow slugs in url patterns | Allow slugs in url patterns
| Python | mit | arteria/django-copywriting,arteria/django-copywriting |
82430e9ec30be2003293640867c14af306dc9ca5 | chmvh_website/gallery/management/commands/generatethumbnails.py | chmvh_website/gallery/management/commands/generatethumbnails.py | from django.core.management.base import BaseCommand
from gallery import models
from gallery.tasks import create_thumbnail
class Command(BaseCommand):
help = 'Generates thumbnails for gallery images without thumbnails'
def add_arguments(self, parser):
parser.add_argument(
'--overwrite',
... | from django.core.management.base import BaseCommand
from gallery import models
from gallery.tasks import create_thumbnail
class Command(BaseCommand):
help = 'Generates thumbnails for gallery images without thumbnails'
def add_arguments(self, parser):
parser.add_argument(
'--overwrite',
... | Fix error in thumbnail deletion. | Fix error in thumbnail deletion.
| Python | mit | cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website |
c6db8701986e8eb075b92916067e5904cd13fe9f | deploy/delete_stale_projects.py | deploy/delete_stale_projects.py | import shutil
import os
from projects.models import Project
slugs = [p.slug for p in Project.objects.all()]
build_projects = os.listdir('/home/docs/checkouts/readthedocs.org/user_builds/')
final = []
for slug in build_projects:
if slug not in slugs and slug.replace('_', '-') not in slugs:
final.append(sl... | import shutil
import os
from readthedocs.projects.models import Project
slugs = [p.slug for p in Project.objects.all()]
build_projects = os.listdir('/home/docs/checkouts/readthedocs.org/user_builds/')
final = []
for slug in build_projects:
if slug not in slugs and slug.replace('_', '-') not in slugs:
fin... | Add rtd import to master | Add rtd import to master
| Python | mit | safwanrahman/readthedocs.org,istresearch/readthedocs.org,tddv/readthedocs.org,pombredanne/readthedocs.org,espdev/readthedocs.org,safwanrahman/readthedocs.org,rtfd/readthedocs.org,espdev/readthedocs.org,safwanrahman/readthedocs.org,espdev/readthedocs.org,tddv/readthedocs.org,davidfischer/readthedocs.org,istresearch/read... |
c1dc3c503d09e95321fc6f3fe3d7ab114ff58fc9 | patty/segmentation/pointCloudMeasurer.py | patty/segmentation/pointCloudMeasurer.py | import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
pca.fit(np.asarray(pointCloud))
primary_axis = np... | import numpy as np
from sklearn.decomposition import PCA
def measureLength(pointCloud):
"""Returns the length of a point cloud in its longest direction."""
if len(pointCloud) == 0:
return 0
pca = PCA(n_components = 1)
pc_array = np.asarray(pointCloud)
pca.fit(pc_arra... | Make sure np.array is used for PCA in measureLength | Make sure np.array is used for PCA in measureLength
| Python | apache-2.0 | NLeSC/PattyAnalytics |
42f21057388361e50416197b25be9dfbdb2764b0 | any_imagefield/forms/widgets.py | any_imagefield/forms/widgets.py | import mimetypes
from django.contrib.admin.widgets import AdminFileWidget
from django.template.loader import render_to_string
class ImagePreviewWidget(AdminFileWidget):
"""
An :class:`~django.forms.FileInput` widget that also displays a preview of the image.
"""
template_with_initial = u'%(clear_templ... | import mimetypes
from django.contrib.admin.widgets import AdminFileWidget
from django.template.loader import render_to_string
class ImagePreviewWidget(AdminFileWidget):
"""
An :class:`~django.forms.FileInput` widget that also displays a preview of the image.
"""
template_with_initial = u'%(clear_templ... | Fix render() kwargs for Django 2.1 | Fix render() kwargs for Django 2.1
| Python | apache-2.0 | edoburu/django-any-imagefield,edoburu/django-any-imagefield |
8a309491f6370814f88d8be7e5b7c697c4b59dcd | great_expectations/__init__.py | great_expectations/__init__.py | import pandas as pd
from util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_datase... | import pandas as pd
from .util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_datas... | Change import util to .util to support python 3 | Change import util to .util to support python 3
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.