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 |
|---|---|---|---|---|---|---|---|---|
457b6c74c676478f4045d0a9801fa81a3d75d714 | Change how manage.py injects local directory into sys.path to ensure it overwrites other instalations | Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server | dashboard_server/manage.py | dashboard_server/manage.py | #!/usr/bin/python
#
# Copyright (C) 2010 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of Launch Control.
#
# Launch Control is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by... | #!/usr/bin/python
#
# Copyright (C) 2010 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of Launch Control.
#
# Launch Control is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by... | agpl-3.0 | Python |
708ad4b2d8f0e7fda71be1b8c20442f01b7c8f07 | Fix history casebug | svkampen/James | plugins/history.py | plugins/history.py | """
History
"""
from .util.decorators import command
@command('history')
def history(bot, nick, target, chan, arg):
""" Get user's history. """
args = arg.split()
try:
if len(args) > 2 or len(args) < 2 or int(args[1]) > 16 or int(args[1]) < 1:
return bot.msg(chan, "Usage: +history <nic... | """
History
"""
from .util.decorators import command
@command('history')
def history(bot, nick, target, chan, arg):
""" Get user's history. """
args = arg.split()
try:
if len(args) > 2 or len(args) < 2 or int(args[1]) > 16 or int(args[1]) < 1:
return bot.msg(chan, "Usage: +history <nic... | mit | Python |
9eb2347e1f1d36acb22d49341e066286146fdd17 | use cron | fhirschmann/tucan | tucanwatch.py | tucanwatch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import mechanize
from lxml import html
def get_grades(username, password):
br = mechanize.Browser()
br.open("https://www.tucan.tu-darmstadt.de")
br.select_form(nr=0)
br.form["usrname"] = username
br.form... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import mechanize
from lxml import html
def get_grades(username, password):
br = mechanize.Browser()
br.open("https://www.tucan.tu-darmstadt.de")
br.select_form(nr=0)
br.form["usrname"] = username
br.form["pass"] = password
br.submit()
br.foll... | mit | Python |
6ff6f7ecf75551dc49685c4bb0501e6f4b2de854 | Fix for regression test, since we rely on the formatter for std::vector in the test we need a libc++ category. | llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb | packages/Python/lldbsuite/test/expression_command/vector_of_enums/TestVectorOfEnums.py | packages/Python/lldbsuite/test/expression_command/vector_of_enums/TestVectorOfEnums.py | """
Test Expression Parser regression test to ensure that we handle enums
correctly, in this case specifically std::vector of enums.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestVectorOfEnums(TestBase):
mydir = TestBase... | """
Test Expression Parser regression test to ensure that we handle enums
correctly, in this case specifically std::vector of enums.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestVectorOfEnums(TestBase):
mydir = TestBase... | apache-2.0 | Python |
df7e834b8418aeeeaee7fb90b953468c2490b93d | Add Ascii Art & Version Number | ekonstantinidis/pypiup | pypiup/cli.py | pypiup/cli.py | import __init__
import os
import click
from pypiup.requirements import Requirements
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@click.command()
@click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to... | import os
import click
from pypiup.requirements import Requirements
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@click.command()
@click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.t... | bsd-2-clause | Python |
e0423d453189508bdb73fc78320b5736bc127fd4 | Bump version | felliott/waterbutler,Johnetordoff/waterbutler,TomBaxter/waterbutler,CenterForOpenScience/waterbutler,kwierman/waterbutler,RCOSDP/waterbutler,chrisseto/waterbutler,icereval/waterbutler,rafaeldelucena/waterbutler,rdhyee/waterbutler,hmoco/waterbutler,Ghalko/waterbutler,cosenal/waterbutler | waterbutler/__init__.py | waterbutler/__init__.py | __version__ = '0.2.2'
__import__("pkg_resources").declare_namespace(__name__)
| __version__ = '0.2.1'
__import__("pkg_resources").declare_namespace(__name__)
| apache-2.0 | Python |
6833bd136086e0e46fabb3921c65d22325857c56 | add utility for getting domains created by a user | dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | corehq/apps/domain/utils.py | corehq/apps/domain/utils.py | import re
from couchdbkit import ResourceNotFound
from django.conf import settings
from corehq import toggles
from corehq.apps.domain.models import Domain
from corehq.util.quickcache import quickcache
from dimagi.utils.couch.database import get_db
from corehq.apps.es import DomainES
DOMAIN_MODULE_KEY = 'DOMAIN_MODU... | import re
from couchdbkit import ResourceNotFound
from django.conf import settings
from corehq import toggles
from corehq.apps.domain.models import Domain
from corehq.util.quickcache import quickcache
from dimagi.utils.couch.database import get_db
DOMAIN_MODULE_KEY = 'DOMAIN_MODULE_CONFIG'
ADM_DOMAIN_KEY = 'ADM_ENA... | bsd-3-clause | Python |
695fb09b1f048878cd7358e1e536aee2313b6d61 | Include listenonrepeat.com in regex for #39 | tomleese/smartbot,Muzer/smartbot,Cyanogenoid/smartbot,thomasleese/smartbot-old | plugins/youtube.py | plugins/youtube.py | import re
import urllib
import isodate
import requests
import smartbot
from smartbot import utils
from smartbot.exceptions import *
from smartbot.formatting import *
REGEX = r"(?:https?://)?(?:www\.)?(?:youtu\.?be|listenonrepeat)(?:\.com)?/(?:watch/?\?v=)?([^\s]+)"
class Plugin(smartbot.Plugin):
"""Get informa... | import re
import urllib
import isodate
import requests
import smartbot
from smartbot import utils
from smartbot.exceptions import *
from smartbot.formatting import *
REGEX = r"(?:https?://)?(?:www\.)?youtu\.?be(?:\.com)?/(?:watch\?v=)?([^\s]+)"
class Plugin(smartbot.Plugin):
"""Get information about posted Yo... | mit | Python |
088286502b545b65a63ce0e7e44f584faac3aa4b | Add Pox. Also remove erroneous left() from square | silshack/fall2013turtlehack | turtlehack.py | turtlehack.py | import turtle
import random
# A function that takes a turtle, a radius, a color, and an optional thickness and draws a circle
def colored_circle(turtle, radius, color, thickness = 1):
turtle.width(thickness)
turtle.color(color)
turtle.circle(radius)
# A function that takes a side length and a color and makes a sq... | import turtle
import random
# A function that takes a turtle, a radius, a color, and an optional thickness and draws a circle
def colored_circle(turtle, radius, color, thickness = 1):
turtle.width(thickness)
turtle.color(color)
turtle.circle(radius)
# A function that takes a side length and a color and makes a sq... | mit | Python |
6c9a3e5133115a4724c8499380ee690a9cca0552 | Add Exception on import of pmagpy if using wrong Python version (should be impossible to install this version, but people are tricky….) | lfairchild/PmagPy,lfairchild/PmagPy,Caoimhinmg/PmagPy,lfairchild/PmagPy,Caoimhinmg/PmagPy,Caoimhinmg/PmagPy | pmagpy/__init__.py | pmagpy/__init__.py | from __future__ import absolute_import
import sys
if sys.version_info <= (3,):
raise Exception("""
You are running Python {}.
This version of pmagpy is only compatible with Python 3.
Make sure you have pip >= 9.0 to avoid this kind of issue,
as well as setuptools >= 24.2:
$ pip install pip setuptools --upgrade
T... | from __future__ import absolute_import
from . import pmag
from . import ipmag
from . import pmagplotlib
from . import find_pmag_dir
from . import version
from . import controlled_vocabularies2 as controlled_vocabularies
from . import data_model3
from . import new_builder
from . import mapping
#import set_env
__all__ =... | bsd-3-clause | Python |
05f4a8af5f856f2451f1f9e2be262876f53f67ef | Bump schema version :disappointed: | dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | corehq/apps/export/const.py | corehq/apps/export/const.py | """
Some of these constants correspond to constants set in corehq/apps/export/static/export/js/const.js
so if changing a value, ensure that both places reflect the change
"""
from couchexport.deid import (
deid_ID,
deid_date
)
from corehq.apps.export.transforms import (
case_id_to_case_name,
user_id_to_... | """
Some of these constants correspond to constants set in corehq/apps/export/static/export/js/const.js
so if changing a value, ensure that both places reflect the change
"""
from couchexport.deid import (
deid_ID,
deid_date
)
from corehq.apps.export.transforms import (
case_id_to_case_name,
user_id_to_... | bsd-3-clause | Python |
ef275bd9ff509842161397b81af8ac765c0bab3a | patch to work properly for ALL | dparlevliet/elastic-firewall,dparlevliet/elastic-firewall,dparlevliet/elastic-firewall | update_firewall.py | update_firewall.py | #! /usr/bin/python
import sys
import os
import json
import socket
import ext.iptables as ipt
class ElasticRules():
rules = {
'allowed_ips': {},
'ports': {},
}
def add_port_rule(self, port, whom, type):
key = "%s:%s:%s" % (port, type, whom)
self.rules['ports'][key] = (port, whom, type)
def re... | #! /usr/bin/python
import sys
import os
import json
import socket
import ext.iptables as ipt
class ElasticRules():
rules = {
'allowed_ips': {},
'ports': {},
}
def add_port_rule(self, port, whom, type):
key = "%s:%s:%s" % (port, type, whom)
self.rules['ports'][key] = (port, whom, type)
def re... | mit | Python |
0e5db5420b941574f7074e716159d85b3097ae58 | use vagrant as the default. | ionrock/rdo | rdo/config.py | rdo/config.py | import os
import functools
from ConfigParser import ConfigParser
# Use vagrant by default
DEFAULTS = {
'driver': 'vagrant',
'directory': '/vagrant'
}
def get_config(config_file='.rdo.conf'):
config = ConfigParser()
config.read(config_file)
env = os.environ.get('RDO_ENV') or 'default'
try:
... | import os
import functools
from ConfigParser import ConfigParser
def get_config(config_file='.rdo.conf'):
config = ConfigParser()
config.read(config_file)
env = os.environ.get('RDO_ENV') or 'default'
return dict(config.items(env))
if __name__ == '__main__':
c = Config('example.conf')
c.pars... | bsd-3-clause | Python |
ac1d6923e0dc682698f808e6401c4686348f4c33 | Update to new settings | danielfrg/danielfrg.github.io-source,danielfrg/danielfrg.github.io-source,danielfrg/danielfrg.github.io-source | pelicanconf.py | pelicanconf.py | from __future__ import unicode_literals
LOAD_CONTENT_CACHE = False
SITEURL = ''
# SITEURL = 'http://danielfrg.github.io'
AUTHOR = u'Daniel Rodriguez'
SITENAME = u'Daniel Rodriguez'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
MARKUP = ('md', 'ipynb')
DEFAULT_DATE_FORMAT = '%B %d, %Y'
SUMMARY_MAX_LENGTH = 150
DEFAULT_PAG... | from __future__ import unicode_literals
LOAD_CONTENT_CACHE = False
SITEURL = ''
# SITEURL = 'http://danielfrg.github.io'
AUTHOR = u'Daniel Rodriguez'
SITENAME = u'Daniel Rodriguez'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
MARKUP = ('md', 'ipynb')
DEFAULT_DATE_FORMAT = '%B %d, %Y'
SUMMARY_MAX_LENGTH = 150
DEFAULT_PAG... | apache-2.0 | Python |
9caeab6005ca0508f7045c869def5962edb48ed1 | verify Fixed a bug with the stop command for plain | sxend/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,methane/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,actframework/F... | plain/setup.py | plain/setup.py | import setup_util
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
setup_util.replace_text("plain/src/main/resources/application.conf", "127.0.0.1", args.database_host)
if os.name == 'nt':
subprocess.check_call(".\sbt.bat assembly && del /f /s /q target\scala-2.10\cache", s... | import setup_util
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
setup_util.replace_text("plain/src/main/resources/application.conf", "127.0.0.1", args.database_host)
if os.name == 'nt':
subprocess.check_call(".\sbt.bat assembly && del /f /s /q target\scala-2.10\cache", s... | bsd-3-clause | Python |
8c1ec4a8dc35b38a15c000a6eb6ccb046f51d44a | Fix unit tests for export-configuration and generate-configuration. | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop | tests/pdtools/test_node.py | tests/pdtools/test_node.py | import click
from click.testing import CliRunner
from mock import patch, MagicMock
from pdtools import node
@patch("pdtools.util.open_yaml_editor")
@patch("pdtools.node.util.format_result")
@patch("pdtools.node.ParadropClient")
def test_simple_node_commands(ParadropClient, format_result, open_yaml_editor):
comma... | import click
from click.testing import CliRunner
from mock import patch
from pdtools import node
@patch("pdtools.util.open_yaml_editor")
@patch("pdtools.node.util.format_result")
@patch("pdtools.node.ParadropClient")
def test_simple_node_commands(ParadropClient, format_result, open_yaml_editor):
commands = [
... | apache-2.0 | Python |
032d0cd785a979da59e90c1064a868cd252618e4 | Change import to form used everywhere else. | bsipocz/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,almarklein/scikit-image,emmanuelle/scikits.image,blink1073/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,almarklein/scikit-image,emmanuelle/scikits.image,emon10005/scikit-image,WarrenWeckesser/scikits-image,paalge/scikit-image,almarkl... | scikits/image/color/tests/test_colorconv.py | scikits/image/color/tests/test_colorconv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:author: Nicolas Pinto, 2009
:license: modified BSD
"""
import os.path
import numpy as np
from numpy.testing import *
from scikits.image.io import imread
from scikits.image.color import (
rgb2hsv,
)
from scikits.image import data_dir
import colorsys
class... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:author: Nicolas Pinto, 2009
:license: modified BSD
"""
from os import path
import numpy as np
from numpy.testing import *
from scikits.image.io import imread
from scikits.image.color import (
rgb2hsv,
)
from scikits.image import data_dir
import colorsys
... | bsd-3-clause | Python |
822ff043c755a731d5f12181071f3ce0d1a7b2a2 | Adjust name of CLI utility | OcelotProject/Compare,OcelotProject/Compare,OcelotProject/Compare | ocelot_compare/bin/cli.py | ocelot_compare/bin/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ocelot-compare CLI interface.
Usage:
ocelot-compare compare <run_id> <ref_dirpath> [--debug]
ocelot-compare show <run_id> [--debug]
Options:
--list List the updates needed, but don't do anything
-h --help Show this screen.
--version ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ocelot-compare CLI interface.
Usage:
compare-cli compare <run_id> <ref_dirpath> [--debug]
compare-cli show <run_id> [--debug]
Options:
--list List the updates needed, but don't do anything
-h --help Show this screen.
--version Sh... | bsd-3-clause | Python |
6d0e4c0568d6ad5ee16afd34e30b06a5fb3b58eb | bump version number | laowantong/mocodo,laowantong/mocodo,laowantong/mocodo,laowantong/mocodo,laowantong/mocodo | mocodo/version_number.py | mocodo/version_number.py | version = u"2.1.4" | version = u"2.1.3" | mit | Python |
aeb59440809f9a3ab32bf65752627822ce57b5fa | use AdvectionDiffusion timestepper class for test_IP_diffusion | firedrakeproject/dcore,firedrakeproject/gusto | tests/test_IP_diffusion.py | tests/test_IP_diffusion.py | from gusto import *
from firedrake import PeriodicIntervalMesh, ExtrudedMesh, SpatialCoordinate,\
VectorFunctionSpace, Constant, exp, as_vector
import pytest
def setup_IPdiffusion(dirname, vector, DG):
dt = 0.01
L = 10.
m = PeriodicIntervalMesh(50, L)
mesh = ExtrudedMesh(m, layers=50, layer_heigh... | import itertools
from os import path
from gusto import *
from firedrake import PeriodicIntervalMesh, ExtrudedMesh, SpatialCoordinate,\
VectorFunctionSpace, File, Constant, Function, exp, as_vector
import pytest
def setup_IPdiffusion(vector, DG):
dt = 0.01
L = 10.
m = PeriodicIntervalMesh(50, L)
m... | mit | Python |
8f6921e9fdc294fd6cc0f5701624a27ff63ed1c0 | Add 'Objectiveable' to Objectives, and rename association | NejcZupec/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core... | src/ggrc/models/objective.py | src/ggrc/models/objective.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
from ggrc import db
from .associationproxy import association_proxy
from .mixins i... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
from ggrc import db
from .associationproxy import association_proxy
from .mixins i... | apache-2.0 | Python |
996486d25a23f2d75384e8c2736ca4735a542283 | Fix obj load function | minoue/miExecutor | module/others/plugins.py | module/others/plugins.py | from maya import cmds
class Commands(object):
""" class name must be 'Commands' """
commandDict = {}
def _loadObjPlugin(self):
if not cmds.pluginInfo("objExport", q=True, loaded=True):
cmds.loadPlugin("objExport")
commandDict['loadObjPlugin'] = "sphere.png"
# ^ Don't forget t... | from maya import cmds
class Commands(object):
""" class name must be 'Commands' """
commandDict = {}
def _loadObjPlugin(self):
if not cmds.pluginInfo("objExport", q=True, loaded=True):
cmds.loadPlugin("objExport")
commandDict['sampleCommand'] = "sphere.png"
# ^ Don't forget t... | mit | Python |
f432ad600fdd9b69fb35a1a56c3799a0521e1c04 | add start command | BrianHicks/perch,BrianHicks/perch | perch/bases.py | perch/bases.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import sys
from .config import constants
from .serializers import serializers
class StdIOHandler(object):
"Provide common I/O handling to the command line"
def __init__(self):
self.config = json.loads(os.environ.get(constants.stage_e... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import sys
from .config import constants
from .serializers import serializers
class StdIOHandler(object):
"Provide common I/O handling to the command line"
def __init__(self):
self.config = json.loads(os.environ.get(constants.stage_e... | bsd-3-clause | Python |
9d61e0bd697cf8cd5086f56f85f6083d29a2f083 | 重构,加入一些注释 | RyanPoy/pyrails | pyactive/relation/relation_methods.py | pyactive/relation/relation_methods.py | # -*- coding:utf-8 -*-
from ..utils import singularize_of, pluralize_of, ColumnNotInColumns
def owner_attr_for_has_one_and_has_belongs_to(self):
""" User has one Phone, owner attr must be 'phone'
Phone belongs to User, owner attr must be 'user'
"""
if self._owner_attr:
return self._owner_attr
... | # -*- coding:utf-8 -*-
from ..utils import singularize_of, pluralize_of, ColumnNotInColumns
def owner_attr_for_has_one_and_has_belongs_to(self):
""" for has_one and belongs_to
"""
if self._owner_attr:
return self._owner_attr
if self.owner is None:
return None
from ..record import A... | mit | Python |
de89e3c3cf0eee28693f33f26b9b9b24e8def64e | Change 'http' to 'https' for SonarCloud | jadolg/rocketchat_API | tests/test_integrations.py | tests/test_integrations.py | from uuid import uuid1
import pytest
@pytest.fixture(autouse=True)
def integrations_create_webhook_incoming(logged_rocket):
return logged_rocket.integrations_create(
integrations_type="webhook-incoming",
name=str(uuid1()),
enabled=True,
username=logged_rocket.me().json().get("user... | from uuid import uuid1
import pytest
@pytest.fixture(autouse=True)
def integrations_create_webhook_incoming(logged_rocket):
return logged_rocket.integrations_create(
integrations_type="webhook-incoming",
name=str(uuid1()),
enabled=True,
username=logged_rocket.me().json().get("user... | mit | Python |
cd20c89ffa34538437a41e2416be3168aab14926 | add placeholder | marshki/pyWipe,marshki/pyWipe | tests/test_user_is_root.py | tests/test_user_is_root.py | import os
import sys
"""Placeholder.
"""
def user_is_root():
"""Check if current UID is 0.
"""
if os.getuid() != 0:
print("This program requires ROOT privileges. Exiting.")
sys.exit()
user_is_root()
| import os
import sys
def user_is_root():
"""Check if current UID is 0.
"""
if os.getuid() != 0:
print("This program requires ROOT privileges. Exiting.")
sys.exit()
user_is_root()
| mit | Python |
f0e172872435307d5fe3ac48ff7c2ed0b3df5759 | split up integration and unit tests, the sqlite tests take longer than i'd like, do as much unit testing as possible -- adding some unit tests for player height/weight conversion | fancystats/nhlstats | tests/unit/models_tests.py | tests/unit/models_tests.py | import unittest
from nhlstats.models import Player
class TestModelPlayer(unittest.TestCase):
def test_height_na(self):
p = Player()
self.assertEqual(p.height, None)
self.assertEqual(p.height_imperial, 'N/A')
self.assertEqual(p.height_metric, 'N/A')
p... | import unittest
from nhlstats.models import Player
class TestModelPlayer(unittest.TestCase):
def test_height_na(self):
p = Player()
self.assertEqual(p.height_imperial, 'N/A') | mit | Python |
ee274d44eec39bd0ff886b5fd4818d43896b8210 | Change default resolution | Ajnasz/pippo,Ajnasz/pippo,Ajnasz/pippo | photodaemon.py | photodaemon.py | import picamera
import redis
import time
def take_photo():
camera = picamera.PiCamera()
camera.resolution = (1280, 720)
camera.capture('static/photo.jpg')
camera.close()
r.publish('photo', time.time())
r = redis.StrictRedis(host='localhost', port=6379, db=0)
p = r.pubsub()
p.subscribe('take-photo'... | import picamera
import redis
import time
def take_photo():
camera = picamera.PiCamera()
camera.capture('static/photo.jpg')
camera.close()
r.publish('photo', time.time())
r = redis.StrictRedis(host='localhost', port=6379, db=0)
p = r.pubsub()
p.subscribe('take-photo')
while True:
message = p.get_m... | mit | Python |
93cb2784eedda59aa725198b6a2bb49d9cba3fe9 | add arguments | archangelic/pinhook | pinhook/cli.py | pinhook/cli.py | import click
from .bot import Bot
from marshmallow import Schema, fields, validate, INCLUDE
class Config(Schema):
nickname = fields.Str(required=True)
channels = fields.List(fields.Str(), required=True)
server = fields.Str(required=True)
port = fields.Int()
ops = fields.List(fields.Str())
ssl_r... | import click
from .bot import Bot
from marshmallow import Schema, fields, validate, INCLUDE
class Config(Schema):
nickname = fields.Str(required=True)
channels = fields.List(fields.Str(), required=True)
server = fields.Str(required=True)
port = fields.Int()
ops = fields.List(fields.Str())
ssl_r... | mit | Python |
1046e53c2f6068be9ff7c0ecb62ca665e08fccb4 | Tweak Sentry init to allow running from default settings.py. | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario | plenario/__init__.py | plenario/__init__.py | from flask import Flask, render_template, redirect, url_for, request
from raven.contrib.flask import Sentry
from plenario.database import session as db_session
from plenario.models import bcrypt
from plenario.api import api, cache
from plenario.auth import auth, login_manager
from plenario.views import views
from plena... | import os
from flask import Flask, render_template, redirect, url_for, request
from raven.contrib.flask import Sentry
from plenario.database import session as db_session
from plenario.models import bcrypt
from plenario.api import api, cache
from plenario.auth import auth, login_manager
from plenario.views import views
... | mit | Python |
a60102ea950c44431097576d74921ea4867fb197 | Remove urllib and use requests | thepieterdc/ugent-food | ugent-food.py | ugent-food.py | #!/usr/bin/env python3
import json
import datetime
import requests
import sys
from urllib.error import HTTPError
def header(text, fillchar='-', width=40):
tofill = max(width - 4 - len(text), 0)
leftpad = tofill // 2
print('{}[ {} ]{}'.format(
fillchar * leftpad,
text,
fillchar * ... | #!/usr/bin/env python3
import json
import datetime
import sys
import urllib.request
from urllib.error import HTTPError
def header(text, fillchar='-', width=40):
tofill = max(width - 4 - len(text), 0)
leftpad = tofill // 2
print('{}[ {} ]{}'.format(
fillchar * leftpad,
text,
fillc... | mit | Python |
ef62b2c146bb1c8960a3ee700c544d61519998b2 | Remove unreachable conditional | genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2 | wqflask/base/GeneralObject.py | wqflask/base/GeneralObject.py | # Copyright (C) University of Tennessee Health Science Center, Memphis, TN.
#
# This program 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 la... | # Copyright (C) University of Tennessee Health Science Center, Memphis, TN.
#
# This program 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 la... | agpl-3.0 | Python |
c2c1b850c1045d0e57217b074d5ce79dfee78681 | Update moksha's app_cfg | mokshaproject/moksha,lmacken/moksha,pombredanne/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,ralphbean/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha | moksha/config/app_cfg.py | moksha/config/app_cfg.py | from tg.configuration import AppConfig, Bunch
import moksha
from moksha import model
from moksha.lib import app_globals, helpers
base_config = AppConfig()
base_config.package = moksha
# Set the default renderer
base_config.default_renderer = 'mako'
base_config.renderers = []
base_config.renderers.append('mako')
# @... | from tg.configuration import AppConfig, Bunch
import moksha
from moksha import model
from moksha.lib import app_globals, helpers
base_config = AppConfig()
base_config.renderers = []
base_config.package = moksha
#Set the default renderer
base_config.default_renderer = 'genshi'
base_config.renderers.append('genshi')
... | apache-2.0 | Python |
8e5246cf9b95294c56d2ee76bcf25975de144c3b | debug status | tjcsl/mhacksiv | project/utils/status.py | project/utils/status.py | import json
import requests
from project.models import Phone, Alias
def get_alias(phone, shortname):
phon = Phone.query.filter(Phone.phone_number == phone).first()
if phon is None:
print("unknown phone -- using %s" % shortname)
return shortname
alis = Alias.query.filter(Alias.uid == phon.uid... | import json
import requests
from project.models import Phone, Alias
def get_alias(phone, shortname):
phon = Phone.query.filter(Phone.phone_number == phone).first()
if phon is None:
return shortname
alis = Alias.query.filter(Alias.uid == phon.uid and Alias._from == shortname).first()
if alis is N... | apache-2.0 | Python |
7a7c2a069bf6464d3225a0627fe92ce2cd327c5d | fix status | tjcsl/mhacksiv | project/utils/status.py | project/utils/status.py | import json
import requests
def get_alias(phone, shortname):
return shortname
def get_status(wit_json, phone):
wit_json = json.loads(wit_json)
entities = wit_json["outcomes"][0]["entities"]
server = entities["server"][0]["value"]
status_entity = entities["status_item"][0]["value"]
server = get_... | import json
import requests
def get_alias(phone, shortname):
return shortname
def get_status(wit_json, phone):
wit_json = json.loads(wit_json)
entities = wit_json["outcomes"][0]["entities"]
server = entities["server"][0]["value"]
status_entity = entities["status_item"][0]["value"]
server = get_... | apache-2.0 | Python |
bdd8eb3f6db0592e9eebca75b595a7128c148faa | Bump Version | whutch/cwmud,whutch/atria | cwmud/__init__.py | cwmud/__init__.py | # -*- coding: utf-8 -*-
"""A modular MUD server."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2016 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from os.path import abspath, dirname
__author__ = "Will Hutcheson"
__contact__ = "... | # -*- coding: utf-8 -*-
"""A modular MUD server."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2016 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from os.path import abspath, dirname
__author__ = "Will Hutcheson"
__contact__ = "... | mit | Python |
9b8e5e6183ca343b31f4396f0cd7538876f529f2 | add check for large messages | cyberkitsune/PSO2Proxy,alama/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy | proxy/PSOCryptoUtils.py | proxy/PSOCryptoUtils.py | from Crypto.Cipher import ARC4, PKCS1_v1_5
from Crypto.PublicKey import RSA
class PSO2RC4(object):
"""docstring for PSO2RC4Decrypter"""
def __init__(self, key):
self.rc4key = key
self.rc4de = ARC4.new(key)
self.rc4en = ARC4.new(key)
def decrypt(self, data):
return self.rc... | from Crypto.Cipher import ARC4, PKCS1_v1_5
from Crypto.PublicKey import RSA
class PSO2RC4(object):
"""docstring for PSO2RC4Decrypter"""
def __init__(self, key):
self.rc4key = key
self.rc4de = ARC4.new(key)
self.rc4en = ARC4.new(key)
def decrypt(self, data):
return self.rc... | agpl-3.0 | Python |
4d1b9e93b485085acc977a3b3cefbad286a2cb7b | Fix wrong select call | qurben/mopidy-headless,avanc/mopidy-headless | mopidy_headless/input.py | mopidy_headless/input.py | from __future__ import unicode_literals
import logging
import threading
from evdev import ecodes, InputDevice, list_devices, categorize
from select import select
logger = logging.getLogger(__name__)
class InputThread(threading.Thread):
def __init__(self):
super(InputThread, self).__init__()
self.name="I... | from __future__ import unicode_literals
import logging
import threading
from evdev import ecodes, InputDevice, list_devices, categorize
from select import select
logger = logging.getLogger(__name__)
class InputThread(threading.Thread):
def __init__(self):
super(InputThread, self).__init__()
self.name="I... | apache-2.0 | Python |
76f7f84c320722ba1b969fa132196dcdf0132664 | Change empty label for admin supplier module edit | suutari-ai/shoop,suutari-ai/shoop,taedori81/shoop,taedori81/shoop,shoopio/shoop,jorge-marques/shoop,akx/shoop,shawnadelic/shuup,suutari/shoop,hrayr-artunyan/shuup,shoopio/shoop,shawnadelic/shuup,jorge-marques/shoop,suutari/shoop,akx/shoop,hrayr-artunyan/shuup,suutari-ai/shoop,taedori81/shoop,hrayr-artunyan/shuup,suutar... | shoop/admin/modules/suppliers/views/edit.py | shoop/admin/modules/suppliers/views/edit.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from djang... | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from djang... | agpl-3.0 | Python |
cc9fd6e1b34c334d218fcacbf3399c8ffa79c66c | rename a variable to prevent shadowing | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit | cs251tk/referee/__main__.py | cs251tk/referee/__main__.py | from tempfile import gettempdir
import sys
import os
from ..common import chdir
from ..specs import load_some_specs
from .args import process_args
from .process_student import process_student
from .parse_commits import parse_commits_for_assignments
from .emailify import emailify
from .send_email import send_email
de... | from tempfile import gettempdir
import sys
import os
from ..common import chdir
from ..specs import load_some_specs
from .args import process_args
from .process_student import process_student
from .parse_commits import parse_commits_for_assignments
from .emailify import emailify
from .send_email import send_email
de... | mit | Python |
a474cca425218cefb6efd39813d1c098bf1417cd | Use PEP-440 compliant version | depop/django-oauth2-provider,depop/django-oauth2-provider,depop/django-oauth2-provider | provider/__init__.py | provider/__init__.py | __version__ = "0.2.7+depop.6.1"
| __version__ = "0.2.7-depop6"
| mit | Python |
75ad8f5b695638be75c27997c349297f681ef68c | fix return value from --version flag | nodepy/nodepy | nodepy/main.py | nodepy/main.py | """
The Node.py command-line interface.
"""
from nodepy.utils import pathlib
from nodepy.loader import PythonModule
import argparse
import code
import os
import pdb
import nodepy
import sys
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
VERSION = 'node.py {} [{} {}]'.form... | """
The Node.py command-line interface.
"""
from nodepy.utils import pathlib
from nodepy.loader import PythonModule
import argparse
import code
import os
import pdb
import nodepy
import sys
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
VERSION = 'node.py {} [{} {}]'.form... | mit | Python |
a2daf4a378cb379399f82c8b8df70c5b08c321f9 | fix #3 (thanks to natim) | pelletier/hg_publishall | publishall.py | publishall.py | #!/usr/bin/env python
"""allows you to publish on all your repositories.
Requirements:
mercurial
Use:
hg pusha
You can also use hg pushall
Installation:
Add the following entry to the [extensions] bloc of your .hg/hgrc config.
publishall = /path/to/publishall.py
"""
from mercurial.i18n import _
fr... | #!/usr/bin/env python
"""allows you to publish on all your repositories.
Requirements:
mercurial
Use:
hg pusha
You can also use hg pushall
Installation:
Add the following entry to the [extensions] bloc of your .hg/hgrc config.
publishall = /path/to/publishall.py
"""
from mercurial.i18n import _
from mercurial impo... | mit | Python |
57b743a411d673842bbf60dc7cf09e27bd8bfe2f | increase verbosity | xflr6/bitsets,pombredanne/bitsets | run-tests.py | run-tests.py | #!/usr/bin/env python3
"""Run the tests with https://pytest.org."""
import pathlib
import platform
import sys
import pytest
SELF = pathlib.Path(__file__)
ARGS = [#'--pdb',
#'--exitfirst',
]
if platform.system() == 'Windows' and 'idlelib' in sys.modules:
ARGS += ['--capture=sys', '--color=no']
... | #!/usr/bin/env python3
"""Run the tests with https://pytest.org."""
import platform
import sys
import pytest
ARGS = [#'--pdb',
#'--exitfirst',
]
if platform.system() == 'Windows' and 'idlelib' in sys.modules:
ARGS += ['--capture=sys', '--color=no']
sys.exit(pytest.main(ARGS + sys.argv[1:]))
| mit | Python |
d3cbcfa3d134ef7ce158f229eff75a83418afc52 | Write the extraction script properly. | hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande | tools/dmqmc/extract_n_k.py | tools/dmqmc/extract_n_k.py | #!/usr/bin/env python
'''Extract the momentum distribution from an analysed DMQMC simulation.'''
import pandas as pd
import numpy as np
import sys
def main(args):
if (len(sys.argv) < 2):
print ("Usage: extract_n_k.py file bval")
sys.exit()
bval = float(sys.argv[2])
data = pd.read_csv(s... | #!/usr/bin/env python
'''Extract the momentum distribution from a analysed DMQMC simulation.'''
import pandas as pd
import numpy as np
import sys
# [review] - JSS: use if __name__ == '__main__' and functions so code can easily be reused in another script if necessary.
if (len(sys.argv) < 2):
print ("Usage: extra... | lgpl-2.1 | Python |
71647b64ca6cb29ab7f21127df4378721fea328d | Fix run_tests.py on windows | ucoin-io/cutecoin,ucoin-io/cutecoin,ucoin-io/cutecoin | run_tests.py | run_tests.py | import sys
import os
import signal
import unittest
import subprocess
import time
import shlex
cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000'
p = subprocess.Popen(shlex.split(cmd))
time.sleep(2)
# Force saves to be done in temp directory
os.environ["XDG_CONFIG_HOME"] = os.path.join(os.path.di... | import sys
import os
import signal
import unittest
import subprocess
import time
import shlex
cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000'
p = subprocess.Popen(shlex.split(cmd))
time.sleep(2)
# Force saves to be done in temp directory
os.environ["XDG_CONFIG_HOME"] = os.path.join(os.path.di... | mit | Python |
95e011ce93a38fb0157ad07aee8f7ad0df6e9315 | exit with code error if failures | buxx/synergine | run_tests.py | run_tests.py | from os import getcwd
from sys import path as ppath
ppath.insert(1,getcwd()+'/modules') # TODO: win32 compatibilite (python path)
import unittest
from lifegame.test.LifeGameTestSuite import LifeGameTestSuite
from tests.TestSuite import TestSuite
# TODO: Lister les tests ailleurs ? Recuperer les suite de tests de modu... | from os import getcwd
from sys import path as ppath
ppath.insert(1,getcwd()+'/modules') # TODO: win32 compatibilite (python path)
import unittest
from lifegame.test.LifeGameTestSuite import LifeGameTestSuite
from tests.TestSuite import TestSuite
# TODO: Lister les tests ailleurs ? Recuperer les suite de tests de modu... | apache-2.0 | Python |
ea41856f32e78b367681060d9f0790a209c8165e | change run host | zhy0216/pillar,zhy0216/pillar | runserver.py | runserver.py | # -*- coding: utf-8 -*-
from projectname.app import app
if(__name__ == "__main__"):
app.debug = app.config["DEBUG_MODE"]
app.run(host='0.0.0.0')
| # -*- coding: utf-8 -*-
from projectname.app import app
if(__name__ == "__main__"):
app.debug = app.config["DEBUG_MODE"]
app.run()
| mit | Python |
2dc57094577175e3a925e3601f4aef52ead58585 | remove \r | anlutro/qdb,anlutro/qdb,anlutro/qdb,anlutro/qdb | qdb/models.py | qdb/models.py | from sqlalchemy import Column, Integer, Text, DateTime, Boolean
from qdb.database import Base
import re
class Quote(Base):
__tablename__ = 'quotes'
id = Column(Integer, primary_key=True)
body = Column(Text)
submitted_at = Column(DateTime)
approved = Column(Boolean)
score = Column(Integer)
def __init__(self, b... | from sqlalchemy import Column, Integer, Text, DateTime, Boolean
from qdb.database import Base
import re
class Quote(Base):
__tablename__ = 'quotes'
id = Column(Integer, primary_key=True)
body = Column(Text)
submitted_at = Column(DateTime)
approved = Column(Boolean)
score = Column(Integer)
def __init__(self, b... | mit | Python |
3c573218ddcf0e732d226cae80bea55d44a0deb4 | change template | valdergallo/controle_de_estacionamento_pyserial | runserver.py | runserver.py | # coding=utf-8
from bottle import route, run, install, template, error, static_file
from bottle_sqlite import SQLitePlugin
# carrega o banco de dados pelo plugin do Bottle
install(SQLitePlugin(dbfile='site.db'))
@error(404)
def error404(error):
# pagina de erros
return 'Nothing here, sorry'
@route('/static... | # coding=utf-8
from bottle import route, run, install, template, error, static_file
from bottle_sqlite import SQLitePlugin
# carrega o banco de dados pelo plugin do Bottle
install(SQLitePlugin(dbfile='site.db'))
@error(404)
def error404(error):
# pagina de erros
return 'Nothing here, sorry'
@route('/static... | mit | Python |
59920c85da22327c14a3b21bb3388732fc723c91 | Check status | devicehive/devicehive-python | devicehive/api_response.py | devicehive/api_response.py | class ApiResponse(object):
"""Api response class."""
SUCCESS_STATUS = 'success'
ID_KEY = 'requestId'
ACTION_KEY = 'action'
STATUS_KEY = 'status'
CODE_KEY = 'code'
ERROR_KEY = 'error'
def __init__(self, response, key=None):
self._id = response.pop(self.ID_KEY)
self._acti... | class ApiResponse(object):
"""Api response class."""
SUCCESS_STATUS = 'success'
ID_KEY = 'requestId'
ACTION_KEY = 'action'
STATUS_KEY = 'status'
CODE_KEY = 'code'
ERROR_KEY = 'error'
def __init__(self, response, key=None):
self._id = response.pop(self.ID_KEY)
self._acti... | apache-2.0 | Python |
674f4d8e48eb0d764217d4c849818dc5c0daa5a2 | update version to 0.5.3 | st-tech/zr-obp | obp/version.py | obp/version.py | __version__ = "0.5.3"
| __version__ = "0.5.2"
| apache-2.0 | Python |
0a989b028a1e470a8c3422e601cdca60fb0ddf4a | Convert csvsort to agate, closes #495 | dannguyen/csvkit,onyxfish/csvkit,doganmeh/csvkit,wireservice/csvkit | csvkit/utilities/csvsort.py | csvkit/utilities/csvsort.py | #!/usr/bin/env python
import agate
import six
from csvkit.cli import CSVKitUtility, parse_column_identifiers
class CSVSort(CSVKitUtility):
description = 'Sort CSV files. Like the Unix "sort" command, but for tabular data.'
def add_arguments(self):
self.argparser.add_argument('-y', '--snifflimit', d... | #!/usr/bin/env python
import os
import agate
from csvkit import table
from csvkit.cli import CSVKitUtility, parse_column_identifiers
class CSVSort(CSVKitUtility):
description = 'Sort CSV files. Like the Unix "sort" command, but for tabular data.'
def add_arguments(self):
self.argparser.add_argumen... | mit | Python |
a8bae77c4a096f54414062b7c5a4d9afc75682ec | Handle binary artifacts in Python 3 | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | telemetry/telemetry/internal/results/artifact_compatibility_wrapper.py | telemetry/telemetry/internal/results/artifact_compatibility_wrapper.py | # Copyright 2019 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.
# Compatibility layer for using different artifact implementations through a
# single API.
# TODO(https://crbug.com/1023458): Remove this once artifact imple... | # Copyright 2019 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.
# Compatibility layer for using different artifact implementations through a
# single API.
# TODO(https://crbug.com/1023458): Remove this once artifact imple... | bsd-3-clause | Python |
bea80411c13ed72b1e7d5a5ac79fdba64b4b4661 | Add star graph for sparse.csgraph.dijkstra benchmark | scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy,scipy/scipy | benchmarks/benchmarks/sparse_csgraph_djisktra.py | benchmarks/benchmarks/sparse_csgraph_djisktra.py | """benchmarks for the scipy.sparse.csgraph module"""
import numpy as np
import scipy.sparse
from .common import Benchmark, safe_import
with safe_import():
from scipy.sparse.csgraph import dijkstra
class Dijkstra(Benchmark):
params = [
[30, 300, 900],
[True, False],
['random', 'star']... | """benchmarks for the scipy.sparse.csgraph module"""
import numpy as np
import scipy.sparse
from .common import Benchmark, safe_import
with safe_import():
from scipy.sparse.csgraph import dijkstra
class Dijkstra(Benchmark):
params = [
[30, 300, 900],
[True, False]
]
param_names = ['n... | bsd-3-clause | Python |
b26ba0d29c39095044721d60ecb250b011cf844b | Add link in documentation | sgaynetdinov/py-vkontakte | vk/attachments.py | vk/attachments.py | # coding=utf-8
def get_attachments(attachments_json):
if not attachments_json:
return None
attachment_items = []
for attachment_json in attachments_json:
if attachment_json.get("type") == "photo":
attachment_items.append(AttachmentPhoto.from_json(attachment_json.get("photo")))
... | # coding=utf-8
def get_attachments(attachments_json):
if not attachments_json:
return None
attachment_items = []
for attachment_json in attachments_json:
if attachment_json.get("type") == "photo":
attachment_items.append(AttachmentPhoto.from_json(attachment_json.get("photo")))
... | mit | Python |
868bea37f139ac846f1856af4a5ae659d654c755 | break down player dict more logically | rnagle/pycar,tommeagher/pycar14,tommeagher/pycar14,ireapps/pycar | project2/baseball.py | project2/baseball.py | import csv
import operator
import math
#First, let's see what kind of data we have to work with
def calculate_top10 (filename):
#Open the salary csv
salaries_object = open(filename, 'rb')
#Make the file object usable
salary_data = csv.reader(salaries_object)
#Create your header row and look at w... | import csv
#TODO: Make this so we can walk a folder structure
SALARIES_FILE = 'data/2013/Salaries.csv'
#First, let's see what kind of data we have to work with
def explore_salary_csv(filename):
#Open the salary csv
salaries_object = open(SALARIES_FILE, 'rb')
#Make the file object usable
salary_data ... | mit | Python |
4f01013e6a958580c106709de0d37b7ca192202f | Add saturated fat and trans fat | 11craft/django-usda,nicksanders/django-usda | usda/facts.py | usda/facts.py | from .models import Nutrient, NutrientData
ENERGY = 208
TOTAL_FAT = 204
SATURATED_FAT = 606
TRANS_FAT = 605
class NutritionFacts(object):
def __init__(self, food, calories=None, grams=100):
self.food = food
self._calories = calories
self._grams = grams
energy_nutrient = Nutrient... | from .models import Nutrient, NutrientData
ENERGY = 208
TOTAL_FAT = 204
class NutritionFacts(object):
def __init__(self, food, calories=None, grams=100):
self.food = food
self._calories = calories
self._grams = grams
energy_nutrient = Nutrient.objects.get(number=208)
sel... | bsd-3-clause | Python |
852220a8eedd86a092072ac3d2563ff3fc6c8bd4 | make Service class inherit from object | JamesGardiner/chwrapper,JamesGardiner/companies-house | chwrapper/services/base.py | chwrapper/services/base.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (c) 2015 James Gardiner
#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 us... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (c) 2015 James Gardiner
#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 us... | mit | Python |
e950f905c34b1912973f1639fdf635f67292562e | Add usage example to listemner registration script. | ucla/PushHubCore | pushhub/scripts.py | pushhub/scripts.py | import optparse
import textwrap
import sys
from pyramid.paster import bootstrap
from pyramid.request import Request
from pushhub.worker import notify_subscribers
def process_subscriber_notices():
description = """
Processes subscriber notifications waiting in the queue.
This script is meant to be run a... | import optparse
import textwrap
import sys
from pyramid.paster import bootstrap
from pyramid.request import Request
from pushhub.worker import notify_subscribers
def process_subscriber_notices():
description = """
Processes subscriber notifications waiting in the queue.
This script is meant to be run a... | bsd-3-clause | Python |
34d2d292dc0868aba84d86878300f86524c6fbd2 | Apply Oslo ModelBase to NeutronBase | gkotton/vmware-nsx,gkotton/vmware-nsx | neutron/db/model_base.py | neutron/db/model_base.py | # Copyright (c) 2012 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | # Copyright (c) 2012 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | apache-2.0 | Python |
8c3b22ac6469da923440e053c52d1007d4baf7f7 | Update fb_post.py | umangahuja1/Python | Automation/fb_post.py | Automation/fb_post.py | '''
This script is created to post status on fb from terminal
'''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui impo... | '''
This script let's you post status on fb from terminal
'''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import S... | apache-2.0 | Python |
b2d28a64bb0837dd97e8be7f97f31f88d380f110 | Add TFX support in pydoc (#23960) | chamikaramj/beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,chamikaramj/beam,apache/beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,chamikaramj/beam,apache/beam,apache/beam,chamikaramj/beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,apache/beam,apache/beam | sdks/python/apache_beam/ml/inference/__init__.py | sdks/python/apache_beam/ml/inference/__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | apache-2.0 | Python |
aaaaa378e0463e83412503ab3eb51809321714d9 | Rename method | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | falcom/api/common/read_only_data_structure.py | falcom/api/common/read_only_data_structure.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.
class ReadOnlyDataStructure:
auto_properties = ( )
__subclasses = set()
def __init__ (self, **kwargs):
self.__set_read_... | # 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.
class ReadOnlyDataStructure:
auto_properties = ( )
__subclasses = set()
def __init__ (self, **kwargs):
self.__set_read_... | bsd-3-clause | Python |
d1fd32946ba422e8f240bd44bffab3107f4d1057 | Return the emoji and format it | michaeljoseph/pymoji,michaeljoseph/pymoji | pymoji/__init__.py | pymoji/__init__.py | """Emits HTML from emoji"""
__author__ = 'Michael Joseph'
__email__ = 'michaeljoseph@gmail.com'
__url__ = 'https://github.com/michaeljoseph/pymoji'
__version__ = '0.0.1'
from .emoji import emoji
def pymoji(text):
if text[0] <> text[:-1] and text[0] <> ':':
text = ':%s:' % text
return emoji(text)
| """Python Library Boilerplate contains all the boilerplate you need to create a Python package."""
__author__ = 'Michael Joseph'
__email__ = 'michaeljoseph@gmail.com'
__url__ = 'https://github.com/michaeljoseph/pymoji'
__version__ = '0.0.1'
def pymoji():
return 'Hello World!'
| apache-2.0 | Python |
0768cba738b3e044930e2d201c7c3705396433a2 | fix bugs when ref or deg is all-zero array | vBaiCai/python-pesq | pypesq/__init__.py | pypesq/__init__.py | import numpy as np
from pesq_core import _pesq
from math import fabs
EPSILON = 1e-6
def pesq(ref, deg, fs=16000, normalize=False):
'''
params:
ref: ref signal,
deg: deg signal,
fs: sample rate,
'''
ref = np.array(ref, copy=True)
deg = np.array(deg, copy=True)
... | import numpy as np
from pesq_core import _pesq
from math import fabs
def pesq(ref, deg, fs=16000, normalize=False):
'''
params:
ref: ref signal,
deg: deg signal,
fs: sample rate,
'''
ref = np.array(ref, copy=True)
deg = np.array(deg, copy=True)
if normali... | mit | Python |
676cec59b2a67060e7815a9b8aa79bf276e5c708 | test write from buffer | fayazkhan/secret-diary | test.py | test.py | import sys
from unittest.mock import Mock, patch
import arrow
from diary import create_entry, Entry, main, show, write_from_buffer
def test_show():
content = 'test'
time = arrow.now()
session = Mock(query=Mock(return_value=[Entry(
updated=time, content=content)]))
with patch('diary.display_r... | from unittest.mock import Mock, patch
import arrow
from diary import create_entry, Entry, main, show, write_from_buffer
def test_show():
content = 'test'
time = arrow.now()
session = Mock(query=Mock(return_value=[Entry(
updated=time, content=content)]))
with patch('diary.display_row') as disp... | agpl-3.0 | Python |
4930774acfc33bf9e558f9ff7305bf3f61f90959 | Add shebang to run_dev.py | LandRegistry/digital-register-api,LandRegistry/digital-register-api | run_dev.py | run_dev.py | #!/usr/bin/env python
from service.server import app
import os
app.run(host="0.0.0.0", port=int(os.environ['PORT']), debug=True)
| from service.server import app
import os
app.run(host="0.0.0.0", port=int(os.environ['PORT']), debug=True)
| mit | Python |
0e4bb9bd4aed8f77428c70411a1ce43dab06e9b5 | bump package version | bozzzzo/quark,bozzzzo/quark,bozzzzo/quark,datawire/quark,datawire/quark,bozzzzo/quark,datawire/quark,datawire/datawire-connect,datawire/quark,datawire/quark,datawire/datawire-connect,datawire/datawire-connect,datawire/quark,datawire/datawire-connect | quark/_metadata.py | quark/_metadata.py | # Copyright 2015 datawire. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2015 datawire. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | apache-2.0 | Python |
b89dd6baf0ea605f63090401375f2f2ee2445a4f | Update utils.py | vitalik/django-ninja,vitalik/django-ninja,vitalik/django-ninja | ninja/signature/utils.py | ninja/signature/utils.py | import asyncio
import inspect
import re
from typing import Any, Callable, Set
from django.urls import register_converter
from django.urls.converters import UUIDConverter
from pydantic.typing import ForwardRef, evaluate_forwardref
from ninja.types import DictStrAny
__all__ = [
"get_typed_signature",
"get_type... | import asyncio
import inspect
import re
from typing import Any, Callable, ForwardRef, Set
from django.urls import register_converter
from django.urls.converters import UUIDConverter
from pydantic.typing import evaluate_forwardref
from ninja.types import DictStrAny
__all__ = [
"get_typed_signature",
"get_type... | mit | Python |
43a83c42bca30881d9f26dedbfcc5f71b6d8d389 | make su functionality simpler and clearer | frostyfrog/mark2,SupaHam/mark2,frostyfrog/mark2,SupaHam/mark2 | plugins/su.py | plugins/su.py | from plugins import Plugin
from events import UserInput
import re
class Su(Plugin):
command = "sudo -su {user} -- {command}"
mode = "include"
proc = "ban;unban"
def setup(self):
self.exceptions = re.split("\s*[\;\,]\s*", self.exceptions)
self.register(self.uinput, UserInput)
... | from plugins import Plugin
from events import UserInput
import re
modes = ('raw', 'su')
class Su(Plugin):
command = "sudo -su {user} -- {command}"
default = "raw"
exceptions = ""
def setup(self):
self.exceptions = re.split("\s*[\;\,]\s*", self.exceptions)
self.register(self.uinput... | mit | Python |
ee86281f0177b5482ccf30e4af8f557fdea59f69 | Fix missed comma | DevolioDevChat/devolio-slackbot | shortcuts.py | shortcuts.py | shortcuts = {
'frontend': ['web', 'css', 'front-end', 'webdev', 'html', 'sass', 'scss', 'stylus'],
'wordpress': ['wp'],
'databases': ['sql', 'mysql', 'postgre', 'postgresql', 'db'],
'ruby': ['rails', 'ror'],
'cplusplus': ['c++', 'cpp'],
'javascript': ['js', 'jscript', 'ecmascript', 'es5', 'es6'],
'assembl... | shortcuts = {
'frontend': ['web', 'css', 'front-end', 'webdev', 'html', 'sass', 'scss', 'stylus'],
'wordpress': ['wp'],
'databases': ['sql', 'mysql', 'postgre', 'postgresql', 'db'],
'ruby': ['rails', 'ror'],
'cplusplus': ['c++', 'cpp'],
'javascript': ['js', 'jscript', 'ecmascript', 'es5', 'es6'],
'assembl... | unlicense | Python |
362719aace6b37e3719ff8527f8f83b3390cf7cd | Add custom Content-Type headers to PKS, to prevent them from being compressed. | SkierPGP/Skier,SkierPGP/Skier,SkierPGP/Skier | skier/pks.py | skier/pks.py | from flask import Blueprint, request
from skier import pgp
from skier.keyinfo import KeyInfo
legacypks = Blueprint("pks", __name__)
@legacypks.route("/add", methods=["POST"])
def pksadd():
keytext = request.form["keytext"]
result = pgp.add_pgp_key(keytext)
if result[0]:
return "", 200, {"X-HKP-Re... | from flask import Blueprint, request
from skier import pgp
from skier.keyinfo import KeyInfo
legacypks = Blueprint("pks", __name__)
@legacypks.route("/add", methods=["POST"])
def pksadd():
keytext = request.form["keytext"]
result = pgp.add_pgp_key(keytext)
if result[0]:
return "", 200, {"X-HKP-Re... | agpl-3.0 | Python |
239b20905b56b93101794f20900f4c4c37f7418b | Fix failing ObjectTask test | kunalsharma05/django-project,kunalsharma05/django-project,peragro/django-project,peragro/django-project,kunalsharma05/django-project | django_project/managers.py | django_project/managers.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_text
class CommentManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_text
class CommentManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
... | bsd-3-clause | Python |
422696cc76ff708f9b87d70460232fa3c08b6a51 | Update comments. | peterhil/prism | prism/grep.py | prism/grep.py | #!/usr/bin/env python -u
# encoding: utf-8
#
# Copyright (c) 2012, Peter Hillerström <peter.hillerstrom@gmail.com>
# All rights reserved. This software is licensed under 3-clause BSD license.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
... | #!/usr/bin/env python -u
# encoding: utf-8
#
# Copyright (c) 2012, Peter Hillerström <peter.hillerstrom@gmail.com>
# All rights reserved. This software is licensed under 3-clause BSD license.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
... | bsd-3-clause | Python |
0e46446de3c7f18c13a5f683dffd2f611781801d | implement silent/verbose modes | khanhnnvn/poet,ihorlaitan/poet,mossberg/poet,0x0mar/poet | malping.py | malping.py | #!/usr/bin/env python
import sys
import time
import socket
import base64
import datetime
import argparse
import subprocess
import logging as log
SIZE = 1024
def get_args():
""" Parse arguments and return dictionary. """
parser = argparse.ArgumentParser()
parser.add_argument('host', metavar='IP', type=s... | #!/usr/bin/env python
import sys
import time
import socket
import base64
import datetime
import argparse
import subprocess
SIZE = 1024
def get_args():
""" Parse arguments and return dictionary. """
parser = argparse.ArgumentParser()
parser.add_argument('host', metavar='IP', type=str)
parser.add_argu... | mit | Python |
3c0d202715e4a1eb6824c8661b0b0e70672fd2d0 | Delete updates with status new | akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr | akvo/rsr/migrations/0110_auto_20170922_1234.py | akvo/rsr/migrations/0110_auto_20170922_1234.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import akvo.rsr.fields
def update_status_new_to_draft(apps, schema):
IndicatorPeriodData = apps.get_model('rsr', 'IndicatorPeriodData')
IndicatorPeriodData.objects.filter(... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import akvo.rsr.fields
def update_status_new_to_draft(apps, schema):
IndicatorPeriodData = apps.get_model('rsr', 'IndicatorPeriodData')
IndicatorPeriodData.objects.filter(... | agpl-3.0 | Python |
2f09731212bcf63f48fa756d71eee52604345dc1 | Allow to use the class with a setup()-close() model in addition to the with clause (which is the recommended usage) | MonsieurV/PiPocketGeiger | radiation_watch.py | radiation_watch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Radiation Watch Pocket Geiger Type 5 library for Raspberry Pi.
Documentation and usage at: https://github.com/MonsieurV/PiPocketGeiger
Released under MIT License. See LICENSE file.
Contributed by:
- Radiation-watch.org <http://www.radiation-watch.org/>
- Yoan Tournad... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Radiation Watch Pocket Geiger Type 5 library for Raspberry Pi.
Documentation and usage at: https://github.com/MonsieurV/PiPocketGeiger
Released under MIT License. See LICENSE file.
Contributed by:
- Radiation-watch.org <http://www.radiation-watch.org/>
- Yoan Tournad... | mit | Python |
8a6c50d0dccbe24f937776f28a3ef69a1a240180 | Add version information so people can figure out what's going on | chevah/pydoctor,jelmer/pydoctor,jelmer/pydoctor,hawkowl/pydoctor,hawkowl/pydoctor,jelmer/pydoctor,chevah/pydoctor | pydoctor/__init__.py | pydoctor/__init__.py |
version_info = (0, 1, 0)
| isc | Python | |
bca6ca83ce43f6d9b96ac590bda9c6253384ab69 | Refactor for other search options later (search -> suggest) | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django | winthrop/people/viaf.py | winthrop/people/viaf.py | import json
import requests
class ViafAPI(object):
"""Wrapper for Viaf API"""
def __init__(self):
self.base_url = "https://www.viaf.org/"
def suggest(self, query):
"""Do a GET request to pull in JSON"""
url = self.base_url + "viaf/AutoSuggest?query="
r = requests.get("%s%... | import requests
from django.conf import settings
class ViafAPI(object):
"""Wrapper for ViafAPI"""
def __init__(self):
default_url = 'https://www.viaf.org/viaf/AutoSuggest?query='
self.base_url = getattr(settings, "VIAF_AUTOSUGGEST_URL", default_url)
def search(self, query):
"""Do... | apache-2.0 | Python |
8b30b109a6eac4cdbe4d1d57f5f9c8e82693a043 | Bump version | dropbox/pygerduty,gmjosack/pygerduty | pygerduty/version.py | pygerduty/version.py | version_info = (0, 32, 1)
__version__ = '.'.join(str(v) for v in version_info)
| version_info = (0, 32, 0)
__version__ = '.'.join(str(v) for v in version_info)
| mit | Python |
66627614c30f623d4fa7a3539380f620d14ece1e | Fix #11 | KostasMp/PortScanner | portscanner.py | portscanner.py | #!/usr/bin/python
import socket
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description = "Test a specified IP for open ports.")
mutex = parser.add_mutually_exclusive_group()
parser.add_argument('-v', '--verbose', help='Add extra verbosity to the output of the scanner', action=... | #!/usr/bin/python
import socket
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description = "Test for open ports...")
mutex = parser.add_mutually_exclusive_group()
parser.add_argument('-v', '--verbose', help='Add extra verbosity to the output of the scanner', action='store_true')... | mit | Python |
8f097cf7ea20b8fb42635452b02f520152218394 | Remove root improts. | vorwerkc/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,vorwerkc/pymatgen,gmatteo/pymatgen,richardtran415/pymatgen,vorwerkc/pymatgen,richardtran415/pymatgen,vorwerkc/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,gmatteo/pymatgen,gVallverdu/pymatgen,richardtran415/pymatgen,fra... | pymatgen/__init__.py | pymatgen/__init__.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Pymatgen (Python Materials Genomics) is a robust, open-source Python library
for materials analysis. This is the root package.
"""
__author__ = "Pymatgen Development Team"
__email__ = "pymatgen@googlegroup... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
# pylint: disable=C0413
"""
Pymatgen (Python Materials Genomics) is a robust, open-source Python library
for materials analysis. This is the root package.
"""
__author__ = "Pymatgen Development Team"
__email__... | mit | Python |
b8d63d20728deed91d02d507e739d05f3d49a61e | Allow settings to be obtained via pymatgen.settings.PMG_MAPI_KEY | gVallverdu/pymatgen,davidwaroquiers/pymatgen,richardtran415/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,richardtran415/pymatgen,richardtran415/pymatgen,davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,gVallverdu/pymatgen,gVallverdu/pymatgen,davidwaroquiers/pymatgen,fraricci/pymat... | pymatgen/settings.py | pymatgen/settings.py | """
Global settings for pymatgen.
"""
import os
try:
import ruamel.yaml as yaml
except ImportError:
try:
import ruamel_yaml as yaml # type: ignore # noqa
except ImportError:
import yaml # type: ignore # noqa
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".pmgrc.yaml")
def _lo... | """
Global settings for pymatgen.
"""
import os
try:
import ruamel.yaml as yaml
except ImportError:
try:
import ruamel_yaml as yaml # type: ignore # noqa
except ImportError:
import yaml # type: ignore # noqa
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".pmgrc.yaml")
def _lo... | mit | Python |
18d45c6ef78d45722e3b431dcb120d80df28eeda | Bump version | pombredanne/pymaven | pymaven/constants.py | pymaven/constants.py | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | apache-2.0 | Python |
a8f149ee7419aaba0d3992aec93376b445b1451d | bump version again (agh pypi) | AndersenLab/vcf-toolbox,AndersenLab/vcf-kit,AndersenLab/vcf-toolbox,AndersenLab/vcf-kit,AndersenLab/vcf-kit,AndersenLab/vcf-toolbox | vcfkit/__init__.py | vcfkit/__init__.py | __version__ = "0.2.2" | __version__ = "0.2.1" | mit | Python |
daa5323582325ac7278f2b91b73169d41b82ac97 | abort on unknown paper size | brechtm/rinohtype,beni55/rinohtype,beni55/rinohtype,brechtm/rinohtype,brechtm/rinohtype | rinoh/tool.py | rinoh/tool.py |
import argparse
import os
from rinoh import paper
from rinoh.backend import pdf
from rinoh.frontend.rst import ReStructuredTextParser
from rinohlib.templates.article import Article, ArticleOptions
def main():
parser = argparse.ArgumentParser(description='Render a reStructuredText '
... |
import argparse
import os
from rinoh import paper
from rinoh.backend import pdf
from rinoh.frontend.rst import ReStructuredTextParser
from rinohlib.templates.article import Article, ArticleOptions
def main():
parser = argparse.ArgumentParser(description='Render a reStructuredText '
... | agpl-3.0 | Python |
81aaf1f4086708a752eef50fba3082b916c140fb | Update parseArgs method | jabocg/ptyme | ptyme/ptyme.py | ptyme/ptyme.py | #!/bin/env python3
# python 3
import sys
def main():
print(sys.argv)
if len(sys.argv) == 1:
print("give a string for time, _h_m_s for hours, mins, secs, optional"
"string for title")
sys.exit()
parseArgsChar(sys.argv[1])
# go through via characters
def parseArgsChar(timeSt... | #!/bin/env python3
from sys import argv
def main():
parseArgs()
print("Nope.")
print(argv)
# go through via characters
def parseArgsChar():
pass()
# while this works, it only works when _h_m_s format
# might want to not do that
def parseArgs():
if len(argv) > 1:
time = argv[1].split('h')... | mit | Python |
3e2be4a8a597cfaa11b625eb6a94a4a18061df9b | Update develop version to 1.7-dev since 1.6 is in production | emory-libraries/readux,emory-libraries/readux,emory-libraries/readux | readux/__init__.py | readux/__init__.py | __version_info__ = (1, 7, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environ... | __version_info__ = (1, 6, 1, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environm... | apache-2.0 | Python |
73aa3651c71a147ba92e1b99dd0361a11126cc2a | simplify code | hhsprings/cython,mrGeen/cython,mcanthony/cython,achernet/cython,hhsprings/cython,fabianrost84/cython,encukou/cython,slonik-az/cython,marscher/cython,ABcDexter/cython,c-blake/cython,hhsprings/cython,acrispin/cython,mcanthony/cython,acrispin/cython,andreasvc/cython,cython/cython,marscher/cython,acrispin/cython,da-woods/c... | Cython/Plex/Errors.py | Cython/Plex/Errors.py | #=======================================================================
#
# Python Lexical Analyser
#
# Exception classes
#
#=======================================================================
class PlexError(Exception):
message = ""
class PlexTypeError(PlexError, TypeError):
pass
class PlexValue... | #=======================================================================
#
# Python Lexical Analyser
#
# Exception classes
#
#=======================================================================
class PlexError(Exception):
message = ""
class PlexTypeError(PlexError, TypeError):
pass
class PlexValue... | apache-2.0 | Python |
7f40f9bdaba3f595b286b5e83570ac6c468ca899 | Update district.py | mikelambson/tcid,mikelambson/tcid,mikelambson/tcid,mikelambson/tcid | site/models/district.py | site/models/district.py | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
class District(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
name = DB.Column(DB.String(20));
created_by = DB.Column(DB.Integer, DB.ForeignKey('users.id'));
created_at = DB.Column... | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
class District(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
name = DB.Column(DB.VarChar(20));
created_by = DB.Column(DB.Integer, DB.ForeignKey('users.id'));
created_at = DB.Colum... | bsd-3-clause | Python |
06e291fa8d9c2ca4b8ba136e4e724fa6ed9e25b2 | fix version back to 2.9 so we can use bump/minor | ginkgobioworks/edge,ginkgobioworks/edge,ginkgobioworks/edge,ginkgobioworks/edge | src/edge/__init__.py | src/edge/__init__.py | from django.db.backends.signals import connection_created
__version__ = '2.9.0'
def import_gff(name, fn):
"""
Creates a new genome using the specified GFF file.
name: Name of genome
fn: path to GFF file
"""
from edge.models import Genome
if Genome.objects.filter(name=name).count() > 0:
... | from django.db.backends.signals import connection_created
__version__ = '2.9.1'
def import_gff(name, fn):
"""
Creates a new genome using the specified GFF file.
name: Name of genome
fn: path to GFF file
"""
from edge.models import Genome
if Genome.objects.filter(name=name).count() > 0:
... | mit | Python |
66d94ada3def2bb1708333a3d9856663e59a9585 | add pattern field to campaign | byteweaver/django-referral,Chris7/django-referral | referral/models.py | referral/models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
import settings
class Campaign(models.Model):
name = models.CharField(_("Name"), max_length=255, unique=True)
description = models.TextField(_("Description"), blank=True, null=True... | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
import settings
class Campaign(models.Model):
name = models.CharField(_("Name"), max_length=255, unique=True)
description = models.TextField(_("Description"), blank=True, null=True... | mit | Python |
7f34a59f632cc4a46a53b31cb0ec28d4dfa03691 | fix upper limit | smrmkt/project_euler | problem_034.py | problem_034.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to
the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
import math
import timeit
def calc():
eqs = []... | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to
the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
import math
import timeit
def calc():
eqs = []... | mit | Python |
af93302a24ab87e039b66f1f04c3f8802b8610e4 | add problem sentence | smrmkt/project_euler | problem_051.py | problem_051.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
By replacing the 1st digit of the 2-digit number *3,
it turns out that six of the nine possible values:
13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit,
this 5-digit number is the first example having seven prime... | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
'''
import math
import timeit
primes = [2, 3, 5, 7]
def is_prime(n):
for p in primes:
if n % p == 0:
return False
for i in range(max(primes), int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
def replace... | mit | Python |
efb32929d39ea0657a2abff4930d4e0454f5cc91 | increase max-age on CDN | AFP-Graphics/pym.js,nprapps/pym.js,nprapps/pym.js,AFP-Graphics/pym.js,nprapps/pym.js | nprapps_tools/fabfile.py | nprapps_tools/fabfile.py | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
import shutil
import glob
import gzip
import logging
from distutils.util import strtobool
from fabric.api import task, local
LOG_FORMAT = '%(levelname)s:%(name)s:%(asctime)s: %(message)s'
LOG_LEVEL = logging.INFO
# GLOBAL SETTINGS
cwd = os.path.dirname(__file__)
... | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
import shutil
import glob
import gzip
import logging
from distutils.util import strtobool
from fabric.api import task, local
LOG_FORMAT = '%(levelname)s:%(name)s:%(asctime)s: %(message)s'
LOG_LEVEL = logging.INFO
# GLOBAL SETTINGS
cwd = os.path.dirname(__file__)
... | mit | Python |
ce0488b4b421f774759124e84416367aa21e4a1d | fix the reporters admin. it had a duplicate "identity" and no "backend" in the list of displayed columns. | peterayeni/rapidsms,catalpainternational/rapidsms,ehealthafrica-ci/rapidsms,dimagi/rapidsms,peterayeni/rapidsms,unicefuganda/edtrac,peterayeni/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,ken-muturi/rapidsms,eHealthAfrica/rapidsms,ken-muturi/rapidsms,lsgunth/rapidsms,eHealthA... | reporters/admin.py | reporters/admin.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.contrib import admin
from reporters.models import *
from django.core.urlresolvers import reverse
class ReporterAdmin(admin.ModelAdmin):
list_display = ('id','alias','first_name', 'last_name')
list_filter = []
class PersistantConnectionAdmin... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.contrib import admin
from reporters.models import *
from django.core.urlresolvers import reverse
class ReporterAdmin(admin.ModelAdmin):
list_display = ('id','alias','first_name', 'last_name')
list_filter = []
class PersistantConnectionAdmin... | bsd-3-clause | Python |
d71869398944b03486575732584c3349684a8eb3 | fix default cache provider | yacomink/inyourface,yacomink/inyourface | inyourface/DefaultCacheProvider.py | inyourface/DefaultCacheProvider.py | import os, sqlite3
class CacheProvider(object):
def __init__(self, cache_dir):
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
conn = sqlite3.connect(cache_dir + 'faces.db')
self.cache_connection = conn
c = conn.cursor()
# Create table
c.execute... | import os, sqlite3
class CacheProvider(object):
def __init__(self, cache_dir):
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
conn = sqlite3.connect(cache_dir + 'faces.db')
self.cache_connection = conn
c = conn.cursor()
# Create table
c.execute... | mit | Python |
8336e18e8a954e691acb4fead463bdf9e5c432a1 | add gpd support to pacbio renaming | jason-weirather/Au-public,jason-weirather/Au-public,jason-weirather/Au-public,jason-weirather/Au-public | iron/utilities/rename_to_pacbio.py | iron/utilities/rename_to_pacbio.py | #!/usr/bin/python
import sys,argparse
from SequenceBasics import FastaHandleReader, FastqHandleReader
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input',help="Use - for STDIN")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--fasta',action='store_true')
... | #!/usr/bin/python
import sys,argparse
from SequenceBasics import FastaHandleReader, FastqHandleReader
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input',help="Use - for STDIN")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--fasta',action='store_true')
... | apache-2.0 | Python |
a70e76d043a452bcd3962896fa7281e4499fc2af | Package Bonniepp adding sbin to PATH (#16124) | LLNL/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack,iulian787/spack,LLNL/spack,LLNL/spack,iulian787/spack,iulian787/spack | var/spack/repos/builtin/packages/bonniepp/package.py | var/spack/repos/builtin/packages/bonniepp/package.py | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Bonniepp(AutotoolsPackage):
"""Bonnie++ is a benchmark suite that is aimed at performing a... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Bonniepp(AutotoolsPackage):
"""Bonnie++ is a benchmark suite that is aimed at performing a... | lgpl-2.1 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.