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 |
|---|---|---|---|---|---|---|---|---|---|
ee31e6c0302c6840d522666b1f724d0ec429d562 | monasca_setup/detection/plugins/neutron.py | monasca_setup/detection/plugins/neutron.py | import monasca_setup.detection
class Neutron(monasca_setup.detection.ServicePlugin):
"""Detect Neutron daemons and setup configuration to monitor them.
"""
def __init__(self, template_dir, overwrite=True, args=None):
service_params = {
'args': args,
'template_dir': templ... | import monasca_setup.detection
class Neutron(monasca_setup.detection.ServicePlugin):
"""Detect Neutron daemons and setup configuration to monitor them.
"""
def __init__(self, template_dir, overwrite=True, args=None):
service_params = {
'args': args,
'template_dir': templ... | Add process monitoring for LBaaS agents | Add process monitoring for LBaaS agents
Add neutron-lbaas-agent (LBaaS V1) and neutron-lbaasv2-agent (LBaaS
V2) to the neutron detection plugin. Because the string
"neutron-lbaas-agent" can be both a process name and log file name,
the process monitor is susceptible to false positive matching on that
string. Use a lo... | Python | bsd-3-clause | sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent |
8769224d8dbe73e177d19012d54c9bb7e114a3fa | recipes/webrtc.py | recipes/webrtc.py | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import recipe_util # pylint: disable=F0401
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=W0232... | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import recipe_util # pylint: disable=F0401
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=W0232... | Switch WebRTC recipe to Git. | Switch WebRTC recipe to Git.
BUG=412012
Review URL: https://codereview.chromium.org/765373002
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@294546 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | sarvex/depot-tools,fracting/depot_tools,sarvex/depot-tools,azunite/chrome_build,disigma/depot_tools,duongbaoduy/gtools,fracting/depot_tools,hsharsha/depot_tools,Midrya/chromium,hsharsha/depot_tools,ajohnson23/depot_tools,gcodetogit/depot_tools,npe9/depot_tools,mlufei/depot_tools,primiano/depot_tools,chinmaygarde/depot_... |
2393b066fbb0fc88d9e9a1918485cf57c40aecc2 | opps/articles/templatetags/article_tags.py | opps/articles/templatetags/article_tags.py | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = slug + '-' + channel_slug
try:... | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = s... | Add validate published on templatetag get articlebox | Add validate published on templatetag get articlebox
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps |
109fc84cb307083f6a01317bb5b5bea0578088d3 | bloop/__init__.py | bloop/__init__.py | from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation
from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex
from bloop.types import (
String, Float, Integer, Binary, StringSet, FloatSet,
IntegerSet, BinarySet, Null, Boolean, Map, List
)
__all__ = [
"Engine", "ObjectsNot... | from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation
from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex
from bloop.types import (
String, UUID, Float, Integer, Binary, StringSet, FloatSet,
IntegerSet, BinarySet, Null, Boolean, Map, List
)
__all__ = [
"Engine", "Obje... | Add UUID to bloop __all__ | Add UUID to bloop __all__ | Python | mit | numberoverzero/bloop,numberoverzero/bloop |
6c32e39e2e51a80ebc9e31e88e22cc4aa39f7466 | chainer/functions/copy.py | chainer/functions/copy.py | from chainer import cuda
from chainer import function
class Copy(function.Function):
"""Copy an input GPUArray onto another device."""
def __init__(self, out_device):
self.out_device = out_device
def forward_cpu(self, x):
return x[0].copy(),
def forward_gpu(self, x):
return... | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class Copy(function.Function):
"""Copy an input GPUArray onto another device."""
def __init__(self, out_device):
self.out_device = out_device
def check_type_forward(self, in_types):
... | Add unittest(cpu-only) and typecheck for Copy | Add unittest(cpu-only) and typecheck for Copy
| Python | mit | chainer/chainer,sinhrks/chainer,ronekko/chainer,ktnyt/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,tkerola/chainer,elviswf/chainer,tscohen/chainer,muupan/chainer,keisuke-umezawa/chainer,Kaisuke5/chainer,woodshop/chainer,jnishi/chainer,keisuke-umezawa/chainer,tigerneil/chainer,cupy/cupy,niboshi/chainer,chainer... |
f01222f021f277805492e3f539609f6b64be0b7e | blanc_basic_news/news/views.py | blanc_basic_news/news/views.py | from django.views.generic import ListView, DateDetailView
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.conf import settings
from .models import Category, Post
class PostListView(ListView):
paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10)
def get_queryset(se... | from django.views.generic import ListView, DateDetailView
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.conf import settings
from .models import Category, Post
class PostListView(ListView):
paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10)
def get_queryset(se... | Use select_related to help with category foreign keys | Use select_related to help with category foreign keys
| Python | bsd-3-clause | blancltd/blanc-basic-news |
c5f10b2e5ea10dd17c8c19f87dcdfd2584f8e431 | comics/accounts/models.py | comics/accounts/models.py | import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
UserProfile.objects.get_or_create(user=instance)
class UserProfile(models.Mode... | import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
class UserProfile... | Remove conditional sql-select on new user creation | Remove conditional sql-select on new user creation
Only create a user profile if a new user is actually
created.
| Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics |
fd6c7386cfdaa5fb97a428b323fc1f9b17f9f02c | tests/test_helpers.py | tests/test_helpers.py | import pandas
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
def test_pretty_print():
some_stuff = '{"Dusty": "Rhodes"}'
pretty_print(some_stuff)
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
| import vcr
import pandas
import pytest
from sharepa.search import ShareSearch
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
@vcr.use_cassette('tests/vcr/simple_execute.yaml')
def test_pretty_print():
my_search = ShareSearch()
result = my_search.execute()
the_dict = re... | Add pytest fail check on raising pretty print exeption | Add pytest fail check on raising pretty print exeption
| Python | mit | CenterForOpenScience/sharepa,fabianvf/sharepa,samanehsan/sharepa,erinspace/sharepa |
0a9e3fb387c61f2c7cb32502f5c50eaa5b950169 | tests/test_process.py | tests/test_process.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py ... | Fix intermittent travis build error. | Fix intermittent travis build error.
| Python | mit | wamonite/packermate |
e79c90db5dcda56ff9b2b154659984db9c6f7663 | src/main.py | src/main.py | # -*- encoding: utf-8 -*-
import pygame
from scenes import director
from scenes import intro_scene
pygame.init()
def main():
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene)
game_director.loop()
if __name__ == '__main__':
pygam... | # -*- encoding: utf-8 -*-
import pygame
from scenes import director
from scenes import intro_scene
from game_logic import settings
pygame.init()
def main():
initial_settings = settings.Settings(
trials=1000, player='O', oponent='Computer')
game_director = director.Director()
scene = intro_scene.... | Create initial config when starting game | Create initial config when starting game
| Python | mit | juangallostra/TicTacToe |
7dd228d7eaad6b1f37ff3c4d954aebe0ffa99170 | tests/test_targets/test_targets.py | tests/test_targets/test_targets.py | # Copyright 2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | # Copyright 2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Test - targets test fix mcu validity indexes | Test - targets test fix mcu validity indexes
| Python | apache-2.0 | project-generator/project_generator_definitions,0xc0170/project_generator_definitions,ohagendorf/project_generator_definitions |
bd2c0efa6b0205ff0d24cf335f65f755f18566f2 | modernrpc/__init__.py | modernrpc/__init__.py | # coding: utf-8
# default_app_config was deprecated in Django 3.2. Maybe set it only when detected django version is older?
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
# import pkg_resources; version = pkg_resources.get_d... | # coding: utf-8
from packaging.version import Version
import django
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
if Version(django.get_version()) < Version("3.2"):
default_app_c... | Stop defining default_app_config on Django 3.2+ | Stop defining default_app_config on Django 3.2+ | Python | mit | alorence/django-modern-rpc,alorence/django-modern-rpc |
bc5d678937e69fe00e206b6a80c9a2f6dfb1a3a2 | examples/worker_rush.py | examples/worker_rush.py | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
async def on_step(self, state, iteration):
if iteration == 0:
for probe in self.workers:
await self.do(probe.attack(self.enemy_start_locations[0]))
d... | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
async def on_step(self, state, iteration):
if iteration == 0:
for worker in self.workers:
await self.do(worker.attack(self.enemy_start_locations[0]))
... | Use generic names in the worker rush example | Use generic names in the worker rush example
| Python | mit | Dentosal/python-sc2 |
a6a2ee870840730f99ad475e02956c49fe2e7ed3 | common/authapp.py | common/authapp.py | import ConfigParser
from common.application import Application
from keystonemiddleware.auth_token import filter_factory as auth_filter_factory
class KeystoneApplication(Application):
"""
An Application which uses Keystone for authorisation using RBAC
"""
def __init__(self, configuration):
sup... | import ConfigParser
from common.application import Application
from keystonemiddleware.auth_token import filter_factory as auth_filter_factory
class KeystoneApplication(Application):
"""
An Application which uses Keystone for authorisation using RBAC
"""
INI_SECTION = 'keystone_authtoken'
def __... | Remove hardcoded default filename. Raise an error if no app config file was specified, or it is unreadable, or it doesn't contain the section we need. | Remove hardcoded default filename. Raise an error if no app config file was specified, or it is unreadable, or it doesn't contain the section we need.
| Python | apache-2.0 | NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api |
66462c231011f6418fc246789ce4feed10a74a66 | web/whim/core/time.py | web/whim/core/time.py | from datetime import datetime, timezone, time
def zero_time_with_timezone(date, tz=timezone.utc):
return datetime.combine(date, time(tzinfo=tz)) | from datetime import datetime, timezone, time
import dateparser
def zero_time_with_timezone(date, tz=timezone.utc):
return datetime.combine(date, time(tzinfo=tz))
def attempt_parse_date(val):
parsed_date = dateparser.parse(val, languages=['en'])
if parsed_date is None:
# try other strategies?
... | Use dateparser for parsing scraped dates | Use dateparser for parsing scraped dates
| Python | mit | andrewgleave/whim,andrewgleave/whim,andrewgleave/whim |
57a37c4a87e9757a109dfb5f3169fb8264d0795e | neutron/server/rpc_eventlet.py | neutron/server/rpc_eventlet.py | #!/usr/bin/env python
# Copyright 2011 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | #!/usr/bin/env python
# Copyright 2011 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | Switch to start_all_workers in RPC server | Switch to start_all_workers in RPC server
This does the same as the logic present but it emits
the registry callback event for resources.PROCESS AFTER_SPAWN
that some plugins may be expecting.
Change-Id: I6f9aeca753a5d3c0052f553a2ac46786ca113e1e
Related-Bug: #1687896
| Python | apache-2.0 | mahak/neutron,noironetworks/neutron,openstack/neutron,openstack/neutron,openstack/neutron,eayunstack/neutron,mahak/neutron,huntxu/neutron,eayunstack/neutron,noironetworks/neutron,huntxu/neutron,mahak/neutron |
bc961992afeae978e95209606e0e7b1a9b73719f | jesusmtnez/python/kata/game.py | jesusmtnez/python/kata/game.py | class Game():
def __init__(self):
self._score = 0
def roll(self, pins):
pass
def score(self):
return 0
| class Game():
def __init__(self):
self._score = 0
def roll(self, pins):
self._score += pins
def score(self):
return self._score
| Update score in Game class methods | [Python] Update score in Game class methods
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
69c72d47ebf57932b6e20e2c22a5f1c84d07d3eb | pyqode/core/api/__init__.py | pyqode/core/api/__init__.py | """
This package contains the bases classes of pyqode and some utility
functions.
"""
from .code_edit import CodeEdit
from .decoration import TextDecoration
from .encodings import ENCODINGS_MAP, convert_to_codec_key
from .manager import Manager
from .mode import Mode
from .panel import Panel
from .syntax_highlighter i... | """
This package contains the bases classes of pyqode and some utility
functions.
"""
from .code_edit import CodeEdit
from .decoration import TextDecoration
from .encodings import ENCODINGS_MAP, convert_to_codec_key
from .manager import Manager
from .mode import Mode
from .panel import Panel
from .syntax_highlighter i... | Add missing PYGMENTS_STYLES list to pyqode.core.api | Add missing PYGMENTS_STYLES list to pyqode.core.api
| Python | mit | zwadar/pyqode.core,pyQode/pyqode.core,pyQode/pyqode.core |
23d8942ffeeee72e21330bd8ecc5bfb5e91bbc3b | certidude/push.py | certidude/push.py |
import click
import json
import logging
import requests
from datetime import datetime
from certidude import config
def publish(event_type, event_data):
"""
Publish event on push server
"""
if not isinstance(event_data, basestring):
from certidude.decorators import MyEncoder
event_data... |
import click
import json
import logging
import requests
from datetime import datetime
from certidude import config
def publish(event_type, event_data):
"""
Publish event on push server
"""
if not config.PUSH_PUBLISH:
# Push server disabled
return
if not isinstance(event_data, bas... | Add fallbacks for e-mail handling if outbox is not defined | Add fallbacks for e-mail handling if outbox is not defined
| Python | mit | laurivosandi/certidude,laurivosandi/certidude,plaes/certidude,laurivosandi/certidude,plaes/certidude,plaes/certidude,laurivosandi/certidude,plaes/certidude |
e7e8972124d3336834f1c177f655e12528a49624 | cosmo/monitors/osm_data_models.py | cosmo/monitors/osm_data_models.py | import pandas as pd
from monitorframe.monitor import BaseDataModel
from cosmo.filesystem import FileDataFinder
from cosmo import FILES_SOURCE
from cosmo.monitor_helpers import explode_df
class OSMDataModel(BaseDataModel):
def get_data(self):
header_keys = (
'ROOTNAME', 'EXPSTART', 'DETECTOR... | import pandas as pd
from monitorframe.monitor import BaseDataModel
from cosmo.filesystem import FileDataFinder
from cosmo import FILES_SOURCE
from cosmo.monitor_helpers import explode_df
class OSMDataModel(BaseDataModel):
"""Data model for all OSM Shift monitors."""
def get_data(self):
header_keys ... | Add comments and docstring to OSMDataModel | Add comments and docstring to OSMDataModel
| Python | bsd-3-clause | justincely/cos_monitoring |
3e67993eb17aca7571381d59b7fd65eab53dac98 | day19/part2.py | day19/part2.py | inp = 3004953
elves = list(range(1, inp + 1))
i = 0
while len(elves) > 1:
index = (i + int(len(elves) / 2)) % len(elves)
elves.pop(index)
if index < i:
i -= 1
i = (i + 1) % len(elves)
print(elves[0])
input()
| inp = 3004953
class Elf:
def __init__(self, num):
self.num = num
self.prev = None
self.next = None
def remove(self):
self.prev.next = self.next
self.next.prev = self.prev
elves = list(map(Elf, range(1, inp + 1)))
for i in range(inp):
elves[i].prev = elves[(i - 1) %... | Replace list with a linked list for much better performance | Replace list with a linked list for much better performance
| Python | unlicense | ultramega/adventofcode2016 |
561d98e59ea46b56d50341e06578b5c9fe95c73a | perfbucket/watcher.py | perfbucket/watcher.py | import os
import sys
import pyinotify
import analyzer
wm = pyinotify.WatchManager()
class ProcessProfilerEvent(pyinotify.ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
if event.name.endswith(".json"):
base = os.path.splitext(os.path.join(event.path, event.name))[0]
analyze... | import os
import sys
import pyinotify
import analyzer
class ProcessProfilerEvent(pyinotify.ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
if event.name.endswith(".json"):
base = os.path.splitext(os.path.join(event.path, event.name))[0]
analyzer.analyze_profiling_result(base... | Change scope of watch manager. | Change scope of watch manager.
| Python | agpl-3.0 | davidstrauss/perfbucket,davidstrauss/perfbucket,davidstrauss/perfbucket |
2497f494f0e3e7fb57aa8cb1deed0c05fd6b74b1 | handler/FilesService.py | handler/FilesService.py | import tornado
import time
from bson.json_util import dumps
from tornado.options import options
class FilesServiceHandler(tornado.web.RequestHandler):
def initialize(self, logger, mongodb):
self.logger = logger
self.mongodb = mongodb
@tornado.web.asynchronous
@tornado.gen.coroutine
de... | import tornado
import time
from bson.json_util import dumps
from tornado.options import options
class FilesServiceHandler(tornado.web.RequestHandler):
def initialize(self, logger, mongodb):
self.logger = logger
self.mongodb = mongodb[options.db_name]['Files']
@tornado.web.asynchronous
@to... | Save file info in DB | Save file info in DB
| Python | apache-2.0 | jiss-software/jiss-file-service,jiss-software/jiss-file-service,jiss-software/jiss-file-service |
996713fc6aefe20b28c729c46532ae566d5160a1 | paratemp/sim_setup/__init__.py | paratemp/sim_setup/__init__.py | """This module has functions and classes useful for setting up simulations"""
########################################################################
# #
# This test was written by Thomas Heavey in 2019. #
# theavey@bu.ed... | """This module has functions and classes useful for setting up simulations"""
########################################################################
# #
# This test was written by Thomas Heavey in 2019. #
# theavey@bu.ed... | Fix import order (some somewhat cyclic dependencies; should fix) | Fix import order (some somewhat cyclic dependencies; should fix)
| Python | apache-2.0 | theavey/ParaTemp,theavey/ParaTemp |
d787039a58d63cd85068da996a12fc36c1d63804 | ixxy_admin_utils/admin_actions.py | ixxy_admin_utils/admin_actions.py | def xlsx_export_action(modeladmin, request, queryset):
from django.http import HttpResponse
from import_export.formats import base_formats
formats = modeladmin.get_export_formats()
file_format = base_formats.XLSX()
export_data = modeladmin.get_export_data(file_format, queryset, request=request)
... | from django.http import HttpResponse
from import_export.formats import base_formats
def xlsx_export_action(modeladmin, request, queryset):
formats = modeladmin.get_export_formats()
file_format = base_formats.XLSX()
export_data = modeladmin.get_export_data(file_format, queryset, request=request)
cont... | Undo previous commit. It didn't work. | Undo previous commit. It didn't work.
| Python | mit | DjangoAdminHackers/ixxy-admin-utils,DjangoAdminHackers/ixxy-admin-utils |
7dfe4381ecd252530cb7dc274b2dc6aaa39f81cc | deps/pyextensibletype/extensibletype/test/test_interning.py | deps/pyextensibletype/extensibletype/test/test_interning.py | from .. import intern
def test_global_interning():
try:
intern.global_intern("hello")
except AssertionError as e:
pass
else:
raise Exception("Expects complaint about uninitialized table")
intern.global_intern_initialize()
id1 = intern.global_intern("hello")
id2 = intern... | from .. import intern
def test_global_interning():
# Can't really test for this with nose...
# try:
# intern.global_intern("hello")
# except AssertionError as e:
# pass
# else:
# raise Exception("Expects complaint about uninitialized table")
intern.global_intern_initialize(... | Disable global intern exception test | Disable global intern exception test
| Python | bsd-2-clause | stuartarchibald/numba,pitrou/numba,pitrou/numba,shiquanwang/numba,seibert/numba,jriehl/numba,shiquanwang/numba,stefanseefeld/numba,stuartarchibald/numba,cpcloud/numba,cpcloud/numba,gdementen/numba,seibert/numba,numba/numba,sklam/numba,ssarangi/numba,gmarkall/numba,cpcloud/numba,sklam/numba,pitrou/numba,IntelLabs/numba,... |
5bece700c7ebbb2c9ea3ce2781863baf189e2fc0 | cybox/test/objects/__init__.py | cybox/test/objects/__init__.py | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox.utils
class ObjectTestCase(object):
"""A base class for testing all subclasses of ObjectProperties.
Each subclass of ObjectTestCase should subclass both unittest.TestCase
and ObjectTestCa... | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox.test
import cybox.utils
class ObjectTestCase(object):
"""A base class for testing all subclasses of ObjectProperties.
Each subclass of ObjectTestCase should subclass both unittest.TestCase
... | Add (failing) test of object_reference on all ObjectProperties subclasses | Add (failing) test of object_reference on all ObjectProperties subclasses
| Python | bsd-3-clause | CybOXProject/python-cybox |
a354a4f52bce3c3063678b046ba76a694c076652 | web/celSearch/api/scripts/query_wikipedia.py | web/celSearch/api/scripts/query_wikipedia.py | '''
Script used to query Wikipedia for summary of object
'''
import sys
import wikipedia
def main():
# Check that we have the right number of arguments
if (len(sys.argv) != 2):
print 'Incorrect number of arguments; please pass in only one string that contains the subject'
return 'Banana'
print wikipedia... | '''
Script used to query Wikipedia for summary of object
'''
import sys
import wikipedia
import nltk
def main():
# Check that we have the right number of arguments
if (len(sys.argv) != 2):
print 'Incorrect number of arguments; please pass in only one string that contains the query'
return 'Banana'
# Ge... | Add nltk part to script | Add nltk part to script
| Python | apache-2.0 | christopher18/Celsearch,christopher18/Celsearch,christopher18/Celsearch |
2a7ce1ac70f8767e9d2b2a9f1d335cfcc63a92b6 | rplugin/python3/LanguageClient/logger.py | rplugin/python3/LanguageClient/logger.py | import logging
import tempfile
logger = logging.getLogger("LanguageClient")
with tempfile.NamedTemporaryFile(
prefix="LanguageClient-",
suffix=".log", delete=False) as tmp:
tmpname = tmp.name
fileHandler = logging.FileHandler(filename=tmpname)
fileHandler.setFormatter(
logging.Formatter(
... | import logging
logger = logging.getLogger("LanguageClient")
fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S"))
logger.addHandler(fileHandler)
logger.setLevel(logging.WARN)
| Revert "Use tempfile lib for log file" | Revert "Use tempfile lib for log file"
This reverts commit 6e8f35b83fc563c8349cb3be040c61a0588ca745.
The commit caused severer issue than it fixed. In case one need to check
the content of log file, there is no way to tell where the log file
location/name is.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... |
21a392df73324f111fa80e2fd8ce88b0e32c954c | python/algorithms/fibonacci.py | python/algorithms/fibonacci.py | def fib1(amount):
"""
Fibonacci generator example. The second variable is used to store
the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib1(3))
[0, 1, 1]
>>> list(fib1(9))
[0, 1, 1, 2, ... | """Implementations calculation of Fibonacci numbers."""
def fib1(amount):
"""
Calculate Fibonacci numbers.
The second variable is used to store the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib... | Adjust doc strings in Fibonacci numbers implementation | Adjust doc strings in Fibonacci numbers implementation
| Python | mit | pesh1983/exercises,pesh1983/exercises |
9c1190133a680717850a4d0f46a96591b7be4e33 | autoencoder/api.py | autoencoder/api.py | from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None, reduced=False,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=... | from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None, reduced=False,
mask=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, ma... | Change mask parameter in API. | Change mask parameter in API.
| Python | apache-2.0 | theislab/dca,theislab/dca,theislab/dca |
8d7e4cf37e73c1ff9827e94a06327921f553e2f4 | learntools/computer_vision/ex4.py | learntools/computer_vision/ex4.py | from learntools.core import *
import tensorflow as tf
class Q1A(ThoughtExperiment):
_solution = ""
class Q1B(ThoughtExperiment):
_solution = ""
Q1 = MultipartProblem(Q1A, Q1B)
class Q2A(ThoughtExperiment):
_hint = r"Stacking the second layer expanded the receptive field by one neuron on each side, giv... | from learntools.core import *
import tensorflow as tf
# Free
class Q1(CodingProblem):
_solution = ""
def check(self):
pass
class Q2A(ThoughtExperiment):
_hint = r"Stacking the second layer expanded the receptive field by one neuron on each side, giving $3+1+1=5$ for each dimension. If you expande... | Change exercise 4 question 1 | Change exercise 4 question 1
| Python | apache-2.0 | Kaggle/learntools,Kaggle/learntools |
2ee895c61f546f83f4b7fa0c6a2ba72578c378be | problem_2/solution.py | problem_2/solution.py | f1, f2, s, n = 0, 1, 0, 4000000
while f2 < n:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
print s
| def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
... | Add a second Python implementation of problem 2 | Add a second Python implementation of problem 2
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler |
5523ae2278bb0ca055ef7a6e218ac40ed4172bf3 | webapp/byceps/blueprints/ticket/service.py | webapp/byceps/blueprints/ticket/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
"""
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""Return the ticket used by the... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""R... | Save a few SQL queries. | Save a few SQL queries.
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps |
7dc08364cbe513ce4b81483d9330789f5893fcee | Challenges/chall_03.py | Challenges/chall_03.py | #!/usr/local/bin/python3
# Python challenge - 3
# http://www.pythonchallenge.com/pc/def/equality.html
import re
'''
Hint:
One small letter surrounded by EXACTLY three big bodyguards on each of
its sides.
'''
def main():
with open('bodyguard.txt', 'r') as bodyguard:
pattern = re.compile(r'[^A-Z][A-Z]{3}... | #!/usr/local/bin/python3
# Python challenge - 3
# http://www.pythonchallenge.com/pc/def/equality.html
# Keyword: linkedlist
import re
def main():
'''
Hint:
One small letter surrounded by EXACTLY three big bodyguards on each of
its sides.
Page source text saved in bodyguard.txt
'''
with op... | Refactor code, add hints from page | Refactor code, add hints from page
| Python | mit | HKuz/PythonChallenge |
da85d9660166f67133b10953104ccd81b89d0b92 | micawber/cache.py | micawber/cache.py | from __future__ import with_statement
import os
import pickle
from contextlib import closing
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
... | from __future__ import with_statement
import os
import pickle
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
self._cache[k] = v
clas... | Remove a redundant use of contextlib.closing() decorator | Remove a redundant use of contextlib.closing() decorator
Remove the unnecessary contextlib.closing() decorators from open()
calls. The file objects returned by open() provide context manager API
themselves and closing() is only necessary for external file-like
objects that do not support it.
This should work even in... | Python | mit | coleifer/micawber,coleifer/micawber |
2c7dc769874766b230bc11c7ec6f67d3c1157005 | duplicatefiledir/__init__.py | duplicatefiledir/__init__.py | from fman import DirectoryPaneCommand, show_alert
import distutils
from distutils import dir_util, file_util
import os.path
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(selected_files) =... | from fman import DirectoryPaneCommand, show_alert
from urllib.parse import urlparse
import os.path
from shutil import copytree, copyfile
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(sele... | Make it work with last fman version (0.7) on linux | Make it work with last fman version (0.7) on linux
| Python | mit | raguay/DuplicateFileDir |
2f80f786be8e0d235dcb98c4fa562bfe2b9e783f | jobs/spiders/visir.py | jobs/spiders/visir.py | import dateutil.parser
import scrapy
from jobs.items import JobsItem
class VisirSpider(scrapy.Spider):
name = "visir"
start_urls = ['https://job.visir.is/search-results-jobs/']
def parse(self, response):
for job in response.css('.thebox'):
info = job.css('a')[1]
item = J... | import dateutil.parser
import scrapy
from jobs.items import JobsItem
class VisirSpider(scrapy.Spider):
name = "visir"
start_urls = ['https://job.visir.is/search-results-jobs/']
def parse(self, response):
for job in response.css('.thebox'):
info = job.css('a')[1]
item = J... | Fix parsing of dates for Visir. | Fix parsing of dates for Visir.
Some dates are being wrongly parsed, so we need to specify some information about the order of things.
| Python | apache-2.0 | multiplechoice/workplace |
a24d6a25cb7ee5101e8131a9719744f79b23c11b | examples/quotes/quotes.py | examples/quotes/quotes.py | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
my_address = nw0.a... | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
my_address = nw0.a... | Send notification to the correct address | Send notification to the correct address
| Python | mit | tjguk/networkzero,tjguk/networkzero,tjguk/networkzero |
723ae54f260284aad442f076772189cb5820d62e | devtools/ci/push-docs-to-s3.py | devtools/ci/push-docs-to-s3.py | import os
import pip
import tempfile
import subprocess
import opentis.version
BUCKET_NAME = 'openpathsampling.org'
if not opentis.version.release:
PREFIX = 'latest'
else:
PREFIX = opentis.version.short_version
PREFIX = ''
if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()):
... | import os
import pip
import tempfile
import subprocess
import opentis.version
BUCKET_NAME = 'openpathsampling.org'
if not opentis.version.release:
PREFIX = 'latest'
else:
PREFIX = opentis.version.short_version
PREFIX = ''
if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()):
... | Fix for PREFIX omission in S3 push | Fix for PREFIX omission in S3 push
| Python | mit | dwhswenson/openpathsampling,jhprinz/openpathsampling,choderalab/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,jhprinz/openpathsampling,openpathsampling/openpathsampling,openpathsampling/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsam... |
eb391dde8a157252a98fc9bb9b617bc821f7285a | email_from_template/utils.py | email_from_template/utils.py | from django.utils.functional import memoize
from . import app_settings
def get_render_method():
return from_dotted_path(app_settings.EMAIL_RENDER_METHOD)
get_render_method = memoize(get_render_method, {}, 0)
def get_context_processors():
return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESS... | from django.utils.lru_cache import lru_cache
from . import app_settings
@lru_cache
def get_render_method():
return from_dotted_path(app_settings.EMAIL_RENDER_METHOD)
@lru_cache
def get_context_processors():
return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESSORS]
def from_dotted_path(full... | Use @lru_cache now that memoize is gone. | Use @lru_cache now that memoize is gone.
| Python | bsd-3-clause | lamby/django-email-from-template |
75af7171d0245b528018c8e0d0d581916a9dc67d | examples/profilealignment.py | examples/profilealignment.py | # Create sequences to be aligned.
from alignment.sequence import Sequence
a = Sequence("what a beautiful day".split())
b = Sequence("what a disappointingly bad day".split())
print "Sequence A:", a
print "Sequence B:", b
print
# Create a vocabulary and encode the sequences.
from alignment.vocabulary import Vocabulary
v... | from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner
from alignment.profile import Profile
from alignment.profilealigner import SoftScoring, GlobalProfileAligner
# Create sequences to be aligned.
a = Sequence('wh... | Update the profile alignment example. | Update the profile alignment example.
| Python | bsd-3-clause | eseraygun/python-entities,eseraygun/python-alignment |
4bef46ef98591d47d653eeb4f74bf00a8a1d5d69 | correios/utils.py | correios/utils.py | from itertools import chain
from typing import Sized, Iterable, Container, Set
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
r = [r]
elif isinstance(r, RangeSet):
... | from itertools import chain
from typing import Container, Iterable, Sized
class RangeSet(Sized, Iterable, Container):
def __init__(self, *ranges):
self.ranges = []
for r in ranges:
if isinstance(r, range):
self.ranges.append(r)
continue
try... | Use duck typing when creating a RangeSet | Use duck typing when creating a RangeSet
| Python | apache-2.0 | osantana/correios,solidarium/correios,olist/correios |
3fbbdec51cfd93217705adcae37b1bf22d5661fa | backend/playlist/serializers.py | backend/playlist/serializers.py | from rest_framework import serializers
from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry
class TrackSerializer(serializers.ModelSerializer):
album = serializers.StringRelatedField(
read_only=True
)
class Meta:
model = Cdtrack
fields = ('trackid', 'url', 'tracknum', 't... | from rest_framework import serializers
from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry
class TrackSerializer(serializers.ModelSerializer):
album = serializers.StringRelatedField(
read_only=True
)
class Meta:
model = Cdtrack
fields = ('trackid', 'url', 'tracknum', 't... | Add showname to playlist API view. | Add showname to playlist API view.
* Even though it's obsolete now, we need it for old shows.
| Python | mit | ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists |
56aa0448fb3cd1df1a0fd43abc9a0e37e8ddf55b | trans_sync/management/commands/save_trans.py | trans_sync/management/commands/save_trans.py | # coding: utf-8
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option(
'--dry-run',
action='store_true',
dest... | # coding: utf-8
from __future__ import unicode_literals
import os
from os.path import join, isdir
from optparse import make_option
from django.core.management.base import NoArgsCommand
from django.conf import settings
from modeltranslation.translator import translator
from babel.messages.catalog import Catalog
from ba... | Save trans to .po files | Save trans to .po files
| Python | mit | djentlemen/django-modeltranslation-sync |
e2495040277fafdac4c0e060517cf667baa27c02 | chinup/__init__.py | chinup/__init__.py | try:
from .allauth import *
except ImportError:
from .chinup import *
from .exceptions import *
__version__ = '0.1'
| from __future__ import absolute_import, unicode_literals
try:
from .allauth import *
except ImportError:
from .chinup import *
from .exceptions import *
__version__ = '0.1'
# Configure logging to avoid warning.
# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library
import logging... | Configure package-level logging to avoid warning. | Configure package-level logging to avoid warning.
| Python | mit | pagepart/chinup |
fc36b9bc2970c611a4fb5063463f27cfd96df21d | moksha/hub/messaging.py | moksha/hub/messaging.py | # This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | # This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Update our MessagingHub.subscribe method arguments | Update our MessagingHub.subscribe method arguments
| Python | apache-2.0 | ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,lmacken/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,pombredanne/moksha,lmacken/moksha |
a7fcc89755e01bf3dbe7090e2bf7f1211ce9af84 | test/test_property.py | test/test_property.py | import unittest
from odml import Property, Section, Document
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
def test_name(self):
pass
def test_parent(self):
pass
... | import unittest
from odml import Property, Section, Document
from odml.doc import BaseDocument
from odml.section import BaseSection
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
self.assertEqual(p.value[0], 100)
... | Add tests to cover update parent functionality. | Add tests to cover update parent functionality.
| Python | bsd-3-clause | lzehl/python-odml |
bee93012144e033b02c05a1e586620dfa7f4c883 | words/models.py | words/models.py | from django.db import models
class Word(models.Model):
word = models.CharField(max_length=255)
date_retired = models.DateTimeField(null=True, blank=True)
date_active = models.DateTimeField(null=True, blank=True)
views = models.IntegerField(default=0)
@property
def is_active(self):
if ... | from django.db import models
class Word(models.Model):
word = models.CharField(max_length=255)
date_retired = models.DateTimeField(null=True, blank=True)
date_active = models.DateTimeField(null=True, blank=True)
views = models.IntegerField(default=0)
@property
def is_active(self):
if ... | Make the word display nice | Make the word display nice
| Python | bsd-2-clause | kylegibson/how_to_teach_your_baby_tracker |
6765cefc1a5a928b3cff16c0f1014096f82c3d3b | test/test_services.py | test/test_services.py | import pytest
@pytest.mark.parametrize("name, enabled, running", [
("cron", "enabled", "running"),
("docker", "enabled", "running"),
("firewalld", "enabled", "running"),
("haveged", "enabled", "running"),
("ssh", "enabled", "running"),
])
def test_services(Service, name, enabled, running):
is_enabled = Se... | import pytest
@pytest.mark.parametrize("name, enabled, running", [
("cron", "enabled", "running"),
("docker", "enabled", "running"),
("firewalld", "enabled", "running"),
("haveged", "enabled", "running"),
("ssh", "enabled", "running"),
])
def test_services(host, name, enabled, running):
svc = host.servic... | Change test function as existing method deprecated | Change test function as existing method deprecated
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build |
eea647cf05d7143d800f834dd77aeafc32522100 | groundstation/settings.py | groundstation/settings.py | PORT=1248
BEACON_TIMEOUT=5
DEFAULT_BUFSIZE=8192
| PORT=1248
BEACON_TIMEOUT=5
DEFAULT_BUFSIZE=8192
DEFAULT_CACHE_LIFETIME=900
| Add config key for default cache lifetime | Add config key for default cache lifetime
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation |
81f3e4f10243cb31b600666a19112acee7c13f55 | signac/db/__init__.py | signac/db/__init__.py | import warnings
try:
import pymongo # noqa
except ImportError:
warnings.warn("Failed to import pymongo. "
"get_database will not be available.", ImportWarning)
def get_database(*args, **kwargs):
"""Get a database handle.
This function is only available if pymongo is inst... | import logging
import warnings
try:
import pymongo # noqa
except ImportError:
warnings.warn("Failed to import pymongo. "
"get_database will not be available.", ImportWarning)
def get_database(*args, **kwargs):
"""Get a database handle.
This function is only available if ... | Add warning about outdated pymongo versions. | Add warning about outdated pymongo versions.
signac currently only supports pymongo versions 3.x.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac |
ee4f8264d942d7af5f5b71ff6cd162f3ae1fe515 | django_hash_filter/templatetags/hash_filter.py | django_hash_filter/templatetags/hash_filter.py | from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, arg):
"""
Return... | import hashlib
import sys
from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, arg):
""... | Convert unicode string to byte array on Python 3 | Convert unicode string to byte array on Python 3
| Python | mit | andrewjsledge/django-hash-filter |
df216bdc25ef29da821f577a517ccdca61448cf4 | django_lightweight_queue/middleware/logging.py | django_lightweight_queue/middleware/logging.py | from __future__ import absolute_import
import logging
import traceback
log = logging.getLogger(__name__)
class LoggingMiddleware(object):
def process_job(self, job):
log.info("Running job %s", job)
def process_result(self, job, result, duration):
log.info("Finished job %s => %r (Time taken: ... | from __future__ import absolute_import
import logging
import traceback
log = logging.getLogger(__name__)
class LoggingMiddleware(object):
def process_job(self, job):
log.info("Running job %s", job)
def process_result(self, job, result, duration):
log.info("Finished job => %r (Time taken: %.2... | Save over 50% of logfile 'bloat' by not repeating all args on success/failure | Save over 50% of logfile 'bloat' by not repeating all args on success/failure
The data will be right above it just before we run the job.
| Python | bsd-3-clause | prophile/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,thread/django-lightweight-queue |
802b9c2df754b3acf78e9e1facc1802a901e97a2 | furry/furry.py | furry/furry.py | import discord
from discord.ext import commands
class Furry:
"""A cog that adds weird furry commands or something"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def owo(self):
"""OwO what's this?"""
await self.bot.say("*Notices " + user.... | import discord
from discord.ext import commands
class Furry:
"""A cog that adds weird furry commands or something"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def owo(self, user : discord.Member):
"""OwO what's this?"""
await self.bot.... | Fix the command and make it actually work | Fix the command and make it actually work
Pass discord.Member as user
| Python | apache-2.0 | KazroFox/Kaz-Cogs |
6a508d01fa3fa0d4084406fcb2b5e41d1b614b7c | datalogger/__main__.py | datalogger/__main__.py | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.api.workspace import Workspace
from datalogger.analysis_window import AnalysisWindow
from datalogger import __version__
def run_datalogger_full():
print("CUED DataLogger {}".format(__version__))
app = 0
app = QApplication(sys.argv)
... | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.api.workspace import Workspace
from datalogger.analysis_window import AnalysisWindow
from datalogger import __version__
def run_datalogger_full():
print("CUED DataLogger {}".format(__version__))
app = 0
app = QApplication(sys.argv)
... | Move workspace before window creation so config set for window | Move workspace before window creation so config set for window
| Python | bsd-3-clause | torebutlin/cued_datalogger |
70808a2243ebf04aa86d5b4539950b22cd96cc7d | maras/utils/__init__.py | maras/utils/__init__.py | '''
Misc utilities
'''
# Import python libs
import os
import binascii
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
r... | '''
Misc utilities
'''
# Import python libs
import os
import time
import struct
import binascii
import datetime
# create a standard epoch so all platforms will count revs from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple())
def rand_hex_str(size):
'''
Retu... | Add rev generation via normalized timestamps | Add rev generation via normalized timestamps
| Python | apache-2.0 | thatch45/maras |
ae2d52e323ea8959caf474d23de857d59b5b6ca8 | spacy/tests/regression/test_issue3625.py | spacy/tests/regression/test_issue3625.py | from __future__ import unicode_literals
from spacy.lang.hi import Hindi
def test_issue3625():
"""Test that default punctuation rules applies to hindi unicode characters"""
nlp = Hindi()
doc = nlp(u"hi. how हुए. होटल, होटल")
assert [token.text for token in doc] == ['hi', '.', 'how', 'हुए', '.', 'होटल',... | # coding: utf8
from __future__ import unicode_literals
from spacy.lang.hi import Hindi
def test_issue3625():
"""Test that default punctuation rules applies to hindi unicode characters"""
nlp = Hindi()
doc = nlp(u"hi. how हुए. होटल, होटल")
assert [token.text for token in doc] == ['hi', '.', 'how', 'हुए... | Add default encoding utf-8 for test file | Add default encoding utf-8 for test file
| Python | mit | honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy |
ce873b24318fd6493f570f370db1d2c2d244bdcc | joby/spiders/data_science_jobs.py | joby/spiders/data_science_jobs.py | # -*- coding: utf-8 -*-
from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
class DataScienceJobsSpider(CrawlSpider):
log = getLogger(__name__)
name = 'data-science-jobs'
allowed_domains = ['www.data-science-jobs.com', 'fonts.googleap... | # -*- coding: utf-8 -*-
from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
class DataScienceJobsSpider(CrawlSpider):
log = getLogger(__name__)
name = 'data-science-jobs'
allowed_domains = ['www.data-science-jobs.com']
start_urls ... | Rename the parser function to parse_jobs. | Rename the parser function to parse_jobs.
| Python | mit | cyberbikepunk/job-spiders |
b77e8f9a081517701cccf9f177c81eaca877e8c7 | pombola/images/admin.py | pombola/images/admin.py | from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from sorl.thumbnail import get_thumbnail
from sorl.thumbnail.admin import AdminImageMixin
from pombola.images import models
class ImageAdmin(AdminImageMixin, admin.ModelAdmin):
list_display = [ 'thumbnail',... | from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from sorl.thumbnail import get_thumbnail
from sorl.thumbnail.admin import AdminImageMixin
from pombola.images import models
class ImageAdmin(AdminImageMixin, admin.ModelAdmin):
list_display = [ 'thumbnail',... | Handle entries that have no image associated with them | Handle entries that have no image associated with them
| Python | agpl-3.0 | ken-muturi/pombola,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,ken-muturi... |
a03b166f8297783819a43eeb78e5af4d52d11bcc | carbonate/list.py | carbonate/list.py | import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compi... | import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk # noqa # pylint: disable=unused-import
except ImportError:
from scandir import scandir, walk # noqa # pylint: disable=unused-import
def listMetrics(storag... | Make pylint happy as per graphite-web example | Make pylint happy as per graphite-web example
| Python | mit | criteo-forks/carbonate,jssjr/carbonate,deniszh/carbonate,graphite-project/carbonate,jssjr/carbonate,graphite-project/carbonate,criteo-forks/carbonate,jssjr/carbonate,deniszh/carbonate,deniszh/carbonate,criteo-forks/carbonate,graphite-project/carbonate |
119e95dedaf6633e1ca6367bfd13fa08192033bd | pywinauto/unittests/testall.py | pywinauto/unittests/testall.py | import unittest
import os.path
import os
import sys
sys.path.append(".")
#from pywinauto.timings import Timings
#Timings.Fast()
excludes = ['test_sendkeys']
def run_tests():
testfolder = os.path.abspath(os.path.split(__file__)[0])
sys.path.append(testfolder)
for root, dirs, files in... | import os
import sys
import unittest
import coverage
# needs to be called before importing the modules
cov = coverage.coverage(branch = True)
cov.start()
testfolder = os.path.abspath(os.path.dirname(__file__))
package_root = os.path.abspath(os.path.join(testfolder, r"..\.."))
sys.path.append(package_root... | Synchronize testing module with BetterBatch one - and integrate Coverage reporting | Synchronize testing module with BetterBatch one - and integrate Coverage reporting
| Python | bsd-3-clause | cessor/pywinauto,bombilee/pywinauto,ohio813/pywinauto,nameoffnv/pywinauto,yongxin1029/pywinauto,clonly/pywinauto,vsajip/pywinauto,cessor/pywinauto,LogicalKnight/pywinauto,ohio813/pywinauto,nameoffnv/pywinauto,ldhwin/pywinauto,airelil/pywinauto,drinkertea/pywinauto,prasen-ftech/pywinauto,vsajip/pywinauto,wilsoc5/pywinau... |
29032ee9dc69b1f3226358c3a6b74a7e42d71f07 | generationkwh/amortizations.py | generationkwh/amortizations.py | # -*- coding:utf8 -*-
from plantmeter.isodates import isodate
from dateutil.relativedelta import relativedelta
waitYears = 1
expirationYears = 25
def previousAmortizationDate(purchase_date, current_date):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
... | # -*- coding:utf8 -*-
from plantmeter.isodates import isodate
from dateutil.relativedelta import relativedelta
waitYears = 1
expirationYears = 25
def previousAmortizationDate(purchase_date, current_date):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
... | Modify return variable and partenesis | Modify return variable and partenesis
| Python | agpl-3.0 | Som-Energia/somenergia-generationkwh,Som-Energia/somenergia-generationkwh |
9a879fb583f7f4190a4601a9a488ba61414395e0 | kivymd/card.py | kivymd/card.py | # -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.elevationbehavior import ElevationBehavior
from kivymd.theming import ThemableBehavior
from kivy.metrics import dp
Builder.load_string('''... | # -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.elevationbehavior import ElevationBehavior
from kivymd.theming import ThemableBehavior
from kivy.metrics impo... | Add border as option (set via alpha) | Add border as option (set via alpha) | Python | mit | cruor99/KivyMD |
1736d7b7aed3ce3049186ce97e24941de0187caf | oidc_provider/lib/utils/common.py | oidc_provider/lib/utils/common.py | from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('o... | from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('o... | Add IOError custom message when rsa key file is missing. | Add IOError custom message when rsa key file is missing.
| Python | mit | ByteInternet/django-oidc-provider,torreco/django-oidc-provider,juanifioren/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,wojtek-fliposports/django-oidc-provider,nmohoric/django-oidc-provider,nmohoric/django-oidc-provider,... |
a174fbd637bf9ccc7b8a97a251c016495f92f6a9 | eliot/__init__.py | eliot/__init__.py | """
Eliot: Logging as Storytelling
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of self-del... | """
Eliot: Logging as Storytelling
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of self-del... | Add fields to the public API. | Add fields to the public API.
| Python | apache-2.0 | ClusterHQ/eliot,ScatterHQ/eliot,iffy/eliot,ScatterHQ/eliot,ScatterHQ/eliot |
fb1f6f30fc7ba2d3dcce357168a05669c934c234 | build/oggm/run_test.py | build/oggm/run_test.py | #!/usr/bin/env python
import os
os.environ["MPLBACKEND"] = 'agg'
import matplotlib
matplotlib.use('agg')
import pytest
import oggm
import sys
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
initial_dir = os.getcwd()
oggm_file = os.path.abspath(oggm.__file__)
oggm_dir = os.path.dirname... | #!/usr/bin/env python
import os
os.environ["MPLBACKEND"] = 'agg'
import matplotlib
matplotlib.use('agg')
import pytest
import oggm
import sys
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
if os.name == 'nt':
sys.exit(0)
initial_dir = os.getcwd()
oggm_file = os.path.abspath(oggm... | Disable testing on Windows for now, it just takes too long for any CI service | Disable testing on Windows for now, it just takes too long for any CI service
| Python | mit | OGGM/OGGM-Anaconda |
b1cc99458d22b8ed54326de6b4eafececb3a8093 | jobs/telemetry_aggregator.py | jobs/telemetry_aggregator.py | #!/home/hadoop/anaconda2/bin/ipython
import logging
from os import environ
from mozaggregator.aggregator import aggregate_metrics
from mozaggregator.db import submit_aggregates
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
date = environ['date']
logger... | #!/home/hadoop/anaconda2/bin/ipython
import logging
from os import environ
from mozaggregator.aggregator import aggregate_metrics
from mozaggregator.db import submit_aggregates
date = environ['date']
print "Running job for {}".format(date)
aggregates = aggregate_metrics(sc, ("nightly", "aurora", "beta", "release"), d... | Use simple prints for logging. | Use simple prints for logging.
| Python | mpl-2.0 | opentrials/opentrials-airflow,opentrials/opentrials-airflow |
1983885acfccfe4ffa010401fd9ef0971bb6c12c | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
from etcd3.client import Etcd3Client
from etcd3.client import client
from etcd3.client import Transactions
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client', 'etcdrpc', 'utils', 'Transactions']
| from __future__ import absolute_import
from etcd3.client import Etcd3Client
from etcd3.client import client
from etcd3.client import Transactions
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.1.0'
__all__ = ['Etcd3Client', 'client', 'etcdrpc', 'utils', '... | Make Member part of the public api | Make Member part of the public api
| Python | apache-2.0 | kragniz/python-etcd3 |
fb1db28198b54b6288a9e7d499b43f6f1a51284c | partner_deduplicate_by_website/__manifest__.py | partner_deduplicate_by_website/__manifest__.py | # Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2018 Tecnativa - Cristina Martin
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Deduplicate Contacts by Website",
"version": "13.0.1.0.0",
"category": "Tools",
"website"... | # Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2018 Tecnativa - Cristina Martin
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Deduplicate Contacts by Website",
"version": "13.0.1.0.0",
"category": "Tools",
"website"... | Fix website attribute in manifest | Fix website attribute in manifest
| Python | agpl-3.0 | OCA/partner-contact,OCA/partner-contact |
db84de91e665a131ad82be3ed49eb291afd5342d | oratioignoreparser.py | oratioignoreparser.py | import os
import re
class OratioIgnoreParser():
def __init__(self):
self.ignored_paths = ["oratiomodule.tar.gz"]
def load(self, oratio_ignore_path):
with open(oratio_ignore_path, "r") as f:
self.ignored_paths.extend([line.strip() for line in f])
def should_be_ignored(self, fi... | import os
import re
class OratioIgnoreParser():
def __init__(self):
self.ignored_paths = ["oratiomodule.tar.gz"]
def load(self, oratio_ignore_path):
with open(oratio_ignore_path, "r") as f:
self.ignored_paths.extend([line.strip() for line in f])
def should_be_ignored(self, fi... | Make all lines shorter than 80 characters | Make all lines shorter than 80 characters
| Python | mit | oratio-io/oratio-cli,oratio-io/oratio-cli |
5125bbfcf96ff0d3f2690198b43ed96059eb6745 | common/parsableText.py | common/parsableText.py | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
... | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
... | Fix unicode in parsable text | Fix unicode in parsable text
| Python | agpl-3.0 | GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious |
acd376d854693cacf8ca20a9971dcd2653a22429 | rlpy/Agents/__init__.py | rlpy/Agents/__init__.py | from .TDControlAgent import Q_Learning, SARSA
# for compatibility of old scripts
Q_LEARNING = Q_Learning
from .Greedy_GQ import Greedy_GQ
from .LSPI import LSPI
from .LSPI_SARSA import LSPI_SARSA
from .NaturalActorCritic import NaturalActorCritic
| from .TDControlAgent import Q_Learning, SARSA
# for compatibility of old scripts
Q_LEARNING = Q_Learning
from .Greedy_GQ import Greedy_GQ
from .LSPI import LSPI
from .LSPI_SARSA import LSPI_SARSA
from .NaturalActorCritic import NaturalActorCritic
from .PosteriorSampling import PosteriorSampling
from .UCRL import UCRL
| Add new agents to init file | Add new agents to init file
| Python | bsd-3-clause | imanolarrieta/RL,imanolarrieta/RL,imanolarrieta/RL |
48bc050c59d60037fa719542db8f6a0c68752ed1 | config/flask_config.py | config/flask_config.py | # flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABA... | # flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABA... | Use Linkr-unique session cookie name | Use Linkr-unique session cookie name
| Python | mit | LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr |
3ed02baa8ad7fcd1f6ca5cccc4f67799ec79e272 | kimi.py | kimi.py | # Kimi language interpreter in Python 3
# Anjana Vakil
# http://www.github.com/vakila/kimi
import sys
def tokenize(program):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x... | # Kimi language interpreter in Python 3
# Anjana Vakil
# http://www.github.com/vakila/kimi
import sys
def tokenize(string):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x ... | Rename program to string in tokenize | Rename program to string in tokenize
| Python | mit | vakila/kimi |
a7c40b43d90f32d0da4de1389d859865ae283180 | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | Update the proxy list examples | Update the proxy list examples
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase |
b158e65839b9b662d56bd43dfd362ad26da70184 | __init__.py | __init__.py | #Shoopdawoop
from . import CuraEngineBackend
from UM.Preferences import Preferences
def getMetaData():
return { "name": "CuraEngine Backend", "type": "Backend" }
def register(app):
Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine")
engine = CuraEngineBackend.CuraEngineBackend(... | #Shoopdawoop
from . import CuraEngineBackend
from UM.Preferences import Preferences
def getMetaData():
return { "name": "CuraEngine Backend", "type": "Backend" }
def register(app):
Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine")
return CuraEngineBackend.CuraEngineBackend()
... | Update plugin's register functions to return the object instance instead of performing the registration themselves | Update plugin's register functions to return the object instance instead of performing the registration themselves
| Python | agpl-3.0 | Curahelper/Cura,Curahelper/Cura,bq/Ultimaker-Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,quillford/Cura,fxtentacle/Cura,totalretribution/Cura,DeskboxBrazil/Cura,hmflash/Cura,ynotstartups/Wanhao,markwal/Cura,ad1217/Cura,ynotstartups/Wanhao,derekhe/Cura,lo0ol/Ultimaker-Cura,senttech/Cura,totalretribution/Cura,bq/Ultimak... |
c612b92847dc89bb4cd4b63502c43a7a9f63c52f | tx_salaries/utils/transformers/mixins.py | tx_salaries/utils/transformers/mixins.py | class OrganizationMixin(object):
@property
def organization(self):
return {
'name': self.ORGANIZATION_NAME,
'children': [{
'name': unicode(self.department),
}],
}
| class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department.
"""
@property
def organization(self):
return {
'name': ... | Add a docblock for this mixin | Add a docblock for this mixin
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries |
a08005a03ccce63a541e8e41b0d98e9c7c30cc67 | vispy/visuals/graphs/layouts/circular.py | vispy/visuals/graphs/layouts/circular.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import _straight_line_vertic... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import _straight_line_vertic... | Use the more obvious linspace instead of arange | Use the more obvious linspace instead of arange
| Python | bsd-3-clause | michaelaye/vispy,Eric89GXL/vispy,drufat/vispy,drufat/vispy,drufat/vispy,michaelaye/vispy,ghisvail/vispy,ghisvail/vispy,Eric89GXL/vispy,ghisvail/vispy,michaelaye/vispy,Eric89GXL/vispy |
76b0c364b8bfbc553d3eedc97e4805299b8d9974 | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
"""
TBC
"""
#
# Example of defining additional game modes:
# ==========================================
#
# Replace:
# ---------... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
"""
TBC
"""
#
# Example of defining additional game modes:
# ==========================================
#
# Replace:
# ---------... | Update to include instruction and help texts in GET response. | Update to include instruction and help texts in GET response.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
2eac437b9d907fb60d53522633dd278aa277ea08 | test/user_tests/test_models.py | test/user_tests/test_models.py | # coding: utf-8
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_user_profile, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.us... | # coding: utf-8
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_new_user, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user =... | Test for create user in model. Remove test profile creation | Test for create user in model. Remove test profile creation
| Python | mit | sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa |
fc01acc869969e5c0666de1065f149b3caec851d | core/wait_ssh_ready.py | core/wait_ssh_ready.py | from __future__ import print_function
import time
import sys
import socket
import logging
def wait_ssh_ready(host, tries=40, delay=3, port=22):
# Wait until the SSH is actually up
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.info('Waiting for SSH at %s to be ready to connect' % host, end... | from __future__ import print_function
import time
import sys
import socket
import logging
def wait_ssh_ready(host, tries=40, delay=3, port=22):
# Wait until the SSH is actually up
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Waiting for SSH at %s to be ready to connect' % host, end='')
... | Fix incorrect call to logging module | Fix incorrect call to logging module
| Python | agpl-3.0 | andresriancho/nimbostratus-target |
020e8db7ed28c3c6e6968d2d107b23e1fa8eb284 | pcapfile/test/__main__.py | pcapfile/test/__main__.py | #!/usr/bin/env python
"""
This is the front end to the pcapfile test SUITE.
"""
import unittest
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest
from pcap... | #!/usr/bin/env python
"""
This is the front end to the pcapfile test SUITE.
"""
import unittest
import sys
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTes... | Return -1 when tests fail | Return -1 when tests fail
| Python | isc | kisom/pypcapfile |
d474edcdbe1d9966ad09609b87d119c60c2a38d4 | datapusher/main.py | datapusher/main.py | import os
import six
import ckanserviceprovider.web as web
from . import jobs
# check whether jobs have been imported properly
assert(jobs.push_to_datastore)
def serve():
web.init()
web.app.run(web.app.config.get('HOST'), web.app.config.get('PORT'))
def serve_test():
web.init()
return web.app.test... | import os
import six
import ckanserviceprovider.web as web
from datapusher import jobs
# check whether jobs have been imported properly
assert(jobs.push_to_datastore)
def serve():
web.init()
web.app.run(web.app.config.get('HOST'), web.app.config.get('PORT'))
def serve_test():
web.init()
return web... | Fix Import Error for relative Import | [x]: Fix Import Error for relative Import
| Python | agpl-3.0 | ckan/datapusher |
946a2bcd57ac33cca0f48d29350a8f75b2fee2cf | sparqllib/tests/test_formatter.py | sparqllib/tests/test_formatter.py |
import unittest
import sparqllib
class TestBasicFormatter(unittest.TestCase):
def setUp(self):
self.formatter = sparqllib.formatter.BasicFormatter()
def test_newlines(self):
self.assertEqual(self.formatter.format("{}"), "{\n}")
def test_indentation(self):
self.assertEqual(self.fo... |
import unittest
import sparqllib
class TestBasicFormatter(unittest.TestCase):
def setUp(self):
self.formatter = sparqllib.formatter.BasicFormatter()
def test_newlines(self):
self.assertEqual(self.formatter.format("{}"), "{\n}")
self.assertEqual(self.formatter.format("{\n}"), "{\n}")
... | Add test to verify single newline is not stripped | Add test to verify single newline is not stripped
| Python | mit | ALSchwalm/sparqllib |
7aa84fbcc7a3af57ef62c29008fac4036d2d28af | django_afip/migrations/0021_drop_batches.py | django_afip/migrations/0021_drop_batches.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-02 23:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('afip', '0020_backfill_receiptvalidation__processed_date'),
]
operations = [
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-02 23:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('afip', '0020_backfill_receiptvalidation__processed_date'),
]
operations = [
... | Tweak a migration to run on non-transactional DBs | Tweak a migration to run on non-transactional DBs
A single migration failed to run on databases with no support for
transactions because those require explicit ordering of commands that's
generally implicit on modern relational DBs.
Switch the order of those queries to prevent that crash.
Fixes #27
| Python | isc | hobarrera/django-afip,hobarrera/django-afip |
1ff616fe4f6ff0ff295eeeaa4a817851df750e51 | openslides/utils/validate.py | openslides/utils/validate.py | import bleach
allowed_tags = [
"a",
"img", # links and images
"br",
"p",
"span",
"blockquote", # text layout
"strike",
"strong",
"u",
"em",
"sup",
"sub",
"pre", # text formatting
"h1",
"h2",
"h3",
"h4",
"h5",
"h6", # headings
"ol",
... | import bleach
allowed_tags = [
"a",
"img", # links and images
"br",
"p",
"span",
"blockquote", # text layout
"strike",
"del",
"ins",
"strong",
"u",
"em",
"sup",
"sub",
"pre", # text formatting
"h1",
"h2",
"h3",
"h4",
"h5",
"h6", #... | Allow <del> and <ins> html tags. | Allow <del> and <ins> html tags.
| Python | mit | tsiegleauq/OpenSlides,ostcar/OpenSlides,FinnStutzenstein/OpenSlides,normanjaeckel/OpenSlides,jwinzer/OpenSlides,OpenSlides/OpenSlides,tsiegleauq/OpenSlides,jwinzer/OpenSlides,FinnStutzenstein/OpenSlides,CatoTH/OpenSlides,CatoTH/OpenSlides,OpenSlides/OpenSlides,tsiegleauq/OpenSlides,CatoTH/OpenSlides,normanjaeckel/OpenS... |
e0ebd4cb41d3ed9168e819f7017dd98c2fbb599a | insertion_sort.py | insertion_sort.py | def insertion_sort(un_list):
for idx in range(1, len(un_list)):
current = un_list[idx]
position = idx
while position > 0 and un_list[position-1] > current:
un_list[position] = un_list[position-1]
position = position - 1
un_list[position] = current
if __name... | def insertion_sort(un_list):
if type(un_list) is not list:
return "You must pass a valid list as argument. Do it."
for idx in range(1, len(un_list)):
current = un_list[idx]
position = idx
while position > 0 and un_list[position-1] > current:
un_list[position] = un_l... | Update insertion sort with list validation | Update insertion sort with list validation
| Python | mit | jonathanstallings/data-structures |
5a2212746bfabcfd64cf27846770b35f767d57a6 | polls/views.py | polls/views.py | from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from singleurlcrud.views import CRUDView
from .models import *
# Create your views here.
class AuthorCRUDView(CRUDView):
model = Author
list_display = ('name',)
class QuestionCRUDView(CRUDView):
model = Question
lis... | from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from singleurlcrud.views import CRUDView
from .models import *
# Create your views here.
class AuthorCRUDView(CRUDView):
model = Author
list_display = ('name',)
class QuestionCRUDView(CRUDView):
model = Question
lis... | Implement 'Delete' action for polls sample app | Implement 'Delete' action for polls sample app
| Python | bsd-3-clause | harikvpy/crud,harikvpy/crud,harikvpy/crud |
9851430922f9c14583c9eb17062629f6ea99c258 | turbustat/tests/test_vcs.py | turbustat/tests/test_vcs.py | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for VCS
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import VCS, VCS_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testVCS(Test... | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for VCS
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import VCS, VCS_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_VCS_method():
tester ... | Reformat VCS tests; need updated unit test values! | Reformat VCS tests; need updated unit test values!
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat |
75b221fa63b0f81b94ffbbe9f5cdc39a0adb848a | dmrg101/core/braket.py | dmrg101/core/braket.py | '''
File: braket.py
Author: Ivan Gonzalez
Description: A function to implement quantum-mechanics brakets
'''
from numpy import inner
from core.exceptions import DMRGException
def braket(bra, ket):
"""Takes a bra and a ket and return their braket
You use this function to calculate the quantum mechanical braket... | '''
File: braket.py
Author: Ivan Gonzalez
Description: A function to implement quantum-mechanics brakets
'''
from numpy import inner, conjugate
from dmrg_exceptions import DMRGException
def braket(bra, ket):
"""Takes a bra and a ket and return their braket
You use this function to calculate the quantum mechan... | Clean up comments, fixing imports. | Clean up comments, fixing imports.
| Python | mit | iglpdc/dmrg101 |
b1bb9e86b51bf0d1c57fa10ac9b8297f0bc078db | flow_workflow/petri_net/future_nets/base.py | flow_workflow/petri_net/future_nets/base.py | from flow.petri_net import future
from flow.petri_net import success_failure_net
# XXX Maybe this turns into a historian mixin?
class GenomeNetBase(success_failure_net.SuccessFailureNet):
def __init__(self, name, operation_id, parent_operation_id=None):
success_failure_net.SuccessFailureNet.__init__(self,... | from flow.petri_net import future
from flow.petri_net.success_failure_net import SuccessFailureNet
# XXX Maybe this turns into a historian mixin?
class GenomeNetBase(SuccessFailureNet):
"""
Basically a success-failure net with operation_id and parent_operation_id and
the ability to construct historian_act... | Add comments and clean-up import of GenomeNetBase | Add comments and clean-up import of GenomeNetBase
| Python | agpl-3.0 | genome/flow-workflow,genome/flow-workflow,genome/flow-workflow |
de348d8816151f2674410566f3eaff9d43d9dcde | src/markdoc/cli/main.py | src/markdoc/cli/main.py | # -*- coding: utf-8 -*-
import os
import argparse
from markdoc.cli import commands
from markdoc.cli.parser import parser
from markdoc.config import Config, ConfigNotFound
def main(cmd_args=None):
"""The main entry point for running the Markdoc CLI."""
if cmd_args is not None:
args = parser.pars... | # -*- coding: utf-8 -*-
import logging
import os
import argparse
from markdoc.cli import commands
from markdoc.cli.parser import parser
from markdoc.config import Config, ConfigNotFound
def main(cmd_args=None):
"""The main entry point for running the Markdoc CLI."""
if cmd_args is not None:
arg... | Use logging levels to suppress non-error output with --quiet on the CLI. | Use logging levels to suppress non-error output with --quiet on the CLI.
| Python | unlicense | wlonk/markdoc,lrem/phdoc,lrem/phdoc,zacharyvoase/markdoc,snoozbuster/markdoc,wlonk/markdoc,snoozbuster/markdoc |
a9666ecaa7ed904cb9ded38e41ea381eb08d7d65 | citrination_client/models/design/target.py | citrination_client/models/design/target.py | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min")
"""
def __init__(self, name, objective):
"""
Co... | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min", or a scalar value (such as "5.0"))
"""
def __init__(self, name,... | Update outdated design Target docstring | Update outdated design Target docstring
| Python | apache-2.0 | CitrineInformatics/python-citrination-client |
dc57eb8fa84f10ffa9ba3f8133563b7de3945034 | whalelinter/commands/common.py | whalelinter/commands/common.py | #!/usr/bin/env python3
from whalelinter.app import App
from whalelinter.dispatcher import Dispatcher
from whalelinter.commands.command import Command
from whalelinter.commands.apt import Apt
@Dispatcher.register(token='run', command='cd')
class Cd(Command):
def __init__(self, **kwar... | #!/usr/bin/env python3
import re
from whalelinter.app import App
from whalelinter.dispatcher import Dispatcher
from whalelinter.commands.command import Command
from whalelinter.commands.apt import Apt
@Dispatcher.register(token='run', command='cd')
class Cd(Command):
def __init__(s... | Enhance flags detection with regex when trying to remove apt cache | Enhance flags detection with regex when trying to remove apt cache
| Python | mit | jeromepin/whale-linter |
bb3ba296038f45c2de6517c1f980843ce2042aa9 | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.leases import Lease
from etcd3.locks import Lock
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@... | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.leases import Lease
from etcd3.locks import Lock
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@... | Remove obsolete 'utils' entry from '__all__ | Remove obsolete 'utils' entry from '__all__
| Python | apache-2.0 | kragniz/python-etcd3 |
f698dbc8b10aacf6ac8ee2a5d0d63ad01bd73674 | octopus/image/data.py | octopus/image/data.py | # System Imports
import StringIO
import urllib
# Twisted Imports
from twisted.python.util import unsignedID
# Package Imports
from ..data.errors import Immutable
class Image (object):
@property
def value (self):
output = StringIO.StringIO()
img = self._image_fn()
img.scale(0.25).getPIL().save(output, format... | # System Imports
import StringIO
import urllib
# Package Imports
from ..data.errors import Immutable
class Image (object):
@property
def value (self):
output = StringIO.StringIO()
img = self._image_fn()
img.scale(0.25).getPIL().save(output, format = "PNG")
encoded = "data:image/png;base64," + urllib.quote(... | Replace another call to unsignedID. | Replace another call to unsignedID.
| Python | mit | richardingham/octopus,rasata/octopus,rasata/octopus,richardingham/octopus,richardingham/octopus,richardingham/octopus,rasata/octopus |
7881e6d06a34eddef5523df88ee601fb5e5d3ba6 | encryptit/dump_json.py | encryptit/dump_json.py | import json
from .compat import OrderedDict
from .openpgp_message import OpenPGPMessage
def dump_stream(f, output_stream, indent=4):
message = OpenPGPMessage.from_stream(f)
return json.dump(message, output_stream, indent=indent,
cls=OpenPGPJsonEncoder)
class OpenPGPJsonEncoder(json.JSO... | import json
from .compat import OrderedDict
from .openpgp_message import OpenPGPMessage
def dump_stream(f, output_stream, indent=4):
message = OpenPGPMessage.from_stream(f)
return json.dump(message, output_stream, indent=indent,
cls=OpenPGPJsonEncoder)
class OpenPGPJsonEncoder(json.JSO... | Revert "Fix JSON encoding of `PacketLocation`" | Revert "Fix JSON encoding of `PacketLocation`"
This reverts commit 9e91912c6c1764c88890ec47df9372e6ac41612c.
| Python | agpl-3.0 | paulfurley/encryptit,paulfurley/encryptit |
1239128a082757c3a7d53e7b14c189dda06f4171 | flaws/__init__.py | flaws/__init__.py | #!/usr/bin/env python
import sys
from funcy import split, map
from .analysis import global_usage, local_usage, FileSet
import sys, ipdb, traceback
def info(type, value, tb):
traceback.print_exception(type, value, tb)
print
ipdb.pm()
sys.excepthook = info
def main():
command = sys.argv[1]
kwa... | #!/usr/bin/env python
import sys
from funcy import split, map
from .analysis import global_usage, local_usage, FileSet
def main():
command = sys.argv[1]
kwargs, args = split(r'^--', sys.argv[2:])
kwargs = dict(map(r'^--(\w+)(?:=(.+))?', kwargs))
# Run ipdb on exception
if 'ipdb' in kwargs:
... | Make ipdb hook turn on only when --ipdb | Make ipdb hook turn on only when --ipdb
| Python | bsd-2-clause | Suor/flaws |
c64682fe6204b56bd5282c46a7c7168a55b46a86 | spicedham/__init__.py | spicedham/__init__.py | from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training... | from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training... | Allow for the case where no plugin returns a score | Allow for the case where no plugin returns a score
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.