commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
ad54fc8030c47dbacfd80665a6ae3b7ad6a0270d | Fix docstring for is_pyinstaller(). | angr/angr,angr/angr,angr/angr | angr/utils/env.py | angr/utils/env.py | import sys
def is_pyinstaller() -> bool:
"""
Detect if we are currently running as a PyInstaller-packaged program.
:return: True if we are running as a PyInstaller-packaged program. False if we are running in Python directly
(e.g., development mode).
"""
return getattr(sys, 'fro... | import sys
def is_pyinstaller() -> bool:
"""
Detect if we are currently running as a PyInstaller-packaged program.
:return: True if we are running as a PyInstaller-packaged program. False if we are running in Python directly
(e.g., development mode).
"""
return getattr(sys, 'froz... | bsd-2-clause | Python |
6797c9b705b0cfd5c770f68695402baf044510ff | Change default value of checkpoint frequency | harpribot/representation-music,harpribot/representation-music | utils/training_utils/params.py | utils/training_utils/params.py | # Data set split
TRAIN_FRACTION = 0.75
VALIDATE_FRACTION = 0.1
TEST_FRACTION = 0.15
TOTAL_NUM_EXAMPLES = 147052 # Total number of tracks
assert(TRAIN_FRACTION + VALIDATE_FRACTION + TEST_FRACTION == 1.0)
# Validation and check pointing
EVALUATION_FREQ = 900 # Number of mini-batch SGD steps after which an evaluati... | # Data set split
TRAIN_FRACTION = 0.75
VALIDATE_FRACTION = 0.1
TEST_FRACTION = 0.15
TOTAL_NUM_EXAMPLES = 147052 # Total number of tracks
assert(TRAIN_FRACTION + VALIDATE_FRACTION + TEST_FRACTION == 1.0)
# Validation and check pointing
EVALUATION_FREQ = 1000 # Number of mini-batch SGD steps after which an evaluat... | mit | Python |
7a60b7ba2141a94d2d7ad93a07039100f965bb17 | Update IrrigatorsModel.py | mikelambson/tcid,mikelambson/tcid,mikelambson/tcid,mikelambson/tcid | backend/IrrigatorsModel.py | backend/IrrigatorsModel.py | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
from components.validation import validate_word;
class Irrigators(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
name = DB.Column(DB.Varchar(40));
notation = DB.Column(DB.Text);
cre... | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
from components.validation import validate_word;
class Irrigators(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
name = DB.Column(DB.Varchar(40));
notation = DB.Column(DB.Text);
cre... | bsd-3-clause | Python |
3bb167fdbf4e4e3f41a7dda6dbdb2005f3be6d52 | make assert python2.6 compatible | lamby/django-extensions,zefciu/django-extensions,helenst/django-extensions,mandx/django-extensions,maroux/django-extensions,barseghyanartur/django-extensions,dpetzold/django-extensions,mandx/django-extensions,helenst/django-extensions,JoseTomasTocino/django-extensions,gvangool/django-extensions,kevgathuku/django-extens... | django_extensions/tests/json_field.py | django_extensions/tests/json_field.py | import unittest
from django.db import connection
from django.conf import settings
from django.core.management import call_command
from django.db.models import loading
from django.db import models
from django_extensions.db.fields.json import JSONField
class TestModel(models.Model):
a = models.IntegerField()
j... | import unittest
from django.db import connection
from django.conf import settings
from django.core.management import call_command
from django.db.models import loading
from django.db import models
from django_extensions.db.fields.json import JSONField
class TestModel(models.Model):
a = models.IntegerField()
j... | mit | Python |
42c0925b875858752dd86130c42818c43af28872 | change poke command to accept ping as well | mikevb1/discordbot,mikevb1/lagbot | cogs/meta.py | cogs/meta.py | from collections import OrderedDict
import datetime
from discord.ext import commands
import discord
class Meta:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def info(self):
"""Display bot information."""
source_link = 'https://github.com/mikevb1/discordbot'
... | from collections import OrderedDict
import datetime
import random
from discord.ext import commands
import discord
class Meta:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def info(self):
"""Display bot information."""
source_link = 'https://github.com/mikevb1... | mit | Python |
507acdd38ea3333c0b2794264a464678d1898d97 | fix issue with smoothing test: the smoothing region was too wide relative to the overall data length. | lzkelley/zcode,lzkelley/zcode | zcode/math/tests/test_numeric.py | zcode/math/tests/test_numeric.py | """Test methods for `zcode/math/math_core.py`.
Can be run with:
$ nosetests math/tests/test_math_core.py
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from numpy.testing import run_module_suite
from nose.tools import assert_true
import zcode
import zco... | """Test methods for `zcode/math/math_core.py`.
Can be run with:
$ nosetests math/tests/test_math_core.py
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from numpy.testing import run_module_suite
from nose.tools import assert_true
from zcode.math import ... | mit | Python |
f311dd7c560c3a86fa92a75aeb73a892a3be40ba | set maturity to Beta | OCA/account-fiscal-rule,OCA/account-fiscal-rule | account_avatax_sale/__manifest__.py | account_avatax_sale/__manifest__.py | {
"name": "Taxes on Sales Orders using Avalara Avatax API",
"version": "13.0.1.0.0",
"author": "Open Source Integrators, Fabrice Henrion, Odoo SA,"
" Odoo Community Association (OCA)",
"summary": "Sales Orders with automatic Tax application using Avatax",
"license": "AGPL-3",
"category": "Ac... | {
"name": "Taxes on Sales Orders using Avalara Avatax API",
"version": "13.0.1.0.0",
"author": "Open Source Integrators, Fabrice Henrion, Odoo SA,"
" Odoo Community Association (OCA)",
"summary": "Sales Orders with automatic Tax application using Avatax",
"license": "AGPL-3",
"category": "Ac... | agpl-3.0 | Python |
beff28a4d695b6448c3a1f81aa09bfc685a77e60 | Update kafka start/stop script | wangyangjun/StreamBench,wangyangjun/StreamBench,wangyangjun/StreamBench,wangyangjun/RealtimeStreamBenchmark,wangyangjun/StreamBench,wangyangjun/RealtimeStreamBenchmark,wangyangjun/RealtimeStreamBenchmark,wangyangjun/RealtimeStreamBenchmark,wangyangjun/RealtimeStreamBenchmark,wangyangjun/StreamBench,wangyangjun/StreamBe... | script/kafkaServer.py | script/kafkaServer.py | #!/bin/python
from __future__ import print_function
import subprocess
import sys
import json
from util import appendline, get_ip_address
if __name__ == "__main__":
# start server one by one
if len(sys.argv) < 2 or sys.argv[1] not in ['start', 'stop']:
sys.stderr.write("Usage: python %s start or stop\n" % (sys.arg... | #!/bin/python
from __future__ import print_function
import subprocess
import sys
import json
from util import appendline, get_ip_address
if __name__ == "__main__":
# start server one by one
if len(sys.argv) < 2 or sys.argv[1] not in ['start', 'stop']:
sys.stderr.write("Usage: python %s start or stop\n" % (sys.arg... | apache-2.0 | Python |
582f08f1d7bd52076832cc6031473c4363277cf6 | set the default flavor | sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary | conarycfg.py | conarycfg.py | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import deps
import deps.arch
import deps.deps
import os
import versions
import sys
class SrsConfiguration:
def read(self, file):
if os.path.exists(file):
f = open(file, "r")
for line in f:
self.configLine(line)
f.close()
def conf... | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import os
import versions
import sys
class SrsConfiguration:
def read(self, file):
if os.path.exists(file):
f = open(file, "r")
for line in f:
self.configLine(line)
f.close()
def configLine(self, line):
line = line.strip()
if n... | apache-2.0 | Python |
f195c01ad6a98b3454880106e95fe40bbeb14da0 | Fix unit test for essentia dissonance | Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide | tests/test_essentia_dissonance.py | tests/test_essentia_dissonance.py | #! /usr/bin/env python
from unit_timeside import unittest, TestRunner
from timeside.plugins.decoder.file import FileDecoder
from timeside.core import get_processor
from timeside.core.tools.test_samples import samples
class TestEssentiaDissonance(unittest.TestCase):
def setUp(self):
self.analyzer = get_... | #! /usr/bin/env python
from unit_timeside import unittest, TestRunner
from timeside.plugins.decoder.file import FileDecoder
from timeside.core import get_processor
from timeside.core.tools.test_samples import samples
class TestEssentiaDissonance(unittest.TestCase):
def setUp(self):
self.analyzer = get_... | agpl-3.0 | Python |
385d8a073d2996d639e8bc2af7d11658f28575d2 | add more tests | cglewis/vent,CyberReboot/vent,CyberReboot/vent,cglewis/vent,cglewis/vent,CyberReboot/vent | tests/unit/test_api_repository.py | tests/unit/test_api_repository.py | from vent.api.repository import Repository
from vent.api.system import System
def test_add():
""" Test the add function """
repo = Repository(System().manifest)
repo.add('https://github.com/cyberreboot/poseidon')
def test_update():
""" Test the update function """
repo = Repository(System().mani... | from vent.api.repository import Repository
from vent.api.system import System
def test_update():
""" Test the update class """
repo = Repository(System().manifest)
repo.update('foo')
| apache-2.0 | Python |
02a4e17ca4f370a6525fa71dd6e33b9802ff99ff | Add urls only if topology module is active | nemesisdesign/ansible-openwisp2,openwisp/ansible-openwisp2 | templates/openwisp2/urls.py | templates/openwisp2/urls.py | from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from openwisp_utils.admin_theme.admin import admin, openwisp_admin
openwisp_admin()
redirect_view = RedirectView... | from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from openwisp_utils.admin_theme.admin import admin, openwisp_admin
openwisp_admin()
redirect_view = RedirectView... | bsd-3-clause | Python |
40bcf570afbc8b990efd0c55c5d306fa19845e04 | add constant for reduced length | vipul-sharma20/compressr | constants.py | constants.py | """
constants for util and compressr script
"""
REDUCED = 'reduced'
SUFFIX_FLAG = 'suffix_flag'
PREFIX_FLAG = 'prefix_flag'
LENGTH = 'length'
REDUCED_LENGTH = 'reduced_length'
| """
constants for util and compressr script
"""
REDUCED = 'reduced'
SUFFIX_FLAG = 'suffix_flag'
PREFIX_FLAG = 'prefix_flag'
LENGTH = 'length'
| mit | Python |
a10b4d98e801fe4f23d8077a74fbbe19e8d10480 | Update poll.py | JeffreyPowell/pi-heating-hub,JeffreyPowell/pi-heating-hub,JeffreyPowell/pi-heating-hub | cron/poll.py | cron/poll.py | ERROR: type should be string, got "\nhttps://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html\n\n#SQL Connection Test\nimport MySQLdb\ndb = MySQLdb.connect(host=\"localhost\", user=\"pi\", passwd=\"password\", db=\"pi-heating-hub\")\n\ncur = db.cursor()\n\n" | apache-2.0 | Python | |
6b2efe0c5b323f650dc1aea217ea9d7270889bc7 | normalize tag names | MuckRock/muckrock,MuckRock/muckrock,MuckRock/muckrock,MuckRock/muckrock | src/muckrock/tags/models.py | src/muckrock/tags/models.py | """
Models for the tags application
"""
from django.contrib.auth.models import User
from django.db import models
from taggit.models import Tag as TaggitTag, GenericTaggedItemBase
class Tag(TaggitTag):
"""Custom Tag Class"""
user = models.ForeignKey(User, null=True, blank=True)
def save(self, *args, **kw... | """
Models for the tags application
"""
from django.contrib.auth.models import User
from django.db import models
from taggit.models import Tag as TaggitTag, GenericTaggedItemBase
class Tag(TaggitTag):
"""Custom Tag Class"""
user = models.ForeignKey(User, null=True, blank=True)
class Meta:
# pyli... | agpl-3.0 | Python |
960934fb4c9ead99091d32617d98c8d9c4f0d8a5 | include absolute urls in api responses | labkaxita/lakaxita,labkaxita/lakaxita,labkaxita/lakaxita | lakaxita/api.py | lakaxita/api.py | from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.api import Api
from lakaxita.news.models import News
from lakaxita.attachments.models import Attachment
from lakaxita.groups.models import Group
from lakaxita.gallery.models import Category
from lakaxita.lost_found.models import Ite... | from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.api import Api
from lakaxita.news.models import News
from lakaxita.attachments.models import Attachment
from lakaxita.groups.models import Group
from lakaxita.gallery.models import Category
from lakaxita.lost_found.models import Ite... | agpl-3.0 | Python |
590e9a6c97710097b2ab93fa194d7fa3cce9cb6c | add debug toolbar middleware to codeship settings | MuckRock/muckrock,MuckRock/muckrock,MuckRock/muckrock,MuckRock/muckrock | muckrock/settings/codeship.py | muckrock/settings/codeship.py | """
Settings used during testing of the application on codeship
Import from test settings
"""
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
from muckrock.settings.test import *
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
DATABASES['default'] = {
'NAME': ... | """
Settings used during testing of the application on codeship
Import from test settings
"""
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
from muckrock.settings.test import *
DATABASES['default'] = {
'NAME': 'test',
'USER': os.environ.get('PG_USER'),
'PASSWORD': os.environ.ge... | agpl-3.0 | Python |
853c727c472efc09df90cb016bd05f81d4cf5e8e | Print a line telling where the site is available at | cknv/beetle-preview | beetle_preview/__init__.py | beetle_preview/__init__.py | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config.get('port', 5000)
self.builder = builder
def serve(self):
os.chdir(self.director... | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config.get('port', 5000)
self.builder = builder
def serve(self):
os.chdir(self.director... | mit | Python |
2bf01da9e1f19dbbead83eaad69f264198900ac2 | allow I;16B as uint16 datatype | michigraber/neuralyzer,michigraber/neuralyzer | neuralyzer/io/plugins/tiff.py | neuralyzer/io/plugins/tiff.py |
from __future__ import print_function
from neuralyzer.io.loader import LoaderTemplate
FILE_EXTENSIONS = ('tiff', 'tif', )
DEFAULT_LIBRARY = 'PIL'
class Loader(LoaderTemplate):
@staticmethod
def get_data(filepath, library=DEFAULT_LIBRARY):
if library == 'PIL':
try:
... |
from __future__ import print_function
from neuralyzer.io.loader import LoaderTemplate
FILE_EXTENSIONS = ('tiff', 'tif', )
DEFAULT_LIBRARY = 'PIL'
class Loader(LoaderTemplate):
@staticmethod
def get_data(filepath, library=DEFAULT_LIBRARY):
if library == 'PIL':
try:
... | mit | Python |
9b2b91d50edfd07f36bae9d154128602bd855f8e | Update fusebmc.py | dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec | benchexec/tools/fusebmc.py | benchexec/tools/fusebmc.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.tools.esbmc as esbmc
class Tool(esbmc.Tool):
"""
This class ser... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.tools.esbmc as esbmc
class Tool(esbmc.Tool):
"""
This class ser... | apache-2.0 | Python |
bd7ccfd86af79c8ad2b1358b3a3e682e7ac88507 | update cache visualisation | tbicr/map-trends,tbicr/map-trends | vis_cache.py | vis_cache.py | import colorsys
import json
import string
import mercantile
import shapely.geometry
saturations = [0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]
brightness = [0.5, 0.65, 0.8, 0.95]
base = len(saturations)
offset = 1
sv = {i: (saturations[(i + offset) % base], brightness[(i + offset) // base])
for i, _ in enumerate(s... | import json
import itertools
import collections
import mercantile
import shapely.geometry
color = itertools.cycle([
'#%X%X%X' % (r, g, b)
for r in range(14, 4, -1)
for g in range(14, 4, -1)
for b in range(14, 4, -1)
if 20 < r + g + b < 36
])
def get_color():
for i in range(3):
r = n... | mit | Python |
1d3ab147de66ab7b684f6f2f7b4c0f6db9ff3f6b | Fix Atom syndication to aggregate syndicated sources individually. | chromakode/wake | wake/base.py | wake/base.py | from datetime import datetime
from urlparse import urljoin
from flask import Blueprint, render_template, abort, request, url_for
from werkzeug.contrib.atom import AtomFeed
from been import Been
blueprint = Blueprint('wake', __name__)
been = blueprint.been = Been()
store = blueprint.store = been.store
@blueprint... | from datetime import datetime
from urlparse import urljoin
from flask import Blueprint, render_template, abort, request, url_for
from werkzeug.contrib.atom import AtomFeed
from been import Been
blueprint = Blueprint('wake', __name__)
been = blueprint.been = Been()
store = blueprint.store = been.store
@blueprint... | bsd-3-clause | Python |
4b17332254541a348fc69857ea4ca78539f4b422 | call write_ditz after writing templates | GISAElkartea/django-project | django_project/pastertemplates.py | django_project/pastertemplates.py | from os import getlogin, path
from socket import gethostname
from datetime import datetime
from paste.script.templates import Template, var
class DjangoProjectTemplate(Template):
summary = 'Django project template'
use_cheetah = True
_template_dir = 'project_template'
vars = (
var('userna... | from os import getlogin, path
from socket import gethostname
from datetime import datetime
from paste.script.templates import Template, var
class DjangoProjectTemplate(Template):
summary = 'Django project template'
use_cheetah = True
_template_dir = 'project_template'
vars = (
var('userna... | agpl-3.0 | Python |
38359dc8c96eb0a305e57a3f3028ab9f4d73f1e2 | Fix Attr error message | laurent-george/weboob,willprice/weboob,frankrousseau/weboob,RouxRC/weboob,sputnick-dev/weboob,nojhan/weboob-devel,Konubinix/weboob,laurent-george/weboob,laurent-george/weboob,sputnick-dev/weboob,frankrousseau/weboob,willprice/weboob,RouxRC/weboob,Konubinix/weboob,Konubinix/weboob,nojhan/weboob-devel,sputnick-dev/weboob... | weboob/browser/filters/html.py | weboob/browser/filters/html.py | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | agpl-3.0 | Python |
389edb64e3bc2827ad6ed313de9656205843ddd1 | Mark all the tests on ASan bots non-critical due to a regression in the ASan runtime. | eunchong/build,eunchong/build,eunchong/build,eunchong/build | masters/master.chromium.memory/master_gatekeeper_cfg.py | masters/master.chromium.memory/master_gatekeeper_cfg.py | # Copyright (c) 2012 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.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If on... | # Copyright (c) 2012 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.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If on... | bsd-3-clause | Python |
00726313128334e825ab7ff8bcdd1244ceca111b | Add import | Pylons/kai,Pylons/kai | kai/controllers/articles.py | kai/controllers/articles.py | import logging
import re
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect_to
from pylons.decorators import rest
from tw.mods.pylonshf import validate
from kai.lib.base import BaseController, render
from kai.lib.decorators import in_group
from ka... | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect_to
from pylons.decorators import rest
from tw.mods.pylonshf import validate
from kai.lib.base import BaseController, render
from kai.lib.decorators import in_group
from kai.lib.help... | bsd-3-clause | Python |
1ceafadc042b9efc77d3d9d5fca9aff367369151 | Add multi_set action | Brickstertwo/git-commands | bin/utils/parse_actions.py | bin/utils/parse_actions.py | import argparse
def flag_as_value(value):
class FlagAsInt(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, value)
return FlagAsInt
def multi_set(dest1, value1):
class MultiSet(argparse.Action):
def __call__(sel... | import argparse
def flag_as_value(value):
class FlagAsInt(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, value)
return FlagAsInt
| mit | Python |
6fc26b08f6a49fc3d745b790f17f05392d2324d9 | fix deploy.py bug | coderzh/gohugo.org,coderzh/gohugo.org,coderzh/gohugo.org,coderzh/gohugo.org | deploy.py | deploy.py | #!/usr/bin/env python
# coding:utf-8
import os
import sys
import glob
import shutil
import subprocess
__author__ = 'coderzh'
class ChDir:
"""Context manager for changing the current working directory"""
def __init__(self, new_path):
self.newPath = os.path.expanduser(new_path)
d... | #!/usr/bin/env python
# coding:utf-8
import os
import sys
import glob
import shutil
import subprocess
__author__ = 'coderzh'
class ChDir:
"""Context manager for changing the current working directory"""
def __init__(self, new_path):
self.newPath = os.path.expanduser(new_path)
d... | mit | Python |
bb519d85faa4d2177f411eaebb96a827fb942cc5 | Add files via upload | enadol/fbjsonrobot | daterobot.py | daterobot.py | # !python3
import re
# import time
from fbjson import lstdate
# from jsonbuilderbis import match
lstdatenew = []
lstnuevafecha = []
for item in lstdate:
#regex para extraer p.e.
corte = re.compile('.*\s(.*)]')
#print(lstdate)
nada, fecha, nada2 = corte.split(item)
#print(fecha)
#para fecha sin . p... | # !python3
# import datetime
# import time
from fbjson import lstdate
# from jsonbuilderbis import match
lstdatenew = []
lstnuevafecha = []
for item in lstdate:
#print(lstdate)
fecha = item.split('.')
print(fecha)
#para fecha sin . p. ej [Fr ]
#partida = fecha[0].split(' ')
#print(partida)
#dia ... | mit | Python |
300dddc30eb9f44cc864a4214f24d3e478da1a52 | Add achievement deleting. | fi-ksi/web-backend,fi-ksi/web-backend | endpoint/achievement.py | endpoint/achievement.py | from db import session
import model
import util
import falcon
class Achievement(object):
def on_get(self, req, resp, id):
achievement = session.query(model.Achievement).get(id)
if achievement is None:
resp.status = falcon.HTTP_404
return
req.context['result'] = { 'achievement': util.achievement.to_json... | from db import session
import model
import util
import falcon
class Achievement(object):
def on_get(self, req, resp, id):
achievement = session.query(model.Achievement).get(id)
if achievement is None:
resp.status = falcon.HTTP_404
return
req.context['result'] = { 'achievement': util.achievement.to_json... | mit | Python |
81835f5c79fc0f2b014f1082c3e49ff141638309 | change middleware name | altaurog/django-shoogie | shoogie/middleware.py | shoogie/middleware.py | import sys
import traceback
from django import http
from django.conf import settings
from django.views import debug
from shoogie import models
class ExceptionLoggingMiddleware(object):
def process_exception(self, request, exception):
if settings.DEBUG:
return
exc_t... | import sys
import traceback
from django import http
from django.conf import settings
from django.views import debug
from shoogie import models
class DBExceptionMiddleware(object):
def process_exception(self, request, exception):
if settings.DEBUG:
return
exc_type, ... | mit | Python |
c977e0a6696d9fbe119fa22a33cca4ecf85aff8f | Update LoggerRateLimiter_001_space.py | Chasego/cod,cc13ny/algo,cc13ny/algo,Chasego/cod,Chasego/cod,Chasego/codirit,cc13ny/algo,Chasego/cod,cc13ny/algo,cc13ny/Allin,Chasego/cod,cc13ny/Allin,Chasego/codirit,cc13ny/Allin,cc13ny/algo,Chasego/codi,Chasego/codi,Chasego/codi,Chasego/codi,cc13ny/Allin,Chasego/codirit,Chasego/codirit,Chasego/codi,cc13ny/Allin,Chaseg... | leetcode/359-Logger-Rate-Limiter/LoggerRateLimiter_001_space.py | leetcode/359-Logger-Rate-Limiter/LoggerRateLimiter_001_space.py | class Logger(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.log_hash = {}
def shouldPrintMessage(self, timestamp, message):
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false... | class Logger(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.log_set = {}
def shouldPrintMessage(self, timestamp, message):
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false.... | mit | Python |
642518d196f0bd9695426fd52bfb58adfd80d23d | Implement tests for change_password | Elections-R-Us/Elections-R-Us,Elections-R-Us/Elections-R-Us,Elections-R-Us/Elections-R-Us,Elections-R-Us/Elections-R-Us | elections_r_us/tests/test_security.py | elections_r_us/tests/test_security.py | from __future__ import unicode_literals
from ..models import User
def test_user_gets_created(new_session):
"""Test that after create_user adds to the database."""
from ..security import create_user
create_user(new_session, 'username', 'password')
assert len(new_session.query(User).all()) == 1
def t... | from __future__ import unicode_literals
from ..models import User
def test_user_gets_created(new_session):
"""Test that after create_user adds to the database."""
from ..security import create_user
create_user(new_session, 'username', 'password')
assert len(new_session.query(User).all()) == 1
def t... | mit | Python |
5e837ddeca7f749206b76eb568e663e368973f02 | Add summary in l10n_ch_bank | BT-csanchez/l10n-switzerland,CompassionCH/l10n-switzerland,michl/l10n-switzerland,ndtran/l10n-switzerland,BT-ojossen/l10n-switzerland,CompassionCH/l10n-switzerland,eLBati/l10n-switzerland,cyp-opennet/ons_cyp_github,BT-fgarbely/l10n-switzerland,BT-ojossen/l10n-switzerland,cyp-opennet/ons_cyp_github,cgaspoz/l10n-switzerl... | l10n_ch_bank/__openerp__.py | l10n_ch_bank/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# En... | # -*- coding: utf-8 -*-
##############################################################################
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# En... | agpl-3.0 | Python |
7f735d75ea071c2544949ec4cadfa23fb4140e01 | Document the sandbox urls.py | thechampanurag/django-oscar,michaelkuty/django-oscar,Idematica/django-oscar,thechampanurag/django-oscar,monikasulik/django-oscar,QLGu/django-oscar,nickpack/django-oscar,makielab/django-oscar,jmt4/django-oscar,sasha0/django-oscar,ahmetdaglarbas/e-commerce,MatthewWilkes/django-oscar,bnprk/django-oscar,QLGu/django-oscar,j... | sites/sandbox/urls.py | sites/sandbox/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from oscar.app import shop
# These simply need to be imported into this namespace. Ignor... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from oscar.app import shop
from oscar.views ... | bsd-3-clause | Python |
7cda27f088487fb8d3e7f09596bee72a7f88aebd | update decorator | congminghaoxue/learn_python | decorator.py | decorator.py | #!/usr/bin/env python
# encoding: utf-8
# 函数装饰器
def memp(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
# 第一题
@memp
def fibonacci(n):
if n <= 1:
return 1
return fibonacci(n - 1) + fibonacci(n -... | #!/usr/bin/env python
# encoding: utf-8
# 函数装饰器
def memp(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
# 第一题
# @memp
def fibonacci(n):
if n <= 1:
return 1
return fibonacci(n - 1) + fibonacci(n... | apache-2.0 | Python |
d96e51d60d78b25f6a23938246c7b166ed1ef238 | fix peering | guthemberg/yanoama,guthemberg/yanoama | yanoama/system/peering.py | yanoama/system/peering.py | #!/usr/bin/env python
try:
import json
except ImportError:
import simplejson as json
#looking for yanoama module
def get_install_path():
try:
config_file = file('/etc/yanoama.conf').read()
config = json.loads(config_file)
except Exception, e:
print "There was an error in your... | #!/usr/bin/env python
try:
import json
except ImportError:
import simplejson as json
#looking for yanoama module
def get_install_path():
try:
config_file = file('/etc/yanoama.conf').read()
config = json.loads(config_file)
except Exception, e:
print "There was an error in your... | bsd-3-clause | Python |
b2703e712c1a392940b5ab63dd88cf73c5b6db0b | set LOCAL_T_MAX to 5 | miyosuda/async_deep_reinforce | constants.py | constants.py | # -*- coding: utf-8 -*-
LOCAL_T_MAX = 5 # repeat step size
RMSP_EPSILON = 1e-10 # epsilon parameter for RMSProp
CHECKPOINT_DIR = 'checkpoints'
LOG_FILE = 'tmp/a3c_log'
INITIAL_ALPHA_LOW = 1e-4 # log_uniform low limit for learning rate
INITIAL_ALPHA_HIGH = 1e-2 # log_uniform high limit for learning rate
PARALLEL_... | # -*- coding: utf-8 -*-
LOCAL_T_MAX = 20 # repeat step size
RMSP_EPSILON = 1e-10 # epsilon parameter for RMSProp
CHECKPOINT_DIR = 'checkpoints'
LOG_FILE = 'tmp/a3c_log'
INITIAL_ALPHA_LOW = 1e-4 # log_uniform low limit for learning rate
INITIAL_ALPHA_HIGH = 1e-2 # log_uniform high limit for learning rate
PARALLE... | apache-2.0 | Python |
c9ae61bd0aba076c3b6ae937672339bdd90877da | Bump version to 1.1.0.dev1 | gradel/django-sortedm2m,gregmuellegger/django-sortedm2m,gradel/django-sortedm2m,gregmuellegger/django-sortedm2m,gradel/django-sortedm2m,gregmuellegger/django-sortedm2m | sortedm2m/__init__.py | sortedm2m/__init__.py | # -*- coding: utf-8 -*-
__version__ = '1.1.0.dev1'
| # -*- coding: utf-8 -*-
__version__ = '1.1.0'
| bsd-3-clause | Python |
3970106ae0244c869cab790029664522a1e8910c | Fix migration 166 | wakermahmud/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,closeio/nylas... | migrations/versions/166_migrate_body_format.py | migrations/versions/166_migrate_body_format.py | """migrate body format
Revision ID: 3d4f5741e1d7
Revises: 29698176aa8d
Create Date: 2015-05-10 03:16:04.846781
"""
# revision identifiers, used by Alembic.
revision = '3d4f5741e1d7'
down_revision = '29698176aa8d'
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm imp... | """migrate body format
Revision ID: 3d4f5741e1d7
Revises: 29698176aa8d
Create Date: 2015-05-10 03:16:04.846781
"""
# revision identifiers, used by Alembic.
revision = '3d4f5741e1d7'
down_revision = '29698176aa8d'
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm imp... | agpl-3.0 | Python |
933c138cb1a7b7e5afc7405a45a8d6f8865d4670 | fix bug: argument encoding | hack4code/BlogSpider,hack4code/BlogSpider,wartalker/BlogSpider,wartalker/BlogSpider,hack4code/BlogSpider,alone-walker/BlogSpider,alone-walker/BlogSpider,wartalker/BlogSpider,wartalker/BlogSpider,alone-walker/BlogSpider,alone-walker/BlogSpider,hack4code/BlogSpider | spider/mydm/ai/tag.py | spider/mydm/ai/tag.py | # -*- coding: utf-8 -*-
import re
def verify_tags(tags):
return True if all(len(tag) < 32 for tag in tags) else False
class ReExtractor:
PATTERN = re.compile(r'tags?\s*:.*')
def extract(self, s):
tags = [tag.strip() for tag in s[s.find(':')+1:-1].split(',')]
return tags
def __cal... | # -*- coding: utf-8 -*-
import re
def verify_tags(tags):
return True if all(len(tag) < 32 for tag in tags) else False
class ReExtractor:
PATTERN = re.compile(r'tags?\s*:.*')
def extract(self, s):
tags = [tag.strip() for tag in s[s.find(':')+1:-1].split(',')]
return tags
def __cal... | mit | Python |
b02094fe025dca9ff64969a3141e87cba3bb82e1 | remove ts2dt | osoken/sqlite-tensor | sqlite_tensor/util.py | sqlite_tensor/util.py | # -*- coding: utf-8 -*-
import time
from datetime import datetime
import shortuuid
shortuuid.set_alphabet(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
)
def gen_id():
"""Return generated short UUID.
"""
return shortuuid.uuid()
def dt2ts(dt):
return int(time.mktime(dt.ti... | # -*- coding: utf-8 -*-
import time
from datetime import datetime
import shortuuid
shortuuid.set_alphabet(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
)
def gen_id():
"""Return generated short UUID.
"""
return shortuuid.uuid()
def dt2ts(dt):
return int(time.mktime(dt.ti... | mit | Python |
33020a8beafd64eb666e479897f9bab8606a463e | Change to relative import | drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject | sqlobject/__init__.py | sqlobject/__init__.py | """SQLObject"""
# Do import for namespace
# noqa is a directive for flake8 to ignore seemingly unused imports
from .__version__ import version, version_info # noqa
from .col import * # noqa
from .index import * # noqa
from .joins import * # noqa
from .main import * # noqa
from .sqlbuilder import AND, OR, NOT, I... | """SQLObject"""
# Do import for namespace
# noqa is a directive for flake8 to ignore seemingly unused imports
from __version__ import version, version_info # noqa
from col import * # noqa
from index import * # noqa
from joins import * # noqa
from main import * # noqa
from sqlbuilder import AND, OR, NOT, IN, LIK... | lgpl-2.1 | Python |
c4c200db7feedd6aa8babd6c5ec5b54ff368febe | Update convert simple | acuestap/smarttools_test,acuestap/smarttools_test,acuestap/smarttools_test | web/views.py | web/views.py | import datetime
from celery import chain
from .tasks import *
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
from .serializers import VideoSerializer
from django.shortcuts import render
from rest_frame... | import datetime
from celery import chain
from .tasks import *
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
from .serializers import VideoSerializer
from django.shortcuts import render
from rest_frame... | mit | Python |
9ac55bb9615bdda38df5d4cdc4357158e3b63f08 | Improve memoize | anaruse/chainer,wkentaro/chainer,cemoody/chainer,niboshi/chainer,hvy/chainer,muupan/chainer,chainer/chainer,cupy/cupy,ktnyt/chainer,chainer/chainer,laysakura/chainer,kiyukuta/chainer,truongdq/chainer,hvy/chainer,sinhrks/chainer,tscohen/chainer,sinhrks/chainer,sou81821/chainer,minhpqn/chainer,wkentaro/chainer,keisuke-um... | cupy/util.py | cupy/util.py | import atexit
import functools
from cupy import cuda
_memoized_funcs = []
def memoize(for_each_device=False):
"""Makes a function memoizing the result for each argument and device.
This decorator provides automatic memoization of the function result.
Args:
for_each_device (bool): If True, it ... | import atexit
import functools
from cupy import cuda
_memoized_funcs = []
def memoize(for_each_device=False):
"""Makes a function memoizing the result for each argument and device.
This decorator provides automatic memoization of the function result.
Args:
for_each_device (bool): If True, it ... | mit | Python |
a0862fbd206b8ffe46db98f7c9a04211552b5a9d | Add blank functions | import/component.py | component.py | component.py | # -*- coding: utf-8 -*-
"""
component
~~~~~~~~~
A module that implements various helper functions to assist in using
component(1) with a python workflow.
:copyright: (c) 2013 by Daniel Chatfield
:license: MIT, see LICENSE for details.
"""
def require(component_name):
pass
def export(object):... | # -*- coding: utf-8 -*-
"""
component
~~~~~~~~~
A module that implements various helper functions to assist in using
component(1) with a python workflow.
:copyright: (c) 2013 by Daniel Chatfield
:license: MIT, see LICENSE for details.
"""
| mit | Python |
c8753f7aafecac17d500ecf24488e885f7a97d31 | Update serializer -fix typo | icereval/osf.io,amyshi188/osf.io,mluo613/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,abought/osf.io,hmoco/osf.io,amyshi188/osf.io,chrisseto/osf.io,kwierman/osf.io,mluke93/osf.io,sloria/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,aaxelb/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,emetsger/osf.io... | website/addons/s3/serializer.py | website/addons/s3/serializer.py | from website.addons.base.serializer import OAuthAddonSerializer
from website.addons.s3 import utils
class S3Serializer(OAuthAddonSerializer):
addon_short_name = 's3'
REQUIRED_URLS = []
@property
def addon_serialized_urls(self):
node = self.node_settings.owner
user_settings = self.node... | from website.addons.base.serializer import OAuthAddonSerializer
from webs.addons.s3 import utils
class S3Serializer(OAuthAddonSerializer):
addon_short_name = 's3'
REQUIRED_URLS = []
@property
def addon_serialized_urls(self):
node = self.node_settings.owner
user_settings = self.node_se... | apache-2.0 | Python |
c33c527d08b5a7fbe414c07819c69bb884a2e977 | use my version, cit compiles on every system | jgsogo/queryset-cpp,jgsogo/queryset-cpp,jgsogo/queryset-cpp | conanfile.py | conanfile.py |
import os
import fnmatch
from conans import ConanFile, CMake
class QuerysetCPP(ConanFile):
name = "queryset-cpp"
version = "0.4"
generators = "cmake"
settings = "os", "compiler", "build_type", "arch"
exports = "conanfile.py", "CMakeLists.txt", "queryset/*", "tests/*"
url = "https://github.com... |
import os
import fnmatch
from conans import ConanFile, CMake
class QuerysetCPP(ConanFile):
name = "queryset-cpp"
version = "0.4"
generators = "cmake"
settings = "os", "compiler", "build_type", "arch"
exports = "conanfile.py", "CMakeLists.txt", "queryset/*", "tests/*"
url = "https://github.com... | mit | Python |
446d4919c5664ff27fc3bae09439000a1a46866b | Bump version: 0.0.7 -> 0.0.8 | polysquare/cmake-module-common | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.8"
class CMakeModuleCommonConan(ConanFile):
name = "cmake-module-common"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-module-com... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.7"
class CMakeModuleCommonConan(ConanFile):
name = "cmake-module-common"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-module-com... | mit | Python |
df3f94e96e5c28f8eff503b3ce264b2cf0cda209 | Make lint | ASCIT/donut,ASCIT/donut-python,ASCIT/donut-python,ASCIT/donut,ASCIT/donut | donut/modules/groups/constants.py | donut/modules/groups/constants.py | from enum import Enum
# Enum for group types in the groups table
class GroupTypes(Enum):
HOUSE = 'house'
COMMITTEE = 'committee' # i.e IHC, BOC, CRC
ASCIT = 'ascit' # For all groups that are involved with ascit
PUBLICATION = 'publication' # i.e The Tech
UGCURRENT = 'ugcurrent' # current studen... | from enum import Enum
# Enum for group types in the groups table
class GroupTypes(Enum):
HOUSE = 'house'
COMMITTEE = 'committee' # i.e IHC, BOC, CRC
ASCIT = 'ascit' # For all groups that are involved with ascit
PUBLICATION = 'publication' # i.e The Tech
UGCURRENT = 'ugcurrent' # current student gro... | mit | Python |
22549161a50b26c21343b9bec8a9e075dd46b223 | fix unittest to filter a request with same url as start_requests. rel r868. ref #49 | liyy7/scrapy,jeffreyjinfeng/scrapy,zhangtao11/scrapy,pablohoffman/scrapy,cyberplant/scrapy,famorted/scrapy,nfunato/scrapy,moraesnicol/scrapy,nikgr95/scrapy,elacuesta/scrapy,emschorsch/scrapy,Lucifer-Kim/scrapy,jamesblunt/scrapy,pranjalpatil/scrapy,Parlin-Galanodel/scrapy,eliasdorneles/scrapy,AaronTao1990/scrapy,scorphu... | scrapy/trunk/scrapy/tests/test_spidermiddleware_duplicatesfilter.py | scrapy/trunk/scrapy/tests/test_spidermiddleware_duplicatesfilter.py | import unittest
from scrapy.spider import spiders
from scrapy.http import Request, Response
from scrapy.contrib.spidermiddleware.duplicatesfilter import DuplicatesFilterMiddleware, SimplePerDomainFilter
class DuplicatesFilterMiddlewareTest(unittest.TestCase):
def setUp(self):
spiders.spider_modules = ['s... | import unittest
from scrapy.spider import spiders
from scrapy.http import Request, Response
from scrapy.contrib.spidermiddleware.duplicatesfilter import DuplicatesFilterMiddleware, SimplePerDomainFilter
class DuplicatesFilterMiddlewareTest(unittest.TestCase):
def setUp(self):
spiders.spider_modules = ['s... | bsd-3-clause | Python |
2af01c0293db53dc80c552df3986d0e088b65b76 | improve player params extraction(closes #22638) | Orochimarufan/youtube-dl,rg3/youtube-dl,remitamine/youtube-dl,remitamine/youtube-dl,rg3/youtube-dl,Tatsh/youtube-dl,yan12125/youtube-dl,ozburo/youtube-dl,Tatsh/youtube-dl,Orochimarufan/youtube-dl,erikdejonge/youtube-dl,erikdejonge/youtube-dl,nyuszika7h/youtube-dl,yan12125/youtube-dl,spvkgn/youtube-dl,spvkgn/youtube-dl,... | youtube_dl/extractor/bokecc.py | youtube_dl/extractor/bokecc.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_parse_qs
from ..utils import ExtractorError
class BokeCCBaseIE(InfoExtractor):
def _extract_bokecc_formats(self, webpage, video_id, format_id=None):
player_params_str = self._h... | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_parse_qs
from ..utils import ExtractorError
class BokeCCBaseIE(InfoExtractor):
def _extract_bokecc_formats(self, webpage, video_id, format_id=None):
player_params_str = self._h... | unlicense | Python |
d72aea25f2a6d18c7f6d213144e0861fac65a4f9 | Use named match for Gravatar email | Cheppers/zulip,eeshangarg/zulip,jimmy54/zulip,stamhe/zulip,jeffcao/zulip,ufosky-server/zulip,yuvipanda/zulip,kokoar/zulip,zachallaun/zulip,rht/zulip,suxinde2009/zulip,easyfmxu/zulip,timabbott/zulip,sup95/zulip,seapasulli/zulip,yocome/zulip,bowlofstew/zulip,LAndreas/zulip,samatdav/zulip,littledogboy/zulip,niftynei/zulip... | zephyr/lib/bugdown/__init__.py | zephyr/lib/bugdown/__init__.py | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
img = markdown.util.etree.Element('img')
img.set('class', 'message_body_gravatar img-rounded')
img... | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
# NB: the first match of our regex is match.group(2) due to
# markdown internal matches
img = mark... | apache-2.0 | Python |
af16a55be73fd88c7a07faee13917092109ecb72 | Add test for iCal export for workouts | wger-project/wger,wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,wger-project/wger,DeveloperMal/wger,kjagoo/wger_stark,kjagoo/wger_stark,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger,DeveloperMal/wger,kjagoo/wger_stark,petervanderdoes/wger,wger-project/wger,rolandgeider/wger,DeveloperMal/wger,Devel... | wger/manager/tests/test_ical.py | wger/manager/tests/test_ical.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger W... | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger W... | agpl-3.0 | Python |
6fdb04e47bdfc80e17a8c34cebabec98c3c5ee0e | Increase filters | israelg99/eva | eva/models/pixelcnn.py | eva/models/pixelcnn.py | from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def Pi... | from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def Pi... | apache-2.0 | Python |
ed1de617b5fcca499f9ca620ea0d16641e113b30 | Fix wiimoteac | legonigel/wii-drone-on | wiimoteAC.py | wiimoteAC.py | #! /usr/bin/python
import cwiid
import time
class InputWiimoteAC(object):
def makeConnection(self):
print "Press 1 + 2 on the wiimote for Acceleration"
try:
wm = cwiid.Wiimote()
except RuntimeError:
wm = None
else:
wm.led = 2
#wm.enable(cwiid.FLAG_MOTIONPLUS)
wm.rpt_mode = cwiid.RPT_BTN | cwiid... | #! /usr/bin/python
import cwiid
import time
class InputWiimoteAC(object):
def makeConnection(self):
print "Press 1 + 2 on the wiimote for Acceleration"
try:
wm = cwiid.Wiimote()
except RuntimeError:
wm = None
else:
wm.led = 2
#wm.enable(cwiid.FLAG_MOTIONPLUS)
wm.rpt_mode = cwiid.RPT_BTN | cwiid... | mit | Python |
0866b795d3da3f0e3b20759ad597b3b2ca0be126 | enable `/gettext/{aoid}` route | jar3b/py-phias,jar3b/py-phias,jar3b/py-phias,jar3b/py-phias | aore/app.py | aore/app.py | import asyncpg
from aiohttp import web
from aiohttp_pydantic import oas
from settings import AppConfig
from . import log
from .search import FiasFactory
from .views import NormalizeAoidView, error_middleware, ExpandAoidView, ConvertAoidView, FindAoView, cors_middleware, \
GetAoidTextView
async def init_fias(app:... | import asyncpg
from aiohttp import web
from aiohttp_pydantic import oas
from settings import AppConfig
from . import log
from .search import FiasFactory
from .views import NormalizeAoidView, error_middleware, ExpandAoidView, ConvertAoidView, FindAoView, cors_middleware
async def init_fias(app: web.Application) -> No... | bsd-3-clause | Python |
44bfdc7f81183c3a4aa79b0075c2ad2288026e14 | update backend interface | bedaes/burp-ui,bedaes/burp-ui,bedaes/burp-ui,bedaes/burp-ui | burpui/misc/backend/interface.py | burpui/misc/backend/interface.py | # -*- coding: utf8 -*-
class BUIbackend:
def __init__(self, app=None, host='127.0.0.1', port=4972):
self.app = app
self.host = host
self.port = port
def status(self, query='\n', agent=None):
raise NotImplementedError("Sorry, the current Backend does not implement this method!")... | # -*- coding: utf8 -*-
class BUIbackend:
def __init__(self, app=None, host='127.0.0.1', port=4972):
self.app = app
self.host = host
self.port = port
def status(self, query='\n', agent=None):
raise NotImplementedError("Sorry, the current Backend does not implement this method!")... | bsd-3-clause | Python |
059d445f40d7c829b2d5888e1c0e700e03552d47 | Fix tag params in user directory | IndiciumSRL/wirecurly | wirecurly/directory/__init__.py | wirecurly/directory/__init__.py | import logging
log = logging.getLogger(__name__)
__all__ = ['User']
class User(object):
"""A user object for the directory"""
def __init__(self, user_id, password=None):
super(User, self).__init__()
self.user_id = user_id
self.variables = []
self.parameters = []
if password:
self.addParameter('passw... | import logging
log = logging.getLogger(__name__)
__all__ = ['User']
class User(object):
"""A user object for the directory"""
def __init__(self, user_id, password=None):
super(User, self).__init__()
self.user_id = user_id
self.variables = []
self.parameters = []
if password:
self.addParameter('passw... | mpl-2.0 | Python |
dbe28da1be7415ad5f496b983c0345c5e9714fb9 | Add fake devices for non-existant serial ports. | zlfben/gem5,joerocklin/gem5,sobercoder/gem5,HwisooSo/gemV-update,kaiyuanl/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,SanchayanMaity/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,austinharris/gem5-riscv,samueldotj/TeeRISC-Simulator,markoshorro/gem5,gedare/gem5,powerjg/gem5-ci-test,rallylee/gem5,markoshorro/gem5,gedare/ge... | src/dev/x86/Pc.py | src/dev/x86/Pc.py | # Copyright (c) 2008 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list ... | # Copyright (c) 2008 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list ... | bsd-3-clause | Python |
b474c7368f3a8152296acf9cad7459510b71ada5 | Fix SSHOpener to use the new ClosingSubFS | althonos/fs.sshfs | fs/opener/sshfs.py | fs/opener/sshfs.py | from ._base import Opener
from ._registry import registry
from ..subfs import ClosingSubFS
@registry.install
class SSHOpener(Opener):
protocols = ['ssh']
@staticmethod
def open_fs(fs_url, parse_result, writeable, create, cwd):
from ..sshfs import SSHFS
ssh_host, _, dir_path = parse_result.... | from ._base import Opener
from ._registry import registry
@registry.install
class SSHOpener(Opener):
protocols = ['ssh']
@staticmethod
def open_fs(fs_url, parse_result, writeable, create, cwd):
from ..sshfs import SSHFS
ssh_host, _, dir_path = parse_result.resource.partition('/')
... | lgpl-2.1 | Python |
f4c9b193bda5836888e8b90c907bcf5d695401b0 | update git push | munisisazade/developer_portal,munisisazade/developer_portal,munisisazade/developer_portal | api/urls.py | api/urls.py | from django.conf.urls import url, include
from api.views import UserList,BrandDetail,NewsList,ArticleDetail
urlpatterns = [
url(r'^user/(?P<pk>[0-9]+)/$', BrandDetail.as_view(), name='user-detail'),
url(r'^user-list/$', UserList.as_view(), name='user-list'),
url(r'^news-list/$', NewsList.as_view(), name='... | from django.conf.urls import url, include
from rest_framework_jwt.views import obtain_jwt_token
from api.views import UserList,BrandDetail,NewsList,ArticleDetail
urlpatterns = [
url(r'^user/(?P<pk>[0-9]+)/$', BrandDetail.as_view(), name='user-detail'),
url(r'^user-list/$', UserList.as_view(), name='user-list'... | mit | Python |
ad331ef64849ec568fc406183c06a1c9c6a34d44 | Change constants | anishathalye/evolution-chamber,techx/hackmit-evolution-chamber,anishathalye/evolution-chamber,techx/hackmit-evolution-chamber,anishathalye/evolution-chamber,techx/hackmit-evolution-chamber,techx/hackmit-evolution-chamber,anishathalye/evolution-chamber | constants.py | constants.py | class Constants:
APP_NAME = "EVOLUTION_CHAMBER"
COMPARISONS_PER_GENERATION = 100
POPULATION_SIZE = 20
KILL_SIZE = 10
| class Constants:
APP_NAME = "EVOLUTION_CHAMBER"
COMPARISONS_PER_GENERATION = 50
POPULATION_SIZE = 15
KILL_SIZE = 8
| mit | Python |
647e831864ce932278d8c705626f07a96fc56491 | Fix publisher method is published, set tzinfo none | williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,opps/opps,jeanmask/opps | opps/core/models/publisher.py | opps/core/models/publisher.py | #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetim... | #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetim... | mit | Python |
80f3d630673ccd126b3e7cc64970ce3f7feac4d0 | Add flask command to change user password | openmaraude/APITaxi,openmaraude/APITaxi | APITaxi2/commands/users.py | APITaxi2/commands/users.py | import uuid
import click
from flask import Blueprint, current_app
from flask.cli import with_appcontext
from flask_security.utils import hash_password
from APITaxi_models2 import db, Role, User
blueprint = Blueprint('commands_users', __name__, cli_group=None)
@with_appcontext
def valid_role(value):
roles = [r... | import uuid
import click
from flask import Blueprint, current_app
from flask.cli import with_appcontext
from flask_security.utils import hash_password
from APITaxi_models2 import db, Role, User
blueprint = Blueprint('commands_users', __name__, cli_group=None)
@with_appcontext
def valid_role(value):
roles = [r... | agpl-3.0 | Python |
0ed979ea3e25661c4fab254c758a3c2db1f38d8a | Fix PytzUsageWarning for Python versions >= 3.6 (#1062) | scrapinghub/dateparser | dateparser/date_parser.py | dateparser/date_parser.py | import sys
from tzlocal import get_localzone
from .timezone_parser import pop_tz_offset_from_string
from .utils import strip_braces, apply_timezone, localize_timezone
from .conf import apply_settings
class DateParser:
@apply_settings
def parse(self, date_string, parse_method, settings=None):
date_s... | from tzlocal import get_localzone
from .timezone_parser import pop_tz_offset_from_string
from .utils import strip_braces, apply_timezone, localize_timezone
from .conf import apply_settings
class DateParser:
@apply_settings
def parse(self, date_string, parse_method, settings=None):
date_string = str(... | bsd-3-clause | Python |
0c75a5922b506ea12c9bdb69178df91f967eb756 | Update CLI example mgp25/Instagram-API@d7eda0d105b2fb6ff15e757323fa146628361275 | danleyb2/Instagram-API | examples/checkpoint.py | examples/checkpoint.py | from InstagramAPI import Checkpoint
debug = True
print("####################")
print("# #")
print("# CHECKPOINT #")
print("# #")
print("####################")
username = raw_input("\n\nYour username: ").strip()
if username == '':
print("\n\nYou have to set your username\... | from InstagramAPI import Checkpoint
username = '' # // Your username
settingsPath = None
debug = False
c = Checkpoint(username, settingsPath, debug)
print("####################")
print("# #")
print("# CHECKPOINT #")
print("# #")
print("####################")
if username == '... | mit | Python |
9245dc994735e7060414eaa4b3df1b6f2447414f | Add some docstrings | louisswarren/hieretikz | hierarchy.py | hierarchy.py | '''Reason about a directed graph in which the (non-)existance of some edges
must be inferred by the disconnectedness of certain vertices'''
def transitive_closure_set(vertices, edges):
'''Find the transitive closure of a set of vertices.'''
neighbours = {b for a, b in edges if a in vertices}
if neighbours.... | """Reason about a directed graph in which the (non-)existance of some edges
must be inferred by the disconnectedness of certain vertices"""
def transitive_closure_set(vertices, edges):
neighbours = {b for a, b in edges if a in vertices}
if neighbours.issubset(vertices):
return vertices
return trans... | mit | Python |
c97e2a9f0bac1c0d15d5e4aea1a420df79dab689 | Add credit API support added | chargebee/chargebee-python | chargebee/models/subscription.py | chargebee/models/subscription.py | import json
from chargebee.model import Model
from chargebee import request
from chargebee import APIError
class Subscription(Model):
class Addon(Model):
fields = ["id", "quantity"]
pass
class Coupon(Model):
fields = ["coupon_id", "apply_till", "applied_count"]
pass
fields = ["id",... | import json
from chargebee.model import Model
from chargebee import request
from chargebee import APIError
class Subscription(Model):
class Addon(Model):
fields = ["id", "quantity"]
pass
class Coupon(Model):
fields = ["coupon_id", "apply_till", "applied_count"]
pass
fields = ["id",... | mit | Python |
9c008e02214cb3f126c6e7fd02b7ffcdebf916eb | Fix test imports | choderalab/yank,choderalab/yank | Yank/tests/test_pipeline.py | Yank/tests/test_pipeline.py | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test pipeline functions in pipeline.py.
"""
# =================================================================... | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test pipeline functions in pipeline.py.
"""
# =================================================================... | mit | Python |
311833200540fe1f52345a9e229755e7b523341b | Use str(blah) instead of blah.__str__() as its more idiomatic | florianm/datacats,datacats/datacats,datawagovau/datacats,dborzov/datacats,datacats/datacats,JackMc/datacats,florianm/datacats,poguez/datacats,wardi/datacats,JackMc/datacats,poguez/datacats,wardi/datacats,JJediny/datacats,reneenoble/datacats,reneenoble/datacats,dborzov/datacats,JJediny/datacats,deniszgonjanin/datacats,d... | datacats/error.py | datacats/error.py | from clint.textui import colored
class DatacatsError(Exception):
def __init__(self, message, format_args=(), parent_exception=None):
self.message = message
if parent_exception and hasattr(parent_exception, 'user_description'):
vals = {
"original": self.message,
... | from clint.textui import colored
class DatacatsError(Exception):
def __init__(self, message, format_args=(), parent_exception=None):
self.message = message
if parent_exception and hasattr(parent_exception, 'user_description'):
vals = {
"original": self.message,
... | agpl-3.0 | Python |
3c9b61c4ef302cf3463f8d82b7976be7e3400147 | Add a note to compat.py. | Julian/jsonschema,Julian/jsonschema,python-jsonschema/jsonschema | jsonschema/compat.py | jsonschema/compat.py | """
Python 2/3 compatibility helpers.
Note: This module is *not* public API.
"""
import contextlib
import operator
import sys
try:
from collections.abc import MutableMapping, Sequence # noqa
except ImportError:
from collections import MutableMapping, Sequence # noqa
PY3 = sys.version_info[0] >= 3
if PY3:... | import contextlib
import operator
import sys
try:
from collections.abc import MutableMapping, Sequence # noqa
except ImportError:
from collections import MutableMapping, Sequence # noqa
PY3 = sys.version_info[0] >= 3
if PY3:
zip = zip
from functools import lru_cache
from io import StringIO as ... | mit | Python |
834c451641dfbaf8b275fbb63351b10d34796cfd | Update config | Osirium/vcdriver,Lantero/vcenter-driver,Lantero/vcdriver | vcdriver/config.py | vcdriver/config.py | import os
# Session config
HOST = os.getenv('VCDRIVER_HOST')
PORT = os.getenv('VCDRIVER_PORT')
USERNAME = os.getenv('VCDRIVER_USERNAME')
PASSWORD = os.getenv('VCDRIVER_PASSWORD')
# Virtual machine config
RESOURCE_POOL = os.getenv('VCDRIVER_RESOURCE_POOL')
DATA_STORE = os.getenv('VCDRIVER_DATA_STORE')
FOLDER = os.gete... | from getpass import getpass
import os
# Session config
HOST = os.getenv('VCDRIVER_HOST')
PORT = os.getenv('VCDRIVER_PORT')
USERNAME = os.getenv('VCDRIVER_USERNAME')
PASSWORD = os.getenv('VCDRIVER_PASSWORD') or getpass('Vcenter password: ')
# Virtual machine config
RESOURCE_POOL = os.getenv('VCDRIVER_RESOURCE_POOL')
D... | mit | Python |
b7ff4eae91b010e29f03a68e842bb342fd65480c | simplify formular | voc/voctomix,voc/voctomix,h01ger/voctomix,h01ger/voctomix | voctogui/lib/audioleveldisplay.py | voctogui/lib/audioleveldisplay.py | import logging, math
from gi.repository import Gst, Gtk
class AudioLevelDisplay(object):
""" Displays a Level-Meter of another VideoDisplay into a GtkWidget """
def __init__(self, drawing_area):
self.log = logging.getLogger('AudioLevelDisplay[%s]' % drawing_area.get_name())
self.drawing_area = drawing_area
... | import logging, math
from gi.repository import Gst, Gtk
class AudioLevelDisplay(object):
""" Displays a Level-Meter of another VideoDisplay into a GtkWidget """
def __init__(self, drawing_area):
self.log = logging.getLogger('AudioLevelDisplay[%s]' % drawing_area.get_name())
self.drawing_area = drawing_area
... | mit | Python |
1941b0bbdc356245eff4d66cc44d18a2396a5493 | fix test | syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin | test/functional/feature_asset.py | test/functional/feature_asset.py | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import SyscoinTestFramework
from test_framework.util import assert_equ... | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import SyscoinTestFramework
from test_framework.util import wait_until... | mit | Python |
7b4fb97fde74d7d4e4d441900c66f6eb8c04dc13 | create Jupyterhub log file at /var/log | felipenoris/math-server-docker,felipenoris/math-server-docker,felipenoris/AWSFinance,felipenoris/AWSFinance | jupyterhub_config.py | jupyterhub_config.py |
# Whitelist of environment variables for the subprocess to inherit
# c.Spawner.env_keep = ['PATH', 'PYTHONPATH', 'CONDA_ROOT', 'CONDA_DEFAULT_ENV', 'VIRTUAL_ENV', 'LANG', 'LC_ALL']
c.Spawner.env_keep = [ 'PATH', 'LD_LIBRARY_PATH', 'JAVA_HOME', 'CPATH', 'CMAKE_ROOT', 'GOROOT' ]
# set of usernames of admin users
#
# I... |
# Whitelist of environment variables for the subprocess to inherit
# c.Spawner.env_keep = ['PATH', 'PYTHONPATH', 'CONDA_ROOT', 'CONDA_DEFAULT_ENV', 'VIRTUAL_ENV', 'LANG', 'LC_ALL']
c.Spawner.env_keep = [ 'PATH', 'LD_LIBRARY_PATH', 'JAVA_HOME', 'CPATH', 'CMAKE_ROOT', 'GOROOT' ]
# set of usernames of admin users
#
# I... | mit | Python |
e3822dee395a2cfa7d3b98e84f01a09c66309364 | fix pep8 errors | pydanny/django-admin2,pydanny/django-admin2 | example/example/urls.py | example/example/urls.py | from __future__ import unicode_literals
from blog.views import BlogListView, BlogDetailView
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from djadmin2.site import djadmin2_site
djadmin2_site.autodiscover()
url... | from __future__ import unicode_literals
from blog.views import BlogListView, BlogDetailView
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from djadmin2.site import djadmin2_site
admin.autodiscover()
djadmin2_site... | bsd-3-clause | Python |
6adcc0875218a7e00e260885c2b3caf0fc179122 | Fix #24 | NLeSC/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint | fdp-api/python/tests/dump_metadata.py | fdp-api/python/tests/dump_metadata.py | #
# This script creates dump files of metadata in different formats upon requests to FDP.
#
import os
import six
from rdflib import Graph
from logging import getLogger, StreamHandler, INFO
from myglobals import *
if six.PY2:
from urllib2 import (urlopen, urlparse, Request)
urljoin = urlparse.urljoin
urlp... | #
# This script creates dump files of metadata in different formats upon requests to FDP.
#
from os import path, makedirs
from urllib2 import urlopen, urlparse, Request
from rdflib import Graph
from logging import getLogger, StreamHandler, INFO
from myglobals import *
logger = getLogger(__name__)
logger.setLevel(INF... | apache-2.0 | Python |
b6ef71dd8754bf33672f9954cd1d41cce1773599 | fix import statement | e2dmax/Python_SI1145,THP-JOE/Python_SI1145 | examples/simpletest.py | examples/simpletest.py | #!/usr/bin/python
# Author: Joe Gutting
# With use of Adafruit SI1145 library for Arduino, Adafruit_GPIO.I2C & BMP Library by Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wi... | #!/usr/bin/python
# Author: Joe Gutting
# With use of Adafruit SI1145 library for Arduino, Adafruit_GPIO.I2C & BMP Library by Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wi... | mit | Python |
1c35f0c68502ab4a41fec2ae9393066a8195b3f8 | Update simpletest.py | adafruit/Adafruit_Python_BMP,DirkUK/Adafruit_Python_BMP,campenberger/Adafruit_Python_BMP | examples/simpletest.py | examples/simpletest.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # Can enable debug output by uncommenting:
#import logging
#logging.basicConfig(level=logging.DEBUG)
import Adafruit_BMP.BMP085 as BMP085
# Default constructor will pick a default I2C bus.
#
# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library wi... | mit | Python |
d21648ab963e5ebdf2729e528fc31c8a9ce93772 | update speed_test | Koheron/lase | examples/speed_test.py | examples/speed_test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import initExample
import os
import time
import numpy as np
import matplotlib.pyplot as plt
from utilities import load_instrument
from ldk.drivers import Oscillo
cmd = os.getenv('CMD','get_adc')
def speed_test(host, n_pts=1000):
time_array = np.zeros(n_pts)
clie... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import initExample
import os
import time
import numpy as np
import matplotlib.pyplot as plt
from utilities import load_instrument
from ldk.drivers import Oscillo
def speed_test(host, n_pts=1000):
time_array = np.zeros(n_pts)
client = load_instrument(host, instrum... | mit | Python |
a603e70d4e955c0bd19630a61ba0bd3db5575d6d | fix _cost_func test | benvanwerkhoven/kernel_tuner | test/strategies/test_minimize.py | test/strategies/test_minimize.py | from __future__ import print_function
from collections import OrderedDict
from kernel_tuner.strategies import minimize
from kernel_tuner.interface import Options
try:
from mock import Mock
except ImportError:
from unittest.mock import Mock
def fake_runner():
fake_result = {'time': 5}
runner = Mock(... | from __future__ import print_function
from collections import OrderedDict
from kernel_tuner.strategies import minimize
from kernel_tuner.interface import Options
try:
from mock import Mock
except ImportError:
from unittest.mock import Mock
def fake_runner():
fake_result = {'time': 5}
runner = Mock(... | apache-2.0 | Python |
34d0248510b536483b97e5786ef1a81c2d67dbe1 | add MWPotential | followthesheep/galpy,followthesheep/galpy,jobovy/galpy,followthesheep/galpy,jobovy/galpy,jobovy/galpy,followthesheep/galpy,jobovy/galpy | galpy/potential.py | galpy/potential.py | from galpy.potential_src import Potential
from galpy.potential_src import planarPotential
from galpy.potential_src import linearPotential
from galpy.potential_src import verticalPotential
from galpy.potential_src import MiyamotoNagaiPotential
from galpy.potential_src import LogarithmicHaloPotential
from galpy.potential... | from galpy.potential_src import Potential
from galpy.potential_src import planarPotential
from galpy.potential_src import linearPotential
from galpy.potential_src import verticalPotential
from galpy.potential_src import MiyamotoNagaiPotential
from galpy.potential_src import LogarithmicHaloPotential
from galpy.potential... | bsd-3-clause | Python |
6b75e9d7e1c84e5ecc8529618260fb4e6a72ce73 | Update package documentation. | eikonomega/flask-authorization-panda | flask_authorization_panda/__init__.py | flask_authorization_panda/__init__.py | """
**Flask-Authorization-Panda is a Flask extension that provides decorators
for various authentication methods for RESTful web services.
Currently, only HTTP Basic Authentication is supported. **
Usage
-----
>>> from flask.ext.flask_authorization_panda import basic_auth
During app initialization, store your r... | """
**Flask-Authorization-Panda provides easy loading and access to the data elements of
JSON based configuration files.**
Usage
-----
Assuming that an environment variable 'SHARED_CONFIG_FILES' exists
and points to a directory containing multiple JSON files, including
the following::
ldap.json
{
"... | mit | Python |
5409845ebf4c5dae7825f8b3f41f6ba063f1360d | Update __init__.py | kulkarnimandar/SU2,KDra/SU2,chenbojian/SU2,KDra/SU2,Heathckliff/SU2,opfeifle/SU2,drewkett/SU2,cspode/SU2,pawhewitt/Dev,shivajimedida/SU2,pawhewitt/Dev,jlabroquere/SU2,bankur16/SU2,srange/SU2,Heathckliff/SU2,shivajimedida/SU2,shivajimedida/SU2,opfeifle/SU2,shivajimedida/SU2,jlabroquere/SU2,srange/SU2,huahbo/SU2,hlkline/... | SU2_PY/SU2/util/__init__.py | SU2_PY/SU2/util/__init__.py | from switch import switch
from bunch import Bunch as bunch
from ordered_bunch import OrderedBunch as ordered_bunch
from plot import write_plot, tecplot, paraview
from lhc_unif import lhc_unif
from mp_eval import mp_eval
from which import which
|
from switch import switch
from bunch import Bunch as bunch
from ordered_bunch import OrderedBunch as ordered_bunch
from plot import write_plot, tecplot, paraview
from lhc_unif import lhc_unif
from mp_eval import mp_eval | lgpl-2.1 | Python |
cee62120cefa8c773795d2b4e24fb4df40b6532e | Remove declaration of the handlers | dapeng0802/django-blog-zinnia,petecummings/django-blog-zinnia,petecummings/django-blog-zinnia,bywbilly/django-blog-zinnia,Fantomas42/django-blog-zinnia,Maplecroft/django-blog-zinnia,aorzh/django-blog-zinnia,petecummings/django-blog-zinnia,Fantomas42/django-blog-zinnia,Maplecroft/django-blog-zinnia,extertioner/django-bl... | demo/urls.py | demo/urls.py | """Urls for the demo of Zinnia"""
from django.conf import settings
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from django.conf.urls import patterns
from django.views.generic.base import RedirectView
from zinnia.sitemaps import TagSitemap
from zinnia.sitemaps ... | """Urls for the demo of Zinnia"""
from django.conf import settings
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from django.conf.urls import patterns
from django.views.generic.base import RedirectView
from zinnia.sitemaps import TagSitemap
from zinnia.sitemaps ... | bsd-3-clause | Python |
14278fdf0a4f741203b91ca2869f8b4b93fb9fd5 | Allow file URLs | skosukhin/spack,mfherbst/spack,tmerrick1/spack,iulian787/spack,lgarren/spack,LLNL/spack,EmreAtes/spack,lgarren/spack,tmerrick1/spack,TheTimmy/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,skosukhin/spack,mfherbst/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,iulian787/spack,TheTimmy/spack,tmerrick1/spack,lga... | lib/spack/spack/validate.py | lib/spack/spack/validate.py | ##############################################################################
# Copyright (c) 2013, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Written by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
... | ##############################################################################
# Copyright (c) 2013, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Written by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
... | lgpl-2.1 | Python |
48df91d48b21fecfbdb87a0e8b011956594a74c2 | Add surface area class (#2183) | TheAlgorithms/Python | maths/area.py | maths/area.py | """
Find the area of various geometric shapes
"""
from math import pi
from typing import Union
def surface_area_cube(side_length: Union[int, float]) -> float:
"""
Calculate the Surface Area of a Cube.
>>> surface_area_cube(1)
6
>>> surface_area_cube(3)
54
"""
return 6 ... | """
Find the area of various geometric shapes
"""
import math
def area_rectangle(base, height):
"""
Calculate the area of a rectangle
>> area_rectangle(10,20)
200
"""
return base * height
def area_square(side_length):
"""
Calculate the area of a square
>>>... | mit | Python |
94b3aa469e3a37a5c0cffa565a139b6b9607e54e | use interim setting for slave location | sassoftware/mcp,sassoftware/mcp | mcp/config.py | mcp/config.py | #
# Copyright (c) 2005-2006 rPath, Inc.
#
# All rights reserved
#
import os
from conary import conarycfg
from conary.lib import cfgtypes
class MCPConfig(conarycfg.ConfigFile):
basePath = os.path.join(os.path.sep, 'srv', 'rbuilder', 'mcp')
logPath = os.path.join(basePath, 'log')
queueHost = '127.0.0.1'
... | #
# Copyright (c) 2005-2006 rPath, Inc.
#
# All rights reserved
#
import os
from conary import conarycfg
from conary.lib import cfgtypes
class MCPConfig(conarycfg.ConfigFile):
basePath = os.path.join(os.path.sep, 'srv', 'rbuilder', 'mcp')
logPath = os.path.join(basePath, 'log')
queueHost = '127.0.0.1'
... | apache-2.0 | Python |
6d2f22d3a3ef7990dcf2f77b91b619b51d1221c9 | Add support for the new data format (0.2.0) | kerel-fs/ogn-rdb,kerel-fs/ogn-rdb,kerel-fs/ogn-rdb | mkstatistics.py | mkstatistics.py | #!/usr/bin/env python3
import json
from collections import defaultdict
from argparse import ArgumentParser
"""
Generate statistics for receivers.json
Equivalent:
cat receivers.json | jq ".receivers | group_by(.country) | map({(.[0].country): [.[].callsign]})"
"""
def print_stats(all_receivers):
receivers_by_co... | #!/usr/bin/env python3
import json
from collections import defaultdict
from argparse import ArgumentParser
"""
Generate statistics for receivers.json
"""
def print_stats(stations):
stat_by_country = defaultdict(dict)
for s in stations:
stat_by_country[stations[s]['country']][s] = stations[s]
fo... | agpl-3.0 | Python |
22f305a7cb1daab3dc61b0d22b796916417de9d2 | Increase size of bottleneck layer. | lmjohns3/theanets,chrinide/theanets,devdoer/theanets | examples/mnist-deepautoencoder.py | examples/mnist-deepautoencoder.py | #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.run(train, va... | #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 16, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.run(train, va... | mit | Python |
d9efa6723acbc682593125b9d0603328e6fafb8d | fix a comment | alexshepard/aledison | delete_contact.py | delete_contact.py | #!/usr/bin/python
import yaml
config = yaml.safe_load(open("config.yml"))
from contacts import Contacts, Contact
c = Contacts()
import sys
if len(sys.argv) < 2:
print("usage: delete_contact.py <name>")
sys.exit()
script_name = sys.argv.pop(0)
name = sys.argv.pop(0)
contact = c.find_contact_by_name(name)
if co... | #!/usr/bin/python
import yaml
config = yaml.safe_load(open("config.yml"))
from contacts import Contacts, Contact
c = Contacts()
# syntax: add_contact.py <name> <number>
import sys
if len(sys.argv) < 2:
print("usage: delete_contact.py <name>")
sys.exit()
script_name = sys.argv.pop(0)
name = sys.argv.pop(0)
con... | mit | Python |
4dde490bfbf27d5aa92b9a310a45ef4bd7a561a7 | test MolCatalogs | rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig | Code/GraphMol/test_list.py | Code/GraphMol/test_list.py | import sys
tests=[
("testExecs/itertest.exe","",{}),
("testExecs/MolOpsTest.exe","",{}),
("testExecs/testCanon.exe","C1OCCC1 C1CCOC1",{}),
("testExecs/testPickler.exe","",{}),
("testExecs/test1.exe","",{}),
("python","test_list.py",{'dir':'Depictor'}),
("python","test_list.py",{'dir':'FileParsers'}),
... | import sys
tests=[
("testExecs/itertest.exe","",{}),
("testExecs/MolOpsTest.exe","",{}),
("testExecs/testCanon.exe","C1OCCC1 C1CCOC1",{}),
("testExecs/testPickler.exe","",{}),
("testExecs/test1.exe","",{}),
("python","test_list.py",{'dir':'Depictor'}),
("python","test_list.py",{'dir':'FileParsers'}),
... | bsd-3-clause | Python |
f70bbbdadc044a76f7b90b2cac0191353a6a5048 | Rework the import finding logic | ericdill/depfinder | depfinder.py | depfinder.py | import ast
import os
from collections import deque
import sys
from stdlib_list import stdlib_list
conf = {
'ignore_relative_imports': True,
'ignore_builtin_modules': True,
'pyver': None,
}
def get_imported_libs(code):
tree = ast.parse(code)
imports = deque()
for t in tree.body:
# ast.... | import ast
def get_imported_libs(code):
tree = ast.parse(code)
# ast.Import represents lines like 'import foo' and 'import foo, bar'
# the extra for name in t.names is needed, because names is a list that
# would be ['foo'] for the first and ['foo', 'bar'] for the second
imports = [name.name.split... | bsd-3-clause | Python |
9c8972523c3861cb88dd09f51fa1efbf46d4a1b3 | Fix bilibili seeker. | chienius/anicolle | anicolle/seeker/bilibili.py | anicolle/seeker/bilibili.py | import requests
from bs4 import BeautifulSoup
from json import loads
def seek(chk_key, cur_epi):
tepi = cur_epi+1
chk_key = str(chk_key)
try:
int(chk_key)
except ValueError:
query_url = "http://search.bilibili.com/bangumi?keyword=%s" % (chk_key, )
html_content = requests.get(qu... | import requests
from bs4 import BeautifulSoup
from json import loads
def seek(chk_key, cur_epi):
tepi = cur_epi+1
chk_key = str(chk_key)
try:
int(chk_key)
except ValueError:
query_url = "http://www.bilibili.com/search?keyword=%s&orderby=&type=series&tids=&tidsC=&arctype=all&page=1" % (... | mit | Python |
2a8c4790bd432fc4dc0fdda64c0cea4f76fac9ff | Fix add_page_if_missing context processor when no pages exist yet | matthiask/feincms2-content,hgrimelid/feincms,nickburlett/feincms,michaelkuty/feincms,michaelkuty/feincms,hgrimelid/feincms,feincms/feincms,pjdelport/feincms,joshuajonah/feincms,pjdelport/feincms,michaelkuty/feincms,joshuajonah/feincms,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-e... | feincms/context_processors.py | feincms/context_processors.py | from feincms.module.page.models import Page
def add_page_if_missing(request):
# If this attribute exists, the a page object has been registered already
# by some other part of the code. We let it decide, which page object it
# wants to pass into the template
if hasattr(request, '_feincms_page'):
... | from feincms.module.page.models import Page
def add_page_if_missing(request):
# If this attribute exists, the a page object has been registered already
# by some other part of the code. We let it decide, which page object it
# wants to pass into the template
if hasattr(request, '_feincms_page'):
... | bsd-3-clause | Python |
efa36e1013e44fa75f6a77a74bd8bf21f3120976 | Allow for a longer image path | fivejjs/Django-facebook,troygrosfield/Django-facebook,danosaure/Django-facebook,rafaelgontijo/Django-facebook-fork,abendleiter/Django-facebook,pjdelport/Django-facebook,fivejjs/Django-facebook,abendleiter/Django-facebook,abendleiter/Django-facebook,andriisoldatenko/Django-facebook,ganescoo/Django-facebook,VishvajitP/Dj... | django_facebook/models.py | django_facebook/models.py | from django.db import models
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
class FacebookProfileModel(models.Model):
'''
Abstract class to add to your profile model.
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in.... | from django.db import models
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
class FacebookProfileModel(models.Model):
'''
Abstract class to add to your profile model.
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in.... | bsd-3-clause | Python |
571b632a6dceb6035c2dec3c0392cdac10215fa2 | Increase version | dreipol/djangocms-spa,dreipol/djangocms-spa | djangocms_spa/__init__.py | djangocms_spa/__init__.py | __version__ = '0.1.2'
| __version__ = '0.1.1'
| mit | Python |
65a069970435d012577a5e4f8971b1a91d9331a8 | Update to 0.3.34 | KerkhoffTechnologies/django-connectwise,KerkhoffTechnologies/django-connectwise | djconnectwise/__init__.py | djconnectwise/__init__.py | # -*- coding: utf-8 -*-
VERSION = (0, 3, 34, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
| # -*- coding: utf-8 -*-
VERSION = (0, 3, 33, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
| mit | Python |
e1b4a5bebe59ae502e46890f78e666cb50460774 | Update convert_b64.py | GoogleCloudPlatform/ml-on-gcp,GoogleCloudPlatform/ml-on-gcp,GoogleCloudPlatform/ml-on-gcp,GoogleCloudPlatform/ml-on-gcp | dlvm/tools/convert_b64.py | dlvm/tools/convert_b64.py | import base64
INPUT_FILE = 'image.jpg'
OUTPUT_FILE = '/tmp/image_b64.json'
"""Open image and convert it to Base64"""
with open(INPUT_FILE, 'rb') as input_file:
jpeg_bytes = base64.b64encode(input_file.read()).decode('utf-8')
predict_request = '{"image_bytes": {"b64": "%s"}}' % jpeg_bytes
# Write JSON to file
... | import base64
INPUT_FILE = 'image.jpg'
OUTPUT_FILE = '/tmp/image_b64.json'
"""Open image and convert it to Base64"""
with open(INPUT_FILE, 'rb') as f:
jpeg_bytes = base64.b64encode(f.read()).decode('utf-8')
predict_request = '{"image_bytes": {"b64": "%s"}}' % jpeg_bytes
# Write JSON to file
with open(OUTPUT_F... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.