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
c37500894b309a691009b87b1305935ee57648cb
tests/test_test.py
tests/test_test.py
import pytest from web_test_base import * """ A class to test new features without running all of the tests. Usage: py.test tests/test_test.py -rsx """ class TestTest(WebTestBase): urls_to_get = [ "http://aidtransparency.net/" ] text_to_find = [ ("information", '//*[@id="home-strapline...
import pytest from web_test_base import * """ A class to test new features without running all of the tests. Usage: py.test tests/test_test.py -rsx """ class TestTest(WebTestBase): urls_to_get = [ "http://iatistandard.org/" , "http://iatistandard.org/202/namespaces-extensions/" ] text_...
Add test text finding that fails
Add test text finding that fails This indicates that a different method of specifying how and where to find text within a document is required.
Python
mit
IATI/IATI-Website-Tests
dd9dfa86fe0f7cb8d95b580ff9ae62753fb19026
gefion/checks/base.py
gefion/checks/base.py
# -*- coding: utf-8 -*- """Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional...
# -*- coding: utf-8 -*- """Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional...
Fix typos in Result and Check docstrings
Fix typos in Result and Check docstrings
Python
bsd-3-clause
dargasea/gefion
2b9d702b6efd922069ceb44540b1ea7118e3f84b
gensysinfo.py
gensysinfo.py
#!/usr/bin/env python3 import psutil import os import time import math blocks = ['▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ'] def create_bar(filled): if filled > 1: low = str(int(filled)) high = str(int(filled + 1)) filled = filled - int(filled) filled = int(filled * 100) if filled < 50...
#!/usr/bin/env python3 import psutil import os import time import math blocks = ['▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ'] def create_bar(filled): filled = int(filled * 100) if filled < 50: color = "green" elif filled < 80: color = "yellow" else: color = "red" bar = '#[fg=' +...
Allow over 100 again for when load becomes available
Allow over 100 again for when load becomes available
Python
mit
wilfriedvanasten/miscvar,wilfriedvanasten/miscvar,wilfriedvanasten/miscvar
93380d1574438f4e70145e0bbcde4c3331ef5fd3
massa/domain.py
massa/domain.py
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Col...
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Col...
Add a method to find all measurements.
Add a method to find all measurements.
Python
mit
jaapverloop/massa
511abf77f16a7a92dde93a9f1318967b1d237635
go_doc_get.py
go_doc_get.py
import sublime import sublime_plugin import webbrowser def cleanPackage(pkgURI): pkg = pkgURI.split('.com/')[1] return pkg class GoDocGetCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view for region in view.sel(): selected = view.substr(region) if "github.corp" in selected: ...
import sublime import sublime_plugin import webbrowser def cleanPackage(pkgURI): pkg = pkgURI.split('.com/')[1] return pkg class GoDocGetCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view for region in view.sel(): selected = view.substr(region) if "github.corp" in selected: ...
Set specific branch to go to in GitHub
Set specific branch to go to in GitHub
Python
mit
lowellmower/go_doc_get
078a4d36c1dc088937b242ca63b88b4c03f33fa0
isitup/main.py
isitup/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests def check(url): try: response = requests.get( "https://isitup.org/{0}.json".format(url), headers={'User-Agent': 'https://github.com/lord63/isitup'}) except r...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests def check(url): try: response = requests.get( "https://isitup.org/{0}.json".format(url), headers={'User-Agent': 'https://github.com/lord63/isitup'}) except r...
Make sure handle all the exceptions
Make sure handle all the exceptions
Python
mit
lord63/isitup
a65eaeaef60492bfc6319fb9c810155d62c1a3b3
luigi/tasks/export/ftp/go_annotations.py
luigi/tasks/export/ftp/go_annotations.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
Update name and call correct export
Update name and call correct export This now calls the correct export function. Additionally, the class name is changed to reflect it does export.
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
d3cea746432b1bfd1b5f2d38972c1b761b96e8eb
fetchroots.py
fetchroots.py
import os import base64 from requests import Session, Request from OpenSSL import crypto #url = 'http://ct.googleapis.com/aviator/ct/v1/get-roots' url = 'https://ct.api.venafi.com/ct/v1/get-roots' s = Session() r = Request('GET', url) prepped = r.prepare() r = s.send(prepped) if r.status_code == 20...
import os import base64 from requests import Session, Request from OpenSSL import crypto url = 'http://ct.googleapis.com/aviator/ct/v1/get-roots' s = Session() r = Request('GET', url) prepped = r.prepare() r = s.send(prepped) if r.status_code == 200: roots = r.json() # RFC 6962 defines the cert...
Update to use Google Aviator test log
Update to use Google Aviator test log
Python
apache-2.0
wgoulet/CTPyClient
95b90325b1dfa535fc802ad2a06f15e30010bf3a
fore/hotswap.py
fore/hotswap.py
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self...
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self...
Use next(it) instead of it.next()
Hotswap: Use next(it) instead of it.next()
Python
artistic-2.0
MikeiLL/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension
a727161f67edff10bb94785e70add7c42ba99dcc
morepath/tests/test_app.py
morepath/tests/test_app.py
from morepath.app import App, global_app import morepath def setup_module(module): morepath.disable_implicit() def test_global_app(): assert global_app.extends == [] assert global_app.name == 'global_app' def test_app_without_extends(): myapp = App() assert myapp.extends == [global_app] as...
from morepath.app import App, global_app import morepath def setup_module(module): morepath.disable_implicit() def test_global_app(): assert global_app.extends == [] assert global_app.name == 'global_app' def test_app_without_extends(): myapp = App() assert myapp.extends == [global_app] as...
Add coverage of __repr__ of app.
Add coverage of __repr__ of app.
Python
bsd-3-clause
morepath/morepath,faassen/morepath,taschini/morepath
7e00b8a4436ee4bdad4d248a29985b1cef741a53
nimbus/apps/media/utils.py
nimbus/apps/media/utils.py
def bsd_rand(seed): return (1103515245 * seed + 12345) & 0x7fffffff def baseconv(v1, a1, a2): n1 = {c: i for i, c in dict(enumerate(a1)).items()} b1 = len(a1) b2 = len(a2) d1 = 0 for i, c in enumerate(v1): d1 += n1[c] * pow(b1, b1 - i - 1) v2 = "" while d1: v2 = a2[d1...
from nimbus.settings import SECRET_KEY import hashlib def baseconv(v1, a1, a2): n1 = {c: i for i, c in enumerate(a1)} b1 = len(a1) b2 = len(a2) d1 = 0 for i, c in enumerate(v1): d1 += n1[c] * pow(b1, len(v1) - i - 1) v2 = "" while d1: v2 = a2[d1 % b2] + v2 d1 //=...
Patch bug and security vulnerability
Patch bug and security vulnerability
Python
mit
ethanal/Nimbus,ethanal/Nimbus,ethanal/Nimbus,ethanal/Nimbus
8a4a8cc351ae7fecd53932d0fb6ca0a7f9a83fbc
falcom/api/test/test_uris.py
falcom/api/test/test_uris.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import ComposedAssertion from ..uri import URI # There are three URIs that I need to u...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import ComposedAssertion from ..uri import URI # There are three URIs that I need to u...
Refactor a test into its own "given" test class
Refactor a test into its own "given" test class
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
c84aef2acef68d5feadb23aa045d9aa6e2f8512d
tests/app/dao/test_fees_dao.py
tests/app/dao/test_fees_dao.py
from app.dao.fees_dao import dao_update_fee, dao_get_fees, dao_get_fee_by_id from app.models import Fee from tests.db import create_fee class WhenUsingFeesDAO(object): def it_creates_a_fee(self, db_session): fee = create_fee() assert Fee.query.count() == 1 fee_from_db = Fee.query.filter...
from app.dao.fees_dao import dao_update_fee, dao_get_fees, dao_get_fee_by_id from app.models import Fee from tests.db import create_fee class WhenUsingFeesDAO(object): def it_creates_a_fee(self, db_session): fee = create_fee() assert Fee.query.count() == 1 fee_from_db = Fee.query.filter...
Make fees dao test clearer
Make fees dao test clearer
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
5eb8297b6da0b0cfd885975d5b9993a07acca426
importlib_metadata/__init__.py
importlib_metadata/__init__.py
import os import sys import glob import email import itertools import contextlib class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): for...
import os import sys import glob import email import itertools import contextlib class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): glo...
Fix logic in path search.
Fix logic in path search.
Python
apache-2.0
python/importlib_metadata
694575e2707bdf7a2e042e2dd443a46481bc9d39
source/segue/__init__.py
source/segue/__init__.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import imp import uuid def discover_processors(paths=None, options=None): '''Return processor plugins discovered on *paths*. If *paths* is None will try to use environment variable :env...
Add helper function for discovering processor plugins.
Add helper function for discovering processor plugins.
Python
apache-2.0
4degrees/segue
8754f8b73b140fa597de1f70a0cf636d198fadb2
extension_course/tests/conftest.py
extension_course/tests/conftest.py
from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa location_id, minimal_event_dict, municipality, organization, place, user, user_api_client, django_db_modify_db_settings, django_db_s...
from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa location_id, minimal_event_dict, municipality, organization, place, user, user_api_client, django_db_modify_db_settings, django_db_s...
Add new make_* fixtures to extension_course tests
Add new make_* fixtures to extension_course tests
Python
mit
City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
e0d909e25fbf47ebad35756032c9230fe3d3bdaa
example/example/tasksapp/run_tasks.py
example/example/tasksapp/run_tasks.py
import time from dj_experiment.tasks.tasks import longtime_add, netcdf_save if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it will return False print 'Task finished? ', result.ready() print 'Task result: ', result.result # sleep 10 seconds...
import os import time from dj_experiment.tasks.tasks import longtime_add, netcdf_save from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR, DJ_EXPERIMENT_DATA_DIR) if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it wi...
Fix parameters in task call
Fix parameters in task call
Python
mit
francbartoli/dj-experiment,francbartoli/dj-experiment
21e15235b2cd767e0da56a2a0d224824fda58c42
Tools/idle/ZoomHeight.py
Tools/idle/ZoomHeight.py
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ...
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ...
Move zoom height functionality to separate function.
Move zoom height functionality to separate function.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
280c81a3990116f66de9af8e6fd6e71d0215a386
client.py
client.py
#!/usr/bin/env python from configReader import ConfigReader import sys import os, os.path import os.path from time import time from math import floor import hashlib import random import requests f = open('adjectives.txt','r') adjectives = [line.rstrip() for line in f] f.close() configReader = ConfigReader(name="clien...
#!/usr/bin/env python from configReader import ConfigReader import sys import os, os.path import os.path from time import time from math import floor import hashlib import random import requests f = open('adjectives.txt','r') adjectives = [line.rstrip() for line in f] f.close() configReader = ConfigReader(name="clien...
Add authentication to the serverside
Add authentication to the serverside
Python
mit
ollien/Screenshot-Uploader,ollien/Screenshot-Uploader
a68f3ea83c191478f6a7b0dc6a4b49ff6c297ae2
imports.py
imports.py
#!/usr/bin/env python # vim: set fileencoding=utf-8 : from flask import flash from old_xml_import import old_xml_import from sml_import import sml_import import gzip from model import db, Sample from sqlalchemy.sql import func def move_import(xmlfile, filename, user): if filename.endswith('.gz'): xmlfil...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : from flask import flash from old_xml_import import old_xml_import from sml_import import sml_import import gzip from model import db, Sample from sqlalchemy.sql import func def move_import(xmlfile, filename, user): move = None if filename.endswith('.gz'...
Fix exception 'local variable 'move' referenced before assignment' in case of upload of unknown file formats
Fix exception 'local variable 'move' referenced before assignment' in case of upload of unknown file formats
Python
mit
bwaldvogel/openmoves,marguslt/openmoves,marguslt/openmoves,bwaldvogel/openmoves,mourningsun75/openmoves,mourningsun75/openmoves,mourningsun75/openmoves,marguslt/openmoves,bwaldvogel/openmoves
3d86b4473f66a9311a94b1def4c40189eae23990
lancet/git.py
lancet/git.py
import sys import click from slugify import slugify class SlugBranchGetter(object): def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = 'features/{}'.format(issue.key) slug = slugify(issue.fields.summary[:30]) ...
import sys import click from slugify import slugify class SlugBranchGetter(object): prefix = 'feature/' def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = '{}{}'.format(self.prefix, issue.key) slug = slugify(i...
Change the prefix from features/ to feature/.
Change the prefix from features/ to feature/.
Python
mit
GaretJax/lancet,GaretJax/lancet
8816d06381625938137d9fbf8aaee3d9ddabae72
src/sentry/api/endpoints/organization_projects.py
src/sentry/api/endpoints/organization_projects.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project, Team class OrganizationProjectsEndpoint(Organizati...
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project class OrganizationProjectsEndpoint(OrganizationEndp...
Support API keys on organization project list (fixes GH-1666)
Support API keys on organization project list (fixes GH-1666)
Python
bsd-3-clause
ifduyue/sentry,ngonzalvez/sentry,jean/sentry,Kryz/sentry,nicholasserra/sentry,daevaorn/sentry,BayanGroup/sentry,mvaled/sentry,1tush/sentry,looker/sentry,mvaled/sentry,ngonzalvez/sentry,mvaled/sentry,zenefits/sentry,beeftornado/sentry,JackDanger/sentry,hongliang5623/sentry,daevaorn/sentry,JamesMura/sentry,gencer/sentry,...
9616b026894327eb7171f978f3856cdae7c9e06b
child_sync_typo3/wizard/delegate_child_wizard.py
child_sync_typo3/wizard/delegate_child_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <david@coninckx.com> # # The licence is in the file __ope...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <david@coninckx.com> # # The licence is in the file __ope...
Fix res returned on delegate
Fix res returned on delegate
Python
agpl-3.0
MickSandoz/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ndtran/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ndtran/compassion-switzerland,MickSandoz/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzer...
cc5cf942cc56f12e09c50c29b488f71504387b7f
avalonstar/apps/api/serializers.py
avalonstar/apps/api/serializers.py
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Raid, Series from apps.games.models import Game class BroadcastSerializer(serializers.ModelSerializer): class Meta: depth = 1 model = Broadcast class RaidSerializer(serializers.ModelSeri...
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Raid, Series from apps.games.models import Game class BroadcastSerializer(serializers.ModelSerializer): class Meta: model = Broadcast class RaidSerializer(serializers.ModelSerializer): class...
Remove the depth for now.
Remove the depth for now.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
b8770a85e11c048fb0dc6c46f799b17add07568d
productController.py
productController.py
from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('CIUK.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['p...
from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('databaseForTest.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc']...
Change name of database for test
Change name of database for test
Python
mit
joykuotw/python-endpoints,joykuotw/python-endpoints,joykuotw/python-endpoints
c129b435a7759104feaaa5b828dc2f2ac46d5ab1
src/cmdlinetest/afp_mock.py
src/cmdlinetest/afp_mock.py
#!/usr/bin/env python from bottle import route from textwrap import dedent from bottledaemon import daemon_run """ Simple AFP mock to allow testing the afp-cli. """ @route('/account') def account(): return """{"test_account": ["test_role"]}""" @route('/account/<account>/<role>') def credentials(account, role): ...
#!/usr/bin/env python """ Simple AFP mock to allow testing the afp-cli. """ from bottle import route from textwrap import dedent from bottledaemon import daemon_run @route('/account') def account(): return """{"test_account": ["test_role"]}""" @route('/account/<account>/<role>') def credentials(account, role): ...
Move string above the imports so it becomes a docstring
Move string above the imports so it becomes a docstring
Python
apache-2.0
ImmobilienScout24/afp-cli,ImmobilienScout24/afp-cli,ImmobilienScout24/afp-cli
0ee0650dfacf648982615be49cefd57f928a73ee
holonet/core/list_access.py
holonet/core/list_access.py
# -*- coding: utf8 -*- from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) ...
# -*- coding: utf8 -*- from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) ...
Change to exists instead of catching DoesNotExist exception.
Change to exists instead of catching DoesNotExist exception.
Python
mit
webkom/holonet,webkom/holonet,webkom/holonet
f68b4b9b133d3c8ecb9826af9736c8c1fca64e49
maxims/credentials.py
maxims/credentials.py
from axiom import attributes, item from twisted.cred import credentials class UsernamePassword(item.Item): """ A stored username and password. """ username = attributes.bytes(allowNone=False) password = attributes.bytes(allowNone=False) def instantiate(self): return credentials.Userna...
from axiom import attributes, item from twisted.cred import credentials class UsernamePassword(item.Item): """ A stored username and password. Note that although this class is an ``IUsernamePassword`` implementation, you should still use the ``instantiate`` method to get independent ``IUsernamePa...
Add caveat about UsernamePassword already being an IUsernamePassword implementation
Add caveat about UsernamePassword already being an IUsernamePassword implementation
Python
isc
lvh/maxims
214511a6fbdd0763667e740735d0876f78a3b244
derpibooru/query.py
derpibooru/query.py
from .request import url class Search(object): def __init__(self, key=None, q=[], sf="created_at", sd="desc"): self._parameters = { "key": key, "q": q, "sf": sf, "sd": sd } @property def parameters(self): return self._parameters @property def url(self): return url(**...
from .request import url class Search(object): def __init__(self, key=None, q=[], sf="created_at", sd="desc"): self._parameters = { "key": key, "q": [str(tag).strip() for tag in q if tag], "sf": sf, "sd": sd } @property def parameters(self): return self._parameters @proper...
Add check for empty tags
Add check for empty tags
Python
bsd-2-clause
joshua-stone/DerPyBooru
68636bfcf95163e9764860b09a713d59464e3419
conda/linux_dev/get_freecad_version.py
conda/linux_dev/get_freecad_version.py
import sys import os import subprocess import platform platform_dict = {} platform_dict["Darwin"] = "OSX" sys_n_arch = platform.platform() sys_n_arch = sys_n_arch.split("-") system, arch = sys_n_arch[0], sys_n_arch[4] if system in platform_dict: system = platform_dict[system] version_info = subprocess.check_outp...
import sys import os import subprocess import platform platform_dict = {} platform_dict["Darwin"] = "OSX" sys_n_arch = platform.platform() sys_n_arch = sys_n_arch.split("-") system, arch = sys_n_arch[0], sys_n_arch[4] if system in platform_dict: system = platform_dict[system] version_info = subprocess.check_outp...
Revert to using current AppImage update info
Revert to using current AppImage update info https://github.com/FreeCAD/FreeCAD-AppImage/issues/35
Python
lgpl-2.1
FreeCAD/FreeCAD-AppImage,FreeCAD/FreeCAD-AppImage
956ad502766eddbaf3c81672a30e58c814ba8437
test/test_api_classes.py
test/test_api_classes.py
import pytest from jedi import api def make_definitions(): return api.defined_names(""" import sys class C: pass x = C() def f(): pass """) @pytest.mark.parametrize('definition', make_definitions()) def test_basedefinition_type(definition): assert definition.type in (...
import textwrap import pytest from jedi import api def make_definitions(): """ Return a list of definitions for parametrized tests. :rtype: [jedi.api_classes.BaseDefinition] """ source = textwrap.dedent(""" import sys class C: pass x = C() def f(): pass ""...
Make more examples in make_definitions
Make more examples in make_definitions
Python
mit
WoLpH/jedi,jonashaag/jedi,tjwei/jedi,flurischt/jedi,dwillmer/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,WoLpH/jedi
460a2430fbd8832f3fada1a74b754d71a27ac282
mockingjay/matcher.py
mockingjay/matcher.py
import abc import re class Matcher(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def assert_request_matched(self, request): """ Assert that the request matched the spec in this matcher object. """ class HeaderMatcher(Matcher): """ Matcher for the request's hea...
import abc import re class StringOrPattern(object): """ A decorator object that wraps a string or a regex pattern so that it can be compared against another string either literally or using the pattern. """ def __init__(self, subject): self.subject = subject def __eq__(self, other_str...
Allow all values to be compared with either literally or with a pattern
Allow all values to be compared with either literally or with a pattern
Python
bsd-3-clause
kevinjqiu/mockingjay
da69fff2d104c9cccd285078c40de05ea46fdb4d
halaqat/urls.py
halaqat/urls.py
"""halaqat URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
"""halaqat URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
Add back-office to student URL
Add back-office to student URL
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
20929dd2e1ddd0909afc3e25b040bfdcdc2c9b00
src/opencmiss/neon/core/problems/biomeng321lab1.py
src/opencmiss/neon/core/problems/biomeng321lab1.py
''' Copyright 2015 University of Auckland 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 agre...
''' Copyright 2015 University of Auckland 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 agre...
Change name of boundary conditions for Biomeng321 Lab1.
Change name of boundary conditions for Biomeng321 Lab1.
Python
apache-2.0
alan-wu/neon
8c551fe51ed142305945c0cef530ac84ed3e7eb9
nodeconductor/logging/perms.py
nodeconductor/logging/perms.py
from nodeconductor.core.permissions import StaffPermissionLogic PERMISSION_LOGICS = ( ('logging.Alert', StaffPermissionLogic(any_permission=True)), ('logging.SystemNotification', StaffPermissionLogic(any_permission=True)), )
from nodeconductor.core.permissions import StaffPermissionLogic PERMISSION_LOGICS = ( ('logging.Alert', StaffPermissionLogic(any_permission=True)), ('logging.WebHook', StaffPermissionLogic(any_permission=True)), ('logging.PushHook', StaffPermissionLogic(any_permission=True)), ('logging.EmailHook', Sta...
Allow staff user to manage hooks.
Allow staff user to manage hooks.
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
13df4b7ba5c706e1fddbd17ac9edf3894e9a7206
nymms/tests/test_registry.py
nymms/tests/test_registry.py
import unittest from nymms import registry from nymms.resources import Command, MonitoringGroup from weakref import WeakValueDictionary class TestRegistry(unittest.TestCase): def test_empty_registry(self): self.assertEqual(Command.registry, WeakValueDictionary()) def test_register_object(self): ...
import unittest from nymms import registry from nymms.resources import Command, MonitoringGroup from weakref import WeakValueDictionary class TestRegistry(unittest.TestCase): def tearDown(self): # Ensure we have a fresh registry after every test Command.registry.clear() def test_empty_registr...
Clear registry between each test
Clear registry between each test
Python
bsd-2-clause
cloudtools/nymms
6f50381e2e14ab7c1c90e52479ffcfc7748329b3
UI/resources/constants.py
UI/resources/constants.py
# -*- coding: utf-8 -*- SAVE_PASSWORD_HASHED = True MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3 MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3 MAX_RETRIES_NEGOTIATE_CONTRACT = 10 MAX_RETRIES_GET_FILE_POINTERS = 10 FILE_POINTERS_REQUEST_DELAY = 1 # int: file pointers request delay, in seconds. MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = ...
# -*- coding: utf-8 -*- SAVE_PASSWORD_HASHED = True MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3 MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3 MAX_RETRIES_NEGOTIATE_CONTRACT = 10 MAX_RETRIES_GET_FILE_POINTERS = 10 FILE_POINTERS_REQUEST_DELAY = 1 # int: file pointers request delay, in seconds. MAX_DOWNLOAD_REQUEST_BLOCK_SIZE = ...
Add farmer max timeout constant
Add farmer max timeout constant
Python
mit
lakewik/storj-gui-client
be9d58ffcf23e4fb47d2c09e869368ab9ec738c9
localore/localore/embeds.py
localore/localore/embeds.py
from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(...
from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(...
Fix SoundCloud embed width/height replacement.
Fix SoundCloud embed width/height replacement. SoundCloud embeds aren't always 500x500. Also, don't set the "width" embed dict key to '100%': "width"/"height" keys expect integers only.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
8184354179bf6cf88304ebd743b2236258e46522
unicornclient/routine.py
unicornclient/routine.py
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): ...
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): ...
Disable sleep function when stopping
Disable sleep function when stopping
Python
mit
amm0nite/unicornclient,amm0nite/unicornclient
42db9ceae490152040651a23d397e7ad4c950712
flask/flask/tests/test_template.py
flask/flask/tests/test_template.py
from flask import Flask, render_template_string import jinja2 def test_undefined_variable__no_error(): app = Flask(__name__) assert issubclass(app.jinja_env.undefined, jinja2.Undefined) @app.route('/') def endpoint(): return render_template_string('foo = [{{bar}}]', foo='blabla') resp = a...
# -*- coding: utf-8 -*- from flask import Flask, render_template_string import jinja2 def test_undefined_variable__no_error(): app = Flask(__name__) assert issubclass(app.jinja_env.undefined, jinja2.Undefined) @app.route('/') def endpoint(): return render_template_string('foo = [{{bar}}]', foo...
Fix source code encoding error
[flask] Fix source code encoding error
Python
mit
imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning
49c60d069da48cd83939a4e42e933e9a28e21dd2
tests/cupy_tests/cuda_tests/test_nccl.py
tests/cupy_tests/cuda_tests/test_nccl.py
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) ...
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) ...
Check NCCL existence in test decorators
Check NCCL existence in test decorators
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
5ca84f89d08ab4b31c47753ce74129ce06f8ed3a
apps/bluebottle_utils/models.py
apps/bluebottle_utils/models.py
from django.db import models from django_countries import CountryField class Address(models.Model): """ A postal address. """ address_line1 = models.CharField(max_length=100, blank=True) address_line2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=...
from django.db import models from django_countries import CountryField class Address(models.Model): """ A postal address. """ address_line1 = models.CharField(max_length=100, blank=True) address_line2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=...
Add a __unicode__ method to the Address model in utils.
Add a __unicode__ method to the Address model in utils.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
a9cebe11642b41a8c0b277e09bf273b52dbb63f9
apps/careeropportunity/views.py
apps/careeropportunity/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render from django.utils import timezone # API v1 from rest_framework import mixins, viewsets from rest_framework.permissions import AllowAny from apps.careeropportunity.models import CareerOpportunity from apps.careeropportunity.serializers import CareerSerializer...
# -*- coding: utf-8 -*- from django.shortcuts import render from django.utils import timezone # API v1 from rest_framework import mixins, viewsets from rest_framework.permissions import AllowAny from rest_framework.pagination import PageNumberPagination from apps.careeropportunity.models import CareerOpportunity from...
Increase pagination size for careeropportunity api
Increase pagination size for careeropportunity api
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
453b6a8697b066174802257156ac364aed2c650a
emission/storage/timeseries/aggregate_timeseries.py
emission/storage/timeseries/aggregate_timeseries.py
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {}
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {} ...
Implement a sort key method for the aggregate timeseries
Implement a sort key method for the aggregate timeseries This should return null because we want to mix up the identifying information from the timeseries and sorting will re-impose some order. Also sorting takes too much time!
Python
bsd-3-clause
shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-...
6577b521ac8fd0f1c9007f819dc0c7ee27ef4955
numba/typesystem/tests/test_type_properties.py
numba/typesystem/tests/test_type_properties.py
from numba.typesystem import * assert int_.is_int assert int_.is_numeric assert long_.is_int assert long_.is_numeric assert not long_.is_long assert float_.is_float assert float_.is_numeric assert double.is_float assert double.is_numeric assert not double.is_double assert object_.is_object assert list_.is_list asser...
from numba.typesystem import * assert int_.is_int assert int_.is_numeric assert long_.is_int assert long_.is_numeric assert not long_.is_long assert float_.is_float assert float_.is_numeric assert double.is_float assert double.is_numeric assert not double.is_double assert object_.is_object assert list_(int_, 2).is_l...
Update test for rename of list type
Update test for rename of list type
Python
bsd-2-clause
gdementen/numba,GaZ3ll3/numba,stuartarchibald/numba,pitrou/numba,jriehl/numba,stefanseefeld/numba,ssarangi/numba,sklam/numba,IntelLabs/numba,gdementen/numba,jriehl/numba,stuartarchibald/numba,GaZ3ll3/numba,GaZ3ll3/numba,seibert/numba,numba/numba,pombredanne/numba,jriehl/numba,pitrou/numba,cpcloud/numba,gmarkall/numba,s...
c9f5bee80dfb0523050afc6cb72eea096a2e3b95
ir/util.py
ir/util.py
import os import stat import time def updateModificationTime(path): accessTime = os.stat(path)[stat.ST_ATIME] modificationTime = time.time() os.utime(path, (accessTime, modificationTime))
import os import stat import time from PyQt4.QtCore import SIGNAL from PyQt4.QtGui import QAction, QKeySequence, QMenu, QShortcut from aqt import mw def addMenu(name): if not hasattr(mw, 'customMenus'): mw.customMenus = {} if name not in mw.customMenus: menu = QMenu('&' + name, mw) m...
Add helper functions for adding menu items & shortcuts
Add helper functions for adding menu items & shortcuts
Python
isc
luoliyan/incremental-reading-for-anki,luoliyan/incremental-reading-for-anki
eff7f0bf52507013859788eec29eea819af6ce63
grow/preprocessors/routes_cache.py
grow/preprocessors/routes_cache.py
from . import base class RoutesCachePreprocessor(base.BasePreprocessor): KIND = '_routes_cache' def __init__(self, pod): self.pod = pod def run(self, build=True): self.pod.routes.reset_cache(rebuild=True) def list_watched_dirs(self): return ['/content/', '/static/']
import datetime from . import base class RoutesCachePreprocessor(base.BasePreprocessor): KIND = '_routes_cache' LIMIT = datetime.timedelta(seconds=1) def __init__(self, pod): self.pod = pod self._last_run = None def run(self, build=True): # Avoid rebuilding routes cache more ...
Implement ratelimit on routes cache.
Implement ratelimit on routes cache.
Python
mit
denmojo/pygrow,grow/pygrow,grow/grow,denmojo/pygrow,denmojo/pygrow,grow/pygrow,grow/grow,grow/grow,grow/grow,grow/pygrow,denmojo/pygrow
38d16da934503a964ae5e16aafd65c0642970472
pysocialids.py
pysocialids.py
# # define overloading of ids for each social site # to be customized for your accounts # # # flickr # def flickr_api_secret(): return "" def flickr_api_key(): return "" def flickr_user_id(): return "" # # twitter # def twitter_consumer_key(): return "" def twitter_consu...
# # define overloading of ids for each social site # to be customized for your accounts # # # flickr # def flickr_api_secret(): return "" def flickr_api_key(): return "" def flickr_user_id(): return "" # # twitter # def twitter_consumer_key(): return "" def twitter_consu...
Complete social ids for wordpress and faa
Complete social ids for wordpress and faa
Python
mit
JulienLeonard/socialstats
b555137fa7c7e84353daa1d12e29ba636bb9fd77
post_office/test_settings.py
post_office/test_settings.py
# -*- coding: utf-8 -*- INSTALLED_APPS = ['post_office'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', ...
# -*- coding: utf-8 -*- INSTALLED_APPS = ['post_office'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX...
Use locmem cache for tests.
Use locmem cache for tests.
Python
mit
JostCrow/django-post_office,ekohl/django-post_office,CasherWest/django-post_office,ui/django-post_office,carrerasrodrigo/django-post_office,CasherWest/django-post_office,fapelhanz/django-post_office,jrief/django-post_office,RafRaf/django-post_office,LeGast00n/django-post_office,yprez/django-post_office,ui/django-post_o...
96856fc267ec99de6e83a997346c853dbdb1cfd5
reddit_adzerk/lib/validator.py
reddit_adzerk/lib/validator.py
import re from r2.lib.errors import errors from r2.lib.validator import ( VMultiByPath, Validator, ) from r2.models import ( NotFound, Subreddit, ) is_multi_rx = re.compile(r"\A/?(user|r)/[^\/]+/m/(?P<name>.*?)/?\Z") class VSite(Validator): def __init__(self, param, required=True, *args, **kwargs...
import re from r2.lib.errors import errors from r2.lib.validator import ( VMultiByPath, Validator, ) from r2.models import ( NotFound, Subreddit, MultiReddit, ) is_multi_rx = re.compile(r"\A/?(user|r)/[^\/]+/m/(?P<name>.*?)/?\Z") is_adhoc_multi_rx = re.compile(r"\A\/r\/((?:[0-z]+\+)+(?:[0-z])+)\Z"...
Fix adhoc multisubreddit promo_request network request
Fix adhoc multisubreddit promo_request network request
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
06d271da251d3c85266629197d6b31b2ff617623
sympy/matrices/expressions/tests/test_hadamard.py
sympy/matrices/expressions/tests/test_hadamard.py
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct from sympy.matrices import ShapeError from sympy import symbols from sympy.utilities.pytest import raises def test_HadamardProduct(): n, m, k = symbols('n,m,k') Z = MatrixSymbol('Z', n, n) A = MatrixSymbol('A', n, m) B = MatrixSymbol...
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct from sympy.matrices import ShapeError from sympy import symbols from sympy.utilities.pytest import raises def test_HadamardProduct(): n, m, k = symbols('n,m,k') Z = MatrixSymbol('Z', n, n) A = MatrixSymbol('A', n, m) B = MatrixSymbol...
Add index test for Hadamard+MatMul mix
Add index test for Hadamard+MatMul mix
Python
bsd-3-clause
kaichogami/sympy,Sumith1896/sympy,sahmed95/sympy,MridulS/sympy,Gadal/sympy,yashsharan/sympy,Shaswat27/sympy,chaffra/sympy,beni55/sympy,drufat/sympy,MechCoder/sympy,souravsingh/sympy,kaushik94/sympy,abhiii5459/sympy,liangjiaxing/sympy,iamutkarshtiwari/sympy,Gadal/sympy,grevutiu-gabriel/sympy,vipulroxx/sympy,moble/sympy,...
24d2b9620af40395c66bd8d93c443fddfe74b5cf
hs_core/tests/api/rest/__init__.py
hs_core/tests/api/rest/__init__.py
from test_create_resource import * from test_resource_file import * from test_resource_list import * from test_resource_meta import * from test_resource_types import * from test_set_access_rules import * from test_user_info import *
# Do not import tests here as this will cause # some tests to be discovered and run twice
Remove REST test imports to avoid some tests being run twice
Remove REST test imports to avoid some tests being run twice
Python
bsd-3-clause
ResearchSoftwareInstitute/MyHPOM,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,hydroshare/hydroshare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM,hydroshare/hydroshare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,h...
d328129a2f2909c1b8769f1edb94746c4a88dd28
test_project/test_models.py
test_project/test_models.py
from django.db import models class TestUser0(models.Model): username = models.CharField() test_field = models.CharField('My title') class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): ...
from django.db import models class TestUser0(models.Model): username = models.CharField(max_length=255) test_field = models.CharField('My title', max_length=255) class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original f...
Add `max_length` to char fields
Add `max_length` to char fields
Python
bsd-3-clause
byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter
36e6e2bedcc37a48097ccf0abd544ca095748412
build/strip-po-charset.py
build/strip-po-charset.py
# # strip-po-charset.py # import sys, string def strip_po_charset(inp, out): out.write(string.replace(inp.read(), "\"Content-Type: text/plain; charset=UTF-8\\n\"\n","")) def main(): if len(sys.argv) != 3: print "Usage: %s <input (po) file> <output (spo) fi...
# # strip-po-charset.py # import sys, string def strip_po_charset(inp, out): out.write(string.replace(inp.read(), "\"Content-Type: text/plain; charset=UTF-8\\n\"\n","")) def main(): if len(sys.argv) != 3: print "Usage: %s <input (po) file> <output (spo) file>" % sys.arg...
Set svn:eol-style='native' on some text files that were lacking it.
Set svn:eol-style='native' on some text files that were lacking it. git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@855475 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
wbond/subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion
a00f9c56671c028c69638f61d3d4c1fd022c0430
cinspect/tests/test_patching.py
cinspect/tests/test_patching.py
from __future__ import absolute_import, print_function # Standard library import inspect import unittest from cinspect import getfile, getsource class TestHelloModule(unittest.TestCase): def test_patching_inspect_should_work(self): # Given inspect.getsource = getsource inspect.getfile =...
from __future__ import absolute_import, print_function # Standard library import inspect import unittest from cinspect import getfile, getsource class TestPatching(unittest.TestCase): def test_patching_inspect_should_work(self): # Given inspect.getsource = getsource inspect.getfile = ge...
Fix copy paste bug in test class name.
Fix copy paste bug in test class name.
Python
bsd-3-clause
punchagan/cinspect,punchagan/cinspect
97e39ec9e03728384ad00a7e011194412521631e
tests/test_containers.py
tests/test_containers.py
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import os import threading import unittest import containers PORT = 8080 cla...
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import os import threading import unittest import glob, os import containers ...
Remove aci files after tests have run
Remove aci files after tests have run
Python
mit
kragniz/containers
daf4a6fd35811210c546782a771c6ddef8641f25
opps/images/templatetags/images_tags.py
opps/images/templatetags/images_tags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.conf import settings from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.conf import settings from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj...
Fix image_obj template tag when sending Nonetype image
Fix image_obj template tag when sending Nonetype image
Python
mit
YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps
53d25950eb1ff21bb4488b60e802cb243735681f
cmsplugin_zinnia/placeholder.py
cmsplugin_zinnia/placeholder.py
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry with a Placeholder to edit content""" content_placehol...
"""Placeholder model for Zinnia""" import inspect from django.template.context import Context, RequestContext from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry...
Make acquire_context always return some Context
Make acquire_context always return some Context
Python
bsd-3-clause
django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia
caf245e14421472adb0668e57adf5a3e3ae68424
scuba/utils.py
scuba/utils.py
try: from shlex import quote as shell_quote except ImportError: from pipes import quote as shell_quote def format_cmdline(args, maxwidth=80): def lines(): line = '' for a in (shell_quote(a) for a in args): if len(line) + len(a) > maxwidth: yield line ...
try: from shlex import quote as shell_quote except ImportError: from pipes import quote as shell_quote def format_cmdline(args, maxwidth=80): '''Format args into a shell-quoted command line. The result will be wrapped to maxwidth characters where possible, not breaking a single long argument. ...
Fix missing final line from format_cmdline()
Fix missing final line from format_cmdline() The previous code was missing 'yield line' after the for loop. This commit fixes that, as well as the extra space at the beginning of each line. Normally, we'd use str.join() to avoid such a problem, but this code is accumulating the line manually, so we can't just join the...
Python
mit
JonathonReinhart/scuba,JonathonReinhart/scuba,JonathonReinhart/scuba
2c5c04fd0bb1dc4f5bf54af2e2739fb6a0f1d2c4
survey/urls.py
survey/urls.py
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', # Examples: url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/', SurveyDetail.as_view(), name='survey-detail'), url(...
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^s...
Fix - No more crash when entering an url with letter
Fix - No more crash when entering an url with letter
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
0381fe32664e246011d5917a81c81fce936ae364
tests/tangelo-verbose.py
tests/tangelo-verbose.py
import fixture def test_standard_verbosity(): stderr = fixture.start_tangelo(stderr=True) stderr = '\n'.join(stderr) assert 'TANGELO Server is running' in stderr assert 'TANGELO Hostname' in stderr fixture.stop_tangelo() def test_lower_verbosity(): stderr = fixture.start_tangelo("-q", stder...
import fixture def test_standard_verbosity(): stderr = fixture.start_tangelo(stderr=True) stderr = '\n'.join(stderr) fixture.stop_tangelo() assert 'TANGELO Server is running' in stderr assert 'TANGELO Hostname' in stderr def test_lower_verbosity(): stderr = fixture.start_tangelo("-q", stder...
Reorder when the tangelo instance gets shut down in a test so that if an assert fails, other tests will still be able to run.
Reorder when the tangelo instance gets shut down in a test so that if an assert fails, other tests will still be able to run.
Python
apache-2.0
Kitware/tangelo,Kitware/tangelo,Kitware/tangelo
e2954d74b77046d3dee8134128f122a09dff3c7d
clowder_server/emailer.py
clowder_server/emailer.py
from django.core.mail import send_mail from clowder_account.models import ClowderUser ADMIN_EMAIL = 'admin@clowder.io' def send_alert(company, name): for user in ClowderUser.objects.filter(company=company): subject = 'FAILURE: %s' % (name) body = subject send_mail(subject, body, ADMIN_EMAI...
import os import requests from django.core.mail import send_mail from clowder_account.models import ClowderUser ADMIN_EMAIL = 'admin@clowder.io' def send_alert(company, name): for user in ClowderUser.objects.filter(company=company): subject = 'FAILURE: %s' % (name) body = subject slack_to...
Add support for slack messaging
Add support for slack messaging
Python
agpl-3.0
keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server
247c1fc0af2556a5bd421488430d97f45c533771
kaggle/titanic/categorical_and_scaler_prediction.py
kaggle/titanic/categorical_and_scaler_prediction.py
import pandas def main(): train_all = pandas.DataFrame.from_csv('train.csv') train = train_all[['Survived', 'Sex', 'Fare']] print(train) if __name__ == '__main__': main()
import pandas from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.preprocessing import LabelEncoder def main(): train_all = pandas.DataFrame.from_csv('train.csv') train = train_all[['Survived', 'Sex', 'Fare']][:20] gender_label = LabelEncoder()...
Make predictions with gender and ticket price
Make predictions with gender and ticket price
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
70259a9f9ce5647f9c36b70c2eb20b51ba447eda
middleware.py
middleware.py
#!/usr/bin/env python3 class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route tab...
#!/usr/bin/env python3 class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route tab...
Add read static files feature.
Add read static files feature.
Python
bsd-3-clause
starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer
2ef97501b15a9369d21953312115ea36355f251c
minimax.py
minimax.py
class Heuristic: def heuristic(self, board, color): raise NotImplementedError('Dont override this class')
class Heuristic: def heuristic(self, board, color): raise NotImplementedError('Dont override this class') class Minimax: def __init__(self, color_me, h_me, h_challenger): self.h_me = h_me self.h_challenger = h_challenger self.color_me = color_me def heuristic(self, board, color): if co...
Create the minimal class MiniMax
Create the minimal class MiniMax
Python
apache-2.0
frila/agente-minimax
8a573dae750b1b9415df0c9e2c019750171e66f0
migrations.py
migrations.py
import os import json from dateutil.parser import parse from scrapi.util import safe_filename def migrate_from_old_scrapi(): for dirname, dirs, filenames in os.walk('archive'): for filename in filenames: oldpath = os.path.join(dirname, filename) source, sid, dt = dirname.split('/...
import os import json from dateutil.parser import parse from scrapi.util import safe_filename def migrate_from_old_scrapi(): for dirname, dirs, filenames in os.walk('archive'): for filename in filenames: oldpath = os.path.join(dirname, filename) source, sid, dt = dirname.split('/...
Move json print methods into if statement
Move json print methods into if statement
Python
apache-2.0
erinspace/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,fabianvf/scrapi,fabianvf/scrapi,ostwald/scrapi,mehanig/scrapi,alexgarciac/scrapi,jeffreyliu3230/scrapi,felliott/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi
c668aaa0f22f5a61094c2028291b65c781733a54
mojapi/api.py
mojapi/api.py
import json import requests import time def get_statuses(): return requests.get('https://status.mojang.com/check/').json() def get_uuid(username, unix_timestamp=None): if unix_timestamp is None: unix_timestamp = int(time.time()) return requests.get( 'https://api.mojang.com/users/profile...
import json import requests import time def get_statuses(): return requests.get('https://status.mojang.com/check/').json() def get_uuid(username, unix_timestamp=None): if unix_timestamp is None: unix_timestamp = int(time.time()) return requests.get( 'https://api.mojang.com/users/profile...
Add get blocked server hashes call
Add get blocked server hashes call
Python
mit
zugmc/mojapi
6845c56edc315f5ce07f0bf1101d59ee04036024
pydir/daemon-rxcmd.py
pydir/daemon-rxcmd.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 F Dou<programmingrobotsstudygroup@gmail.com> # See LICENSE for details. import bluetooth import os import logging import time from daemon import runner class RxCmdDaemon(): def __init__(self): self.stdin_path = '/dev/null' self.stdou...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 F Dou<programmingrobotsstudygroup@gmail.com> # See LICENSE for details. import bluetooth import os import logging import time from daemon import runner class RxCmdDaemon(): def __init__(self): self.stdin_path = '/dev/null' self.stdou...
Add try/catch to improve error handling
Add try/catch to improve error handling
Python
apache-2.0
javatechs/RxCmd,javatechs/RxCmd,javatechs/RxCmd
96df077d5485979af256fe7b95708ace658fb8e2
test/mitmproxy/test_examples.py
test/mitmproxy/test_examples.py
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from netlib import tutils as netutils from netlib.http import Headers from . import tservers, tutils from examples import ( modify_form, ) def test_load_scripts(): example_dir = utils.Data(__name__).path("../../examples") ...
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from netlib import tutils as netutils from netlib.http import Headers from . import tservers, tutils from examples import ( add_header, modify_form, ) def test_load_scripts(): example_dir = utils.Data(__name__).path("../...
Add tests for add_header example
Add tests for add_header example
Python
mit
mitmproxy/mitmproxy,jvillacorta/mitmproxy,tdickers/mitmproxy,dufferzafar/mitmproxy,mosajjal/mitmproxy,cortesi/mitmproxy,tdickers/mitmproxy,dwfreed/mitmproxy,laurmurclar/mitmproxy,gzzhanghao/mitmproxy,ddworken/mitmproxy,mosajjal/mitmproxy,mhils/mitmproxy,mhils/mitmproxy,fimad/mitmproxy,mitmproxy/mitmproxy,ujjwal96/mitmp...
6f45e82af789586baf7354b562bbb1587d94b28c
qual/tests/test_calendar.py
qual/tests/test_calendar.py
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
Add a test for a date missing from English historical calendars.
Add a test for a date missing from English historical calendars.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
d4c168cc552a444ecb3ee3059f12fa1c34c4419c
test_sempai.py
test_sempai.py
import jsonsempai import os import shutil import sys import tempfile TEST_FILE = '''{ "three": 3, "one": { "two": { "three": 3 } } }''' class TestSempai(object): def setup(self): self.direc = tempfile.mkdtemp(prefix='jsonsempai') sys.path.append(self.dire...
import jsonsempai import os import shutil import sys import tempfile TEST_FILE = '''{ "three": 3, "one": { "two": { "three": 3 } } }''' class TestSempai(object): def setup(self): self.direc = tempfile.mkdtemp(prefix='jsonsempai') sys.path.append(self.dire...
Add test for removing item
Add test for removing item
Python
mit
kragniz/json-sempai
004326064c87184e4373ab0b2d8d7ef9b46d94f9
tokens/conf.py
tokens/conf.py
PHASES = ( ('PHASE_01', 'In review',), ('PHASE_02', 'Active',), ('PHASE_02', 'Inactive',), )
PHASES = ( ('PHASE_01', 'In review',), ('PHASE_02', 'Active',), ('PHASE_02', 'Inactive',), ) TOKEN_TYPES = ( ('MintableToken', 'Mintable Token'), )
Add MintableToken as new token type
Add MintableToken as new token type
Python
apache-2.0
onyb/ethane,onyb/ethane,onyb/ethane,onyb/ethane
76ec25090ece865d67f63c07c32aff7cebf105c1
ynr/apps/people/migrations/0034_get_birth_year.py
ynr/apps/people/migrations/0034_get_birth_year.py
# Generated by Django 3.2.4 on 2021-10-27 14:41 from django.db import migrations def get_birth_year(apps, schema_editor): Person = apps.get_model("people", "Person") for person in Person.objects.all(): birth_year = person.birth_date.split("-")[0] person.birth_date = birth_year person....
# Generated by Django 3.2.4 on 2021-10-27 14:41 from django.db import migrations def get_birth_year(apps, schema_editor): Person = apps.get_model("people", "Person") for person in Person.objects.exclude(birth_date="").iterator(): birth_year = person.birth_date.split("-")[0] person.birth_date ...
Improve performance of birth date data migration
Improve performance of birth date data migration
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
1782b15b244597d56bff18c465237c7e1f3ab482
wikked/commands/users.py
wikked/commands/users.py
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() ...
import logging import getpass from wikked.bcryptfallback import generate_password_hash from wikked.commands.base import WikkedCommand, register_command logger = logging.getLogger(__name__) @register_command class UsersCommand(WikkedCommand): def __init__(self): super(UsersCommand, self).__init__() ...
Add some explanation as to what to do with the output.
newuser: Add some explanation as to what to do with the output.
Python
apache-2.0
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
2342cd5ede9fac66007d2b15025feeff52c2400b
flexget/plugins/operate/verify_ssl_certificates.py
flexget/plugins/operate/verify_ssl_certificates.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event log = logging.getLogger('verify_ssl') class VerifySSLCertificates(object): """ Plugin that ...
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging from requests.packages import urllib3 from flexget import plugin from flexget.event import event log = logging.getLogger('verify_ssl') class VerifySSLCertifi...
Disable warnings about disabling SSL verification.
Disable warnings about disabling SSL verification. Disabling SSL certificate verification results in a warning for every HTTPS request: "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html" D...
Python
mit
OmgOhnoes/Flexget,qk4l/Flexget,jacobmetrick/Flexget,jacobmetrick/Flexget,Flexget/Flexget,LynxyssCZ/Flexget,crawln45/Flexget,Flexget/Flexget,ianstalk/Flexget,OmgOhnoes/Flexget,poulpito/Flexget,drwyrm/Flexget,malkavi/Flexget,jawilson/Flexget,malkavi/Flexget,LynxyssCZ/Flexget,jawilson/Flexget,ianstalk/Flexget,gazpachoking...
3ca30011794143785955792e391902823427ef77
registration/views.py
registration/views.py
# Create your views here. from django.http import HttpResponse from registration.models import Team from django.core import serializers def get_teams(request): return_data = serializers.serialize("json", Team.objects.all()) return HttpResponse(return_data, content_type="application/json")
# Create your views here. from django.http import HttpResponse from registration.models import Team from django.core import serializers from django.views.decorators.cache import cache_page @cache_page(60 * 5) def get_teams(request): return_data = serializers.serialize("json", Team.objects.all()) return HttpRe...
Add caching for getTeams API call
Add caching for getTeams API call
Python
bsd-3-clause
hgrimberg01/esc,hgrimberg01/esc
33fbc424d725836355c071593042953fb195cff6
server/project/apps/core/serializers.py
server/project/apps/core/serializers.py
from rest_framework import serializers from .models import Playlist, Track, Favorite class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' class PlaylistSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: ...
from rest_framework import serializers from .models import Playlist, Track, Favorite class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' class PlaylistSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: ...
Add tracks to playlist on update
Add tracks to playlist on update
Python
mit
hrr20-over9000/9001,SoundMoose/SoundMoose,SoundMoose/SoundMoose,douvaughn/9001,douvaughn/9001,hxue920/9001,hrr20-over9000/9001,hxue920/9001,CalHoll/SoundMoose,CalHoll/SoundMoose,douvaughn/9001,CalHoll/SoundMoose,hrr20-over9000/9001,hxue920/9001,douvaughn/9001,hxue920/9001,SoundMoose/SoundMoose,SoundMoose/SoundMoose,Cal...
193831b6ee8b49674e32413e71819f2451bfc844
situational/apps/quick_history/forms.py
situational/apps/quick_history/forms.py
from django import forms from . import widgets class HistoryDetailsForm(forms.Form): CIRCUMSTANCE_CHOICES = [ ("full_time", "Full time"), ("part_time", "Part time"), ("work_programme", "Work programme"), ("unemployed", "Unemployed"), ("sick", "Off sick"), ("trainin...
from django import forms from . import widgets class HistoryDetailsForm(forms.Form): CIRCUMSTANCE_CHOICES = [ ("full_time", "Full time"), ("part_time", "Part time"), ("unemployed", "Unemployed"), ("sick", "Off sick"), ("training", "In full time training"), ("caring...
Remove "work programme" option from quick history
Remove "work programme" option from quick history
Python
bsd-3-clause
lm-tools/situational,lm-tools/sectors,lm-tools/situational,lm-tools/situational,lm-tools/situational,lm-tools/sectors,lm-tools/situational,lm-tools/sectors,lm-tools/sectors
1ca9052a989ad0c1642875c7f29b8ba2130011fa
south/introspection_plugins/__init__.py
south/introspection_plugins/__init__.py
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_o...
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_o...
Add import of django-annoying patch
Add import of django-annoying patch
Python
apache-2.0
smartfile/django-south,smartfile/django-south
93373242eab8d387a9b13c567239fa2e36b10ffa
mqtt_logger/management/commands/runmqttlistener.py
mqtt_logger/management/commands/runmqttlistener.py
from django.core.management.base import BaseCommand, CommandError from mqtt_logger.models import * class Command(BaseCommand): help = 'Start listening to mqtt subscriptions and save messages in database.' def add_arguments(self, parser): pass def handle(self, *args, **options): self.stdo...
from django.core.management.base import BaseCommand, CommandError from mqtt_logger.models import * import time class Command(BaseCommand): help = 'Start listening to mqtt subscriptions and save messages in database.' def add_arguments(self, parser): pass def handle(self, *args, **options): ...
Make the listener automatically update the subscriptions.
Make the listener automatically update the subscriptions.
Python
mit
ast0815/mqtt-hub,ast0815/mqtt-hub
e019ce982325a6284e844df3c9a5f8172f494ba3
run_mandel.py
run_mandel.py
import fractal import bmp pixels = fractal.mandelbrot(488, 256) bmp.write_grayscale('mandel.bmp', pixels)
import fractal import bmp def main(): pixels = fractal.mandelbrot(488, 256) bmp.write_grayscale('mandel.bmp', pixels) if __name__ == '__main__': main()
Add a main runner for mandel
Add a main runner for mandel
Python
mit
kentoj/python-fundamentals
fa78c5b5442c904ba3888b858eb2c284f16664ed
pages/urls/page.py
pages/urls/page.py
from django.conf.urls import include, patterns, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = patterns('', url(r'', include(router.urls)), )
from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = [ url(r'', include(router.urls)), ]
Purge unnecessary patterns function from urls
Purge unnecessary patterns function from urls
Python
bsd-2-clause
incuna/feincms-pages-api
13f3d7d4a708cd05712b610d979dcf857ae85856
Agents/SentinelDefense.py
Agents/SentinelDefense.py
from pysc2.agents import base_agents from pysc2.lib import actions ## SENTINEL FUNCTIONS # Functions related with Hallucination _HAL_ADEPT = actions.FUNCTIONS.Hallucination_Adept_quick.id _HAL_ARCHON = actions.FUNCTIONS.Hallucination_Archon_quick.id _HAL_COL = actions.FUNCTIONS.Hallucination_Colossus_quick.id _HAL...
from pysc2.agents import base_agents from pysc2.lib import actions Class Sentry(): '''Defines how the sentry SC2 unit works''' def Force_Field(): '''Function related with Force Field creation''' _FORCE_FIELD = actions.FUNCTIONS.Effect_ForceField_screen.id def Guardian_Shield(): '''Function ...
Define class sentry with main actions
Define class sentry with main actions
Python
apache-2.0
SoyGema/Startcraft_pysc2_minigames
1c01b9e794445242c450534d1615a9dc755b89da
randcat.py
randcat.py
import random random.seed() while True: print(chr(random.getrandbits(8)), end='')
#! /usr/bin/python3 import random random.seed() # this initializes with the Date, which I think is a novel enough seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed print(chr(random.getrandbits(8)), end='')
Add some comments and a shebang on top.
Add some comments and a shebang on top.
Python
apache-2.0
Tombert/RandCat
589bc468783e6c7620c3be21195fdbe88e796234
linguist/helpers.py
linguist/helpers.py
# -*- coding: utf-8 -*- import collections import itertools from . import utils def prefetch_translations(instances, **kwargs): """ Prefetches translations for the given instances. Can be useful for a list of instances. """ from .mixins import ModelMixin populate_missing = kwargs.get('popula...
# -*- coding: utf-8 -*- import collections import itertools from . import utils def prefetch_translations(instances, **kwargs): """ Prefetches translations for the given instances. Can be useful for a list of instances. """ from .mixins import ModelMixin if not isinstance(instances, collecti...
Fix prefetch_translations() -- be sure we only deal with iteratables.
Fix prefetch_translations() -- be sure we only deal with iteratables.
Python
mit
ulule/django-linguist
2f8a2fdad8deb96b7b3c971baf866f248c23fdda
madam_rest/views.py
madam_rest/views.py
from flask import jsonify, url_for from madam_rest import app, asset_storage @app.route('/assets/') def assets_retrieve(): assets = [asset_key for asset_key in asset_storage] return jsonify({ "data": assets, "meta": { "count": len(assets) } }) @app.route('/assets/<as...
from datetime import datetime from flask import jsonify, url_for from fractions import Fraction from frozendict import frozendict from madam_rest import app, asset_storage def _serializable(value): """ Utility function to convert data structures with immutable types to mutable, serializable data structur...
Improve serialization of asset metadata.
Improve serialization of asset metadata.
Python
agpl-3.0
eseifert/madam-rest
bae4032cc686fbac906d19456ed744a97b0e1365
characters/views.py
characters/views.py
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
Set default race and class without extra database queries
Set default race and class without extra database queries
Python
mit
mpirnat/django-tutorial-v2
6a4dd66035956037d660271f18592af04edab818
read_images.py
read_images.py
import time import cv2 import os import glob # path = 'by_class' path = 'test' t1 = time.time() file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]')) t2 = time.time() print('Time to list files: ', t2-t1) file_classes=[ele.split('/')[1] for ele in file_names] t3 = time.time() print('Time to list lab...
import time import os import glob import tensorflow as tf # path = 'by_class' path = 'test' t1 = time.time() file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]')) filename_queue = tf.train.string_input_producer(file_names) t2 = time.time() print('Time to list files: ', t2-t1) file_classes=[int(ele....
Read all images using tf itself
Read all images using tf itself
Python
apache-2.0
iitmcvg/OCR-Handwritten-Text,iitmcvg/OCR-Handwritten-Text,iitmcvg/OCR-Handwritten-Text
169d32333aa3152dcec893f2ce58c46d614aaea4
models/employees.py
models/employees.py
import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_pub...
import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_pub...
Fix Dangerous default value {} as argument, pylint.
Fix Dangerous default value {} as argument, pylint.
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
84f913d928d28bc193d21eb223e7815f69c53a22
plugins/jira.py
plugins/jira.py
from neb.engine import Plugin, Command import requests class JiraPlugin(Plugin): def get_commands(self): """Return human readable commands with descriptions. Returns: list[Command] """ return [ Command("jira", self.jira, "Perform commands on Matrix...
from neb.engine import Plugin, Command, KeyValueStore import json import requests class JiraPlugin(Plugin): def __init__(self, config="jira.json"): self.store = KeyValueStore(config) if not self.store.has("url"): url = raw_input("JIRA URL: ").strip() self.store.set("url"...
Make the plugin request server info from JIRA.
Make the plugin request server info from JIRA.
Python
apache-2.0
Kegsay/Matrix-NEB,matrix-org/Matrix-NEB,illicitonion/Matrix-NEB
4fd67e4e17f0813056493a635e8256a017d894e2
src/tempel/models.py
src/tempel/models.py
from django.db import models from django.conf import settings from tempel import utils class Entry(models.Model): content = models.TextField() language = models.CharField(max_length=20, choices=utils.get_languages()) created = models.DateTimeField(auto_now=True, auto_now_ad...
from django.db import models from django.conf import settings from tempel import utils class Entry(models.Model): content = models.TextField() language = models.CharField(max_length=20, choices=utils.get_languages()) created = models.DateTimeField(auto_now=True, auto_now_ad...
Add text representation for Entry object
Add text representation for Entry object
Python
agpl-3.0
fajran/tempel
d17a2308ff903b459b6c9310fd6d42eb0e051544
statsSend/teamCity/teamCityStatisticsSender.py
statsSend/teamCity/teamCityStatisticsSender.py
#!/usr/bin/env python3 from dateutil import parser from statsSend.teamCity.teamCityConnection import TeamCityConnection from statsSend.teamCity.teamCityUrlBuilder import TeamCityUrlBuilder from statsSend.teamCity.teamCityProject import TeamCityProject class TeamCityStatisticsSender: def __init__(self, settings, ...
#!/usr/bin/env python3 from dateutil import parser from statsSend.teamCity.teamCityConnection import TeamCityConnection from statsSend.teamCity.teamCityUrlBuilder import TeamCityUrlBuilder from statsSend.teamCity.teamCityProject import TeamCityProject class TeamCityStatisticsSender: def __init__(self, settings, ...
Add error handling in statistics sender
Add error handling in statistics sender
Python
mit
luigiberrettini/build-deploy-stats
00b134df7281c39595f9efcc1c1da047d1d10277
src/encoded/authorization.py
src/encoded/authorization.py
from .contentbase import LOCATION_ROOT CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a' def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) user = None # We may get called before the context is found and the root set root = r...
from .contentbase import LOCATION_ROOT CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a' def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) user = None # We may get called before the context is found and the root set root = r...
Update group finder to new schemas
Update group finder to new schemas
Python
mit
kidaa/encoded,philiptzou/clincoded,4dn-dcic/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,philiptzou/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,kidaa/encoded,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/snovault,kidaa/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/encode...
5cd9ac8d3079fca16828b25b40fed8358286708b
geotrek/outdoor/models.py
geotrek/outdoor/models.py
from django.conf import settings from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from geotrek.authent.models import StructureRelated from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin from mapentity.models import MapEntityMixin clas...
from django.conf import settings from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from geotrek.authent.models import StructureRelated from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin from mapentity.models import MapEntityMixin clas...
Add links to site detail in site list
Add links to site detail in site list
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
c8e11b602eb7525789ed1c5f4ea686f45b44f304
src/diamond/handler/httpHandler.py
src/diamond/handler/httpHandler.py
#!/usr/bin/python2.7 from Handler import Handler import urllib import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 100...
#!/usr/bin/env python # coding=utf-8 from Handler import Handler import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 1...
Remove unneeded import, fix python path and add coding
Remove unneeded import, fix python path and add coding
Python
mit
signalfx/Diamond,ramjothikumar/Diamond,jriguera/Diamond,anandbhoraskar/Diamond,jriguera/Diamond,Precis/Diamond,jriguera/Diamond,socialwareinc/Diamond,saucelabs/Diamond,acquia/Diamond,dcsquared13/Diamond,stuartbfox/Diamond,hvnsweeting/Diamond,h00dy/Diamond,cannium/Diamond,dcsquared13/Diamond,Ssawa/Diamond,bmhatfield/Dia...
f076acb05840c361890fbb5ef0c8b43d0de7e2ed
opsdroid/message.py
opsdroid/message.py
""" Class to encapsulate a message """ import logging class Message: """ A message object """ def __init__(self, text, user, room, connector): """ Create object with minimum properties """ self.text = text self.user = user self.room = room self.connector = connector ...
""" Class to encapsulate a message """ import logging class Message: """ A message object """ def __init__(self, text, user, room, connector): """ Create object with minimum properties """ self.text = text self.user = user self.room = room self.connector = connector ...
Make regex a None property
Make regex a None property
Python
apache-2.0
FabioRosado/opsdroid,jacobtomlinson/opsdroid,opsdroid/opsdroid
c197bf432655ca051ff4fb672cd41e876d539990
pipeline/api/api.py
pipeline/api/api.py
import datetime import json import falcon from pipeline.api import models, schemas def json_serializer(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() raise TypeError('{} is not JSON serializable'.format(type(obj))) def json_dump(data): return json.dumps(data, default=json_se...
import datetime import json import falcon from pipeline.api import models, schemas def json_serializer(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() raise TypeError('{} is not JSON serializable'.format(type(obj))) def json_dump(data): return json.dumps(data, default=json_se...
Allow creating and viewing stories
Allow creating and viewing stories Closes #1
Python
mit
thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline
220b6a9fee0f307d4de1e48b29093812f7dd10ec
var/spack/repos/builtin/packages/m4/package.py
var/spack/repos/builtin/packages/m4/package.py
from spack import * class M4(Package): """GNU M4 is an implementation of the traditional Unix macro processor.""" homepage = "https://www.gnu.org/software/m4/m4.html" url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz" version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76') depends_on('libsigseg...
from spack import * class M4(Package): """GNU M4 is an implementation of the traditional Unix macro processor.""" homepage = "https://www.gnu.org/software/m4/m4.html" url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz" version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76') variant('sigsegv', de...
Make libsigsegv an optional dependency
Make libsigsegv an optional dependency
Python
lgpl-2.1
lgarren/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,TheTimmy/spack,lgarren/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,mfherbst/spack,matthiasdiener/spack,matthiasdiener/s...
b38647ef390ed6c78c2d55d706bac2f6a396ad39
errors.py
errors.py
# ## PyMoira client library ## ## This file contains the Moira-related errors. # import moira_constants class MoiraBaseError(Exception): """Any exception thrown by the library is inhereted from this""" pass class MoiraConnectionError(MoiraBaseError): """An error which prevents the client from having or continuin...
# ## PyMoira client library ## ## This file contains the Moira-related errors. # import moira_constants class MoiraBaseError(Exception): """Any exception thrown by the library is inhereted from this""" pass class MoiraConnectionError(MoiraBaseError): """An error which prevents the client from having or continuin...
Introduce a new error class.
Introduce a new error class.
Python
mit
vasilvv/pymoira
95e347ae4086d05aadf91a393b856961b34026a5
website_field_autocomplete/controllers/main.py
website_field_autocomplete/controllers/main.py
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from openerp import http from openerp.http import request from openerp.addons.website.controllers.main import Website class Website(Website): @http.route( '/website/fiel...
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from openerp import http from openerp.http import request from openerp.addons.website.controllers.main import Website class Website(Website): @http.route( '/website/fiel...
Use search_read * Use search_read in controller data getter, instead of custom implementation
[FIX] website_field_autocomplete: Use search_read * Use search_read in controller data getter, instead of custom implementation
Python
agpl-3.0
Tecnativa/website,nicolas-petit/website,khaeusler/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,JayVora-SerpentCS/website,khaeusler/website,nicolas-petit/website,Tecnativa/website,khaeusler/website,Tecnativa/website,RoelAdriaans-B-informed/website,nicolas-petit/website,JayVora-SerpentCS/website,Roel...