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 |
|---|---|---|---|---|---|---|---|---|
3e9afd8599f85232f363a809072a56941e5b9c77 | Update cybergis-script-geoserver-import-styles.py | state-hiu/cybergis-scripts,state-hiu/cybergis-scripts | bin/cybergis-script-geoserver-import-styles.py | bin/cybergis-script-geoserver-import-styles.py | from base64 import b64encode
from optparse import make_option
import json
import urllib
import urllib2
import argparse
import time
import sys
import os
import subprocess
#==#
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib', 'cybergis')))
import gs._geoserver_import_styles
#==#
parser... | from base64 import b64encode
from optparse import make_option
import json
import urllib
import urllib2
import argparse
import time
import sys
import os
import subprocess
#==#
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib', 'cybergis')))
import gs._geoserver_import_styles
#==#
parser... | mit | Python |
d7ce75a2fd788eba33deace16a1c00404fa45bc6 | fix typo | lilydjwg/nvchecker | nvchecker/source/cmd.py | nvchecker/source/cmd.py | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import asyncio
import structlog
logger = structlog.get_logger(logger_name=__name__)
async def get_version(name, conf):
cmd = conf['cmd']
p = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stde... | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import asyncio
import structlog
logger = structlog.get_logger(logger_name=__name__)
async def get_version(name, conf):
cmd = conf['cmd']
p = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stde... | mit | Python |
4fc947a1710628a298340421e505db74abab6689 | Modify example conftest to support testing code that uses gevent. (#47) | dropbox/pyannotate | example/example_conftest.py | example/example_conftest.py | # Configuration for pytest to automatically collect types.
# Thanks to Guilherme Salgado.
import pytest
def pytest_collection_finish(session):
"""Handle the pytest collection finish hook: configure pyannotate.
Explicitly delay importing `collect_types` until all tests have
been collected. This gives ge... | # Configuration for pytest to automatically collect types.
# Thanks to Guilherme Salgado.
import pytest
from pyannotate_runtime import collect_types
collect_types.init_types_collection()
@pytest.fixture(autouse=True)
def collect_types_fixture():
collect_types.resume()
yield
collect_types.pause()
def p... | apache-2.0 | Python |
badd2b069fe2c0fedc4d6a971550fd93d15ed1e6 | Fix test-case. | lwoydziak/mockito-python,kaste/mockito-python | mockito_test/aliases_test.py | mockito_test/aliases_test.py | #!/usr/bin/env python
# coding: utf-8
from test_base import TestBase
from mockito import mock, Mock
import warnings
class AliasesTest(TestBase):
def testMockCreationAlias(self):
warnings.simplefilter("ignore")
self.assertTrue(isinstance(Mock(), mock))
if __name__ == '__main__':
import unitt... | #!/usr/bin/env python
# coding: utf-8
from test_base import TestBase
from mockito import mock, Mock
class AliasesTest(TestBase):
def testMockCreationAlias(self):
self.assertEquals(mock, Mock)
if __name__ == '__main__':
import unittest
unittest.main()
| mit | Python |
90edeb2ba64656c97542abcb506a2845cb1cc7bc | add compareYaml() | zer0main/bacteria-core,zer0main/bacteria-core,zer0main/bacteria-core | integration_tests/check_yaml.py | integration_tests/check_yaml.py | #!/usr/bin/python3
""" Check results of execution of integration tests.
Compare .yaml files:
- Generated by integration tests
- Canonized correct results (reference data)
"""
import argparse
import yaml
"""
Compare yaml objects:
add possibility of specifying the correct value ranges in
expected object.
EXAMPLES:... | #!/usr/bin/python3
""" Check results of execution of integration tests.
Compare .yaml files:
- Generated by integration tests
- Canonized correct results (reference data)
"""
import argparse
import yaml
def compare(expected_filename, observed_filename):
with open(expected_filename) as expected_file:
e... | mit | Python |
f3248f6efba54d0dbb5601646bc57e03cb52eabf | Fix string formatting, can't have trailing comma | e-koch/VLA_Lband,e-koch/VLA_Lband | 16B/pipeline4.6.0_custom/EVLA_pipe_statwt_lines.py | 16B/pipeline4.6.0_custom/EVLA_pipe_statwt_lines.py | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... | mit | Python |
eaf86875ef04fcc02a3a0d7e0bb6904a2827458c | handle projecting and removal of extraneous fields | agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro | scripts/nightly/update_sgid.py | scripts/nightly/update_sgid.py | '''
update_sgid.py
handles updating data in SGID from the app database
'''
import logging
from os import path
from pathlib import Path
import arcpy
import settings
from update_fgdb import commonFields
from swapper import swapper
period_replacement = '___'
logger = logging.getLogger('forklift')
def update_sgid_fo... | '''
update_sgid.py
handles updating data in SGID from the app database
'''
import logging
from os import path
import arcpy
import settings
from swapper import swapper
period_replacement = '___'
logger = logging.getLogger('forklift')
def update_sgid_for_crates(crates_from_slip):
logger.info('getting SGID name... | mit | Python |
192f31e6937d078f523ca9196e4a89b7ad5edffc | Update relax.py | MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab | home/hairygael/GESTURES/WORKINPROGRESS/relax.py | home/hairygael/GESTURES/WORKINPROGRESS/relax.py | def relax():
global MoveBodyRandom
MoveBodyRandom=0
global MoveHeadRandom
if (i01.eyesTracking.getOpenCV().capturing == true)
MoveHeadRandom=0
i01.setHandSpeed("left", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setHandSpeed("right", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setArmSpe... | def relax():
global MoveHeadRandom
if (i01.eyesTracking.getOpenCV().capturing == true)
MoveHeadRandom = 0
else
MoveHeadRandom = 1
MoveHeadTimer.startClock()
i01.setHandSpeed("left", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setHandSpeed("right", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)... | apache-2.0 | Python |
5df9fc66ddec18e86f727000fe1b9511672e3a07 | Update plugin_a.py | cgarjun/pyplug | example_plugins/plugin_a.py | example_plugins/plugin_a.py | def main(arg_a, arg_b):
print "plugin_a"
print arg_a
print arg_b
| def main(myarg, jack):
print "plugin_a"
print myarg
print jack
| mit | Python |
9e7890ea12578499c0f5da16e96010ec4c5c11c9 | Remove prints | ekumenlabs/terminus,ekumenlabs/terminus | terminus/builders/procedural_city_builder.py | terminus/builders/procedural_city_builder.py | from geometry.point import Point
from models.city import City
from models.road import Street, Trunk
from models.block import Block
from models.building import Building
from models.ground_plane import GroundPlane
from procedural_city.vertex import Vertex
import pickle
class ProceduralCityBuilder(object):
def __i... | from geometry.point import Point
from models.city import City
from models.road import Street, Trunk
from models.block import Block
from models.building import Building
from models.ground_plane import GroundPlane
from procedural_city.vertex import Vertex
import pickle
class ProceduralCityBuilder(object):
def __i... | apache-2.0 | Python |
717991ce5600bae1cd543941ef74ffe9d31b3d17 | Make time first column | lateefj/asyncinflux | examples/influx_data_gen.py | examples/influx_data_gen.py | import time
import os
from random import random, randint
from gevent import sleep
from asyncinflux import AsyncWriter
from influxdb import client as influxdb
db = influxdb.InfluxDBClient(database="test")
writer = AsyncWriter(db)
writer.start()
while True:
cpu = os.times()
point = [{
"points": [[time.t... | import time
import os
from random import random, randint
from gevent import sleep
from asyncinflux import AsyncWriter
from influxdb import client as influxdb
db = influxdb.InfluxDBClient(database="test")
writer = AsyncWriter(db)
writer.start()
while True:
cpu = os.times()
point = [{
"time": time.time... | apache-2.0 | Python |
aac8b0a7a42457df2414b3970148443ed184a06f | Fix flake8 errors for middleware | incuna/django-rewrite-external-links,incuna/django-rewrite-external-links | rewrite_external_links/middleware.py | rewrite_external_links/middleware.py | import HTMLParser
import re
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.defaultfilters import urlencode
SAFE_EXTERNAL_LINK_PATTERNS = getattr(settings, 'SAFE_EXTERNAL_LINK_PATTERNS', ())
safe_urls = ''
if SAFE_EXTERNAL_LINK_PATTERNS:
safe_urls = '(?!(' + '|'... | import re
import HTMLParser
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.defaultfilters import urlencode
SAFE_EXTERNAL_LINK_PATTERNS = getattr(settings, 'SAFE_EXTERNAL_LINK_PATTERNS', ())
safe_urls = ''
if SAFE_EXTERNAL_LINK_PATTERNS:
safe_urls = '(?!(' + '|'... | bsd-2-clause | Python |
b9d1d97668f13bbc2109b9502f72c6bf3846abed | Fix http_server example (#88) | ttu/ruuvitag-sensor,ttu/ruuvitag-sensor | examples/http_server.py | examples/http_server.py | """
Simple http server, that returns data in json.
Executes get data for sensors in the background.
Endpoints:
http://0.0.0.0:5000/data
http://0.0.0.0:5000/data/<mac>
Requires:
Flask - pip install flask
"""
from datetime import datetime
import json
from multiprocessing import Manager
from concurrent.futu... | """
Simple http server, that returns data in json.
Executes get data for sensors in the background.
Endpoints:
http://0.0.0.0:5000/data
http://0.0.0.0:5000/data/<mac>
Requires:
Flask - pip install flask
"""
from datetime import datetime
import json
from multiprocessing import Manager
from concurrent.futu... | mit | Python |
eb7cf7376b6c81f5d1792441f772de2771563c61 | Fix Reuters example | llcao/keras,pthaike/keras,dhruvparamhans/keras,xiaoda99/keras,jmportilla/keras,JasonTam/keras,ogrisel/keras,imcomking/Convolutional-GRU-keras-extension-,gavinmh/keras,jhauswald/keras,danielforsyth/keras,rlkelly/keras,johmathe/keras,MagicSen/keras,iScienceLuvr/keras,rudaoshi/keras,nt/keras,tencrance/keras,bottler/keras,... | examples/reuters_mlp.py | examples/reuters_mlp.py | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.datasets import reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.utils import np_utils
from... | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.datasets import reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.utils import np_utils
from... | mit | Python |
d9204451c042c7ca80aa558ea280d74e5650de25 | add shots | marceloonit/code_samples | hangman.py | hangman.py |
import getpass
secret_word = getpass.getpass('Enter the word to be played with: ')
length_word = len(secret_word)
tentativas = length_word
while True:
guess = input('Enter a letter: ')
if len(guess) != 1:
continue
if guess in secret_word:
print('JA')
else:
tentativas -=... |
import getpass
secret_word = getpass.getpass('Enter the word to be played with: ')
length_word = len(secret_word)
tentativas = length_word
while True:
guess = input('Enter a letter: ')
if len(guess) != 1:
continue
if guess in secret_word:
print('JA')
else:
tentativas -=... | unlicense | Python |
4874f43cac0ab16e68d3527f08562e26ff82213f | fix example | rootpy/rootpy,kreczko/rootpy,ndawe/rootpy,ndawe/rootpy,rootpy/rootpy,ndawe/rootpy,kreczko/rootpy,kreczko/rootpy,rootpy/rootpy | examples/tree/tree_array.py | examples/tree/tree_array.py | #!/usr/bin/env python
from rootpy.tree import Tree, TreeModel
from rootpy.io import open
from rootpy.types import *
from random import gauss
f = open("test.root", "recreate")
# define the model
class Event(TreeModel):
x = FloatCol()
y = FloatCol()
z = FloatCol()
i = IntCol()
tree = Tree("test", mo... | #!/usr/bin/env python
from rootpy.tree import Tree, TreeModel
from rootpy.io import open
from rootpy.types import *
from random import gauss
f = open("test.root", "recreate")
# define the model
class Event(TreeModel):
x = FloatCol()
y = FloatCol()
z = FloatCol()
i = IntCol()
tree = Tree("test", mo... | bsd-3-clause | Python |
f4661c0fe46c3ef57c5f3beca26a0e9fa67b0b07 | Remove BOOST_TEST_DYN_LINK define for boost_unit_test_framework win build | tuttleofx/sconsProject | autoconf/boost_unit_test_framework.py | autoconf/boost_unit_test_framework.py | from _external import *
from boost import *
class BoostUnittestframeworkChecker(BaseLibChecker):
def __init__( self ):
self.name = 'boost_unit_test_framework'
self.libs = [self.name]
self.language = 'c++',
self.dependencies=[boost]
def configure(self, project, env):
... | from _external import *
from boost import *
class BoostUnittestframeworkChecker(BaseLibChecker):
def __init__( self ):
self.name = 'boost_unit_test_framework'
self.libs = [self.name]
self.language = 'c++',
self.dependencies=[boost]
def configure(self, project, env):
... | mit | Python |
ea1c095fb12c4062616ee0d38818ab1baaabd1eb | Test deserialization of comm message following upload | ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets | ipywidgets/widgets/tests/test_widget_upload.py | ipywidgets/widgets/tests/test_widget_upload.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from unittest import TestCase
from traitlets import TraitError
from ipywidgets import FileUpload
class TestFileUpload(TestCase):
def test_construction(self):
uploader = FileUpload()
# Default
... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from unittest import TestCase
from traitlets import TraitError
from ipywidgets import FileUpload
class TestFileUpload(TestCase):
def test_construction(self):
uploader = FileUpload()
# Default
... | bsd-3-clause | Python |
c5730d19d41f7221c4108f340d0ff8be26c24c74 | Make tag_suggestions test less flaky | noamelf/Open-Knesset,otadmor/Open-Knesset,habeanf/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,navotsil/Open-Knesset,noamelf/Open-Knesset,navotsil/Open-Knesset,navotsil/Open-Knesset,otadmor/Open-Knesset,noamelf/Open-Knesset,otadmor/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,jspan/Ope... | auxiliary/tag_suggestions/__init__.py | auxiliary/tag_suggestions/__init__.py | from tagging.models import Tag, TaggedItem
from django.contrib.contenttypes.models import ContentType
def approve(admin, request, tag_suggestions):
for tag_suggestion in tag_suggestions:
obj = tag_suggestion.object
ct = ContentType.objects.get_for_model(obj)
tag, t_created = Tag.objects.... | from tagging.models import Tag, TaggedItem
from django.contrib.contenttypes.models import ContentType
from auxiliary.models import TagSuggestion
from django.db import IntegrityError
def approve(admin, request, tag_suggestions):
for tag_suggestion in tag_suggestions:
object = tag_suggestion.object
t... | bsd-3-clause | Python |
032713f8b9120afc31642469560f38a49e539bf2 | Add asserts to test_response.py | jparyani/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp | test/test_response.py | test/test_response.py | import pytest
import capnp
import os
import time
import test_response_capnp
class FooServer(test_response_capnp.Foo.Server):
def __init__(self, val=1):
self.val = val
def foo(self, **kwargs):
return 1
class BazServer(test_response_capnp.Baz.Server):
def __init__(self, val=1):
sel... | import pytest
import capnp
import os
import time
import test_response_capnp
class FooServer(test_response_capnp.Foo.Server):
def __init__(self, val=1):
self.val = val
def foo(self, **kwargs):
return 1
class BazServer(test_response_capnp.Baz.Server):
def __init__(self, val=1):
sel... | bsd-2-clause | Python |
3d42e818b68ee600bc1baf434a3266586d55cab2 | Update test_distns.py | stanfordmlgroup/ngboost,stanfordmlgroup/ngboost | ngboost/tests/test_distns.py | ngboost/tests/test_distns.py | import pytest
@pytest.fixture(scope="module")
def dists_scores():
from ngboost.distns import Bernoulli, k_categorical, Normal, LogNormal, Exponential
from ngboost.scores import LogScore, CRPScore
return {
Bernoulli:[LogScore],
k_categorical(4): [LogScore],
Normal: [LogScore, CRPScore],
LogNormal: [LogScor... | import pytest
@pytest.fixture(scope="module")
def dists_scores():
from ngboost.distns import Bernoulli, k_categorical, Normal, LogNormal, Exponential
from ngboost.scores import LogScore, CRPScore
return {
Bernoulli:[LogScore],
k_categorical(4): [LogScore],
Normal: [LogScore, CRPScore],
LogNormal: [LogScor... | apache-2.0 | Python |
ad11c4f9845e1979c9106c9d9914edc315e3f0bf | Add clarification on response code exception text | yakky/django-statictemplate,bdon/django-statictemplate,ojii/django-statictemplate | statictemplate/management/commands/statictemplate.py | statictemplate/management/commands/statictemplate.py | # -*- coding: utf-8 -*-
from contextlib import contextmanager, nested
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand... | # -*- coding: utf-8 -*-
from contextlib import contextmanager, nested
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand... | bsd-3-clause | Python |
85beb625cd4fd00b9472d5d81ab003fdf1d5d4c0 | remove unused dependencies | DevMine/devmine-core | devmine/app/controllers/features_controller.py | devmine/app/controllers/features_controller.py | import json
from devmine.app.models.feature import Feature
from devmine.app.controllers.application_controller import (
ApplicationController
)
from devmine.app.helpers import application_helper as ah
class FeaturesController(ApplicationController):
"""Class for handling requests on the feature resource."""
... | import json
from io import StringIO
from bottle import abort
import logging
from devmine.app.models.feature import Feature
from devmine.app.controllers.application_controller import (
ApplicationController
)
from devmine.app.helpers import application_helper as ah
class FeaturesController(ApplicationController):
... | bsd-3-clause | Python |
48bbcdbe9cc046c196ada3410dd27dd189904943 | Fix dump full version order for modern versions of gcc | nerdvegas/rez,instinct-vfx/rez,instinct-vfx/rez,nerdvegas/rez | src/rez/bind/gcc.py | src/rez/bind/gcc.py | from __future__ import absolute_import
from rez.bind._utils import find_exe, extract_version, make_dirs, log
from rez.package_maker__ import make_package
from rez.utils.lint_helper import env
from rez.utils.platform_ import platform_
import os.path
from rez.exceptions import RezBindError
from rez.system import system
... | from __future__ import absolute_import
from rez.bind._utils import find_exe, extract_version, make_dirs, log
from rez.package_maker__ import make_package
from rez.utils.lint_helper import env
from rez.utils.platform_ import platform_
import os.path
from rez.exceptions import RezBindError
from rez.system import system
... | apache-2.0 | Python |
b7dd30f2b6ddc054929b74433a25e69a36e5ec56 | use CSV for getting tags | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | gem/migrations/0014_add_default_tags.py | gem/migrations/0014_add_default_tags.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import csv
from django.db import migrations
from molo.core.models import (
SiteLanguage, Tag, TagIndexPage, PageTranslation)
def default_tags(apps, schema_editor):
main_lang = SiteLanguage.objects.filter(
is_active=True, is_main_language=... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from molo.core.models import (
SiteLanguage, Tag, TagIndexPage, Main, PageTranslation)
def add_default_tags(apps, schema_editor):
main_lang = SiteLanguage.objects.filter(
is_active=True, is_main_language=... | bsd-2-clause | Python |
85b269bde76af2b8d15dc3b1e9f7cf882fc18dc2 | Add tests for multiple gibson inserts | dtarnowski16/labcalc,mandel01/labcalc,mjmlab/labcalc | labcalc/tests/test_functions.py | labcalc/tests/test_functions.py | #!/usr/bin/env python3
from labcalc.run import *
from labcalc import gibson
# labcalc.gibson
def test_gibson_one_insert():
d = {'vector': [5000, 50], 'insert1': [300, 50]}
assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24}
def test_gibson_two_inserts():
d = {'vector': [5000, 50], 'insert1':... | #!/usr/bin/env python3
from labcalc.run import *
from labcalc import gibson
# labcalc.gibson
def test_gibson_one_insert():
d = {'insert1': [300, 50], 'vector': [5000, 50]}
assert gibson.gibson_calc(d) == {'insert1': 0.24, 'vector': 2.0}
| bsd-3-clause | Python |
82d4ea7bb7f23be3947de0bca049f66e0dbbebbe | use lcm instead of vcm (#1597) | GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples | language/automl/dataset_test.py | language/automl/dataset_test.py | #!/usr/bin/env python
# Copyright 2018 Google LLC
#
# 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 ... | #!/usr/bin/env python
# Copyright 2018 Google LLC
#
# 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 ... | apache-2.0 | Python |
37f697bb79f9d7597024406c0c650f5166886f86 | Revise for loop index | bowen0701/algorithms_data_structures | lc0014_longest_common_prefix.py | lc0014_longest_common_prefix.py | """Leetcode 14. Longest Common Prefix.
Easy
URL: https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
... | """Leetcode 14. Longest Common Prefix.
Easy
URL: https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
... | bsd-2-clause | Python |
caaa807a4226bfdeb18681f8ccb6119bd2caa609 | Add COUNTRY_APP to settings exposed to the templates | hzj123/56th,mysociety/pombola,hzj123/56th,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola... | pombola/core/context_processors.py | pombola/core/context_processors.py | from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
... | from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
... | agpl-3.0 | Python |
f25f3f0ec68342919f556522ef100464c6241a40 | Copy demo purchase_6 on test | OCA/purchase-workflow,OCA/purchase-workflow | purchase_manual_currency/tests/test_purchase_manual_currency.py | purchase_manual_currency/tests/test_purchase_manual_currency.py | # Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests.common import Form, TransactionCase
class TestPurchaseManualCurrency(TransactionCase):
def setUp(self):
super().setUp... | # Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests.common import Form, TransactionCase
class TestPurchaseManualCurrency(TransactionCase):
def setUp(self):
super().setUp... | agpl-3.0 | Python |
5e32fdff266b546a6190a898fbab375051e01448 | Remove redundant ReCollect Waste test fixture (#79907) | mezz64/home-assistant,w1ll1am23/home-assistant,nkgilley/home-assistant,nkgilley/home-assistant,mezz64/home-assistant,w1ll1am23/home-assistant | tests/components/recollect_waste/conftest.py | tests/components/recollect_waste/conftest.py | """Define test fixtures for ReCollect Waste."""
from datetime import date
from unittest.mock import patch
from aiorecollect.client import PickupEvent, PickupType
import pytest
from homeassistant.components.recollect_waste.const import (
CONF_PLACE_ID,
CONF_SERVICE_ID,
DOMAIN,
)
from homeassistant.setup im... | """Define test fixtures for ReCollect Waste."""
from datetime import date
from unittest.mock import patch
from aiorecollect.client import PickupEvent, PickupType
import pytest
from homeassistant.components.recollect_waste.const import (
CONF_PLACE_ID,
CONF_SERVICE_ID,
DOMAIN,
)
from homeassistant.setup im... | apache-2.0 | Python |
f6ebae97b427b4cfcb946103fa917164ea06cc49 | Comment out print for heroku | codeforamerica/mdc-feedback,codeforamerica/mdc-feedback,codeforamerica/mdc-feedback,codeforamerica/mdc-feedback | feedback/dashboard/views.py | feedback/dashboard/views.py | # -*- coding: utf-8 -*-
import datetime
import requests
import json
from flask import (
Blueprint, render_template, request, flash
)
from flask.ext.login import (
login_required
)
blueprint = Blueprint(
"dashboard", __name__,
template_folder='../templates',
static_folder="../static"
)
stats = {}... | # -*- coding: utf-8 -*-
import datetime
import requests
import json
from flask import (
Blueprint, render_template, request, flash
)
from flask.ext.login import (
login_required
)
blueprint = Blueprint(
"dashboard", __name__,
template_folder='../templates',
static_folder="../static"
)
stats = {}... | mit | Python |
5c9edb2ae6e35e1b10d7d51b493eef569d751af2 | put back rmq tests | CyberReboot/vent,bpagon13/vent,cglewis/vent,Jeff-Wang93/vent,CyberReboot/vent,cprafullchandra/vent,Joecakes4u/vent,lilchurro/vent,bpagon13/vent,Joecakes4u/vent,cprafullchandra/vent,bpagon13/vent,CyberReboot/vent,cglewis/vent,lilchurro/vent,Jeff-Wang93/vent,Jeff-Wang93/vent,cglewis/vent,lilchurro/vent | core/rmq-es-connector/test_rmq_es_connector.py | core/rmq-es-connector/test_rmq_es_connector.py | import pytest
import rmq_es_connector
class Method():
""" create mock method object """
routing_key = None
def __init__(self, routing_key=""):
self.routing_key = routing_key
def test_rmq_es_connector_connections():
""" tests the connections function """
rmq_es = rmq_es_connector.RmqEs()
... | import pytest
import rmq_es_connector
"""
class Method():
""" create mock method object """
routing_key = None
def __init__(self, routing_key=""):
self.routing_key = routing_key
def test_rmq_es_connector_connections():
""" tests the connections function """
rmq_es = rmq_es_connector.RmqEs... | apache-2.0 | Python |
cafd23b13165b1b850fa693baaa6091bc42d8182 | remove .tests.backend.ini2.test_40_loads_with_dict_type_option as it was merged into .test.backend.common.Test_10_dumps_and_loads | ssato/python-anyconfig,ssato/python-anyconfig | tests/backend/ini2.py | tests/backend/ini2.py | #
# Copyright (C) 2012 - 2017 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods
from __future__ import absolute_import
import anyconfig.backend.ini as TT
import tests.backend.common as TBC
# :seealso: `tests.backend.common.CNF_0`
CNF_0_S = """\... | #
# Copyright (C) 2012 - 2017 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods
from __future__ import absolute_import
import anyconfig.backend.ini as TT
import tests.backend.common as TBC
# :seealso: `tests.backend.common.CNF_0`
CNF_0_S = """\... | mit | Python |
8de4cb6e314da95b243f140f53b3c77487695a55 | Correct zip() error in run_cyclus function | Baaaaam/cyBaM,gonuke/cycamore,cyclus/cycaless,gonuke/cycamore,Baaaaam/cycamore,jlittell/cycamore,rwcarlsen/cycamore,Baaaaam/cyBaM,Baaaaam/cycamore,rwcarlsen/cycamore,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,rwcarlsen/cycamore,Baaaaam/cycamore,jlittell/cycamore,Baaaaam/cyBaM,Baaaaam/cyCLASS,cyclus/cycaless,Ba... | tests/cyclus_tools.py | tests/cyclus_tools.py | #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
cmd = [cyclus, ... | #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in zip(sim_files):
holdsrtn = [1] # needed because nose does not send() to test generator
cmd = [cyc... | bsd-3-clause | Python |
903747807df1953d4f7ae173aa223150ac6921d8 | Update custom.py | satishgoda/learningqt,satishgoda/learningqt | basics/modelview/columnview/custom.py | basics/modelview/columnview/custom.py | class CustomColumnView(ColumnView):
def __init__(self, *args, **kwargs):
super(CustomColumnView, self).__init__(*args, **kwargs)
self.activated.connect(self.onActivated)
def keyPressEvent(self, event):
super(CustomColumnView, self).keyPressEvent(event)
index = self.selectedI... | class CustomColumnView(QtGui.QColumnView):
def __init__(self, *args, **kwargs):
super(CustomColumnView, self).__init__(*args, **kwargs)
self.activated.connect(self.onActivated)
def keyPressEvent(self, event):
super(CustomColumnView, self).keyPressEvent(event)
index = self.se... | mit | Python |
47d9a8df136e235f49921d4782c5e392b0101107 | Make _cleaned_subject migration match declared schema. | Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,Eagl... | migrations/versions/147_add_cleaned_subject.py | migrations/versions/147_add_cleaned_subject.py | """add cleaned subject
Revision ID: 486c7fa5b533
Revises: 1d7a72222b7c
Create Date: 2015-03-10 16:33:41.740387
"""
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn ... | """add cleaned subject
Revision ID: 486c7fa5b533
Revises: 1d7a72222b7c
Create Date: 2015-03-10 16:33:41.740387
"""
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn ... | agpl-3.0 | Python |
cbc7d1f3ddd986664ea1050c4b1ac1251de3ff85 | Add examples of how to get relevant attributes from the response. | eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot | incoming_mail.py | incoming_mail.py | #!/usr/bin/env python
#
# Copyright 2010 Eric Entzel <eric@ubermac.net>
#
from ecal_wsgi import EcalWSGIApplication
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from gdata.service import RequestError
import logging
import urllib
from... | #!/usr/bin/env python
#
# Copyright 2010 Eric Entzel <eric@ubermac.net>
#
from ecal_wsgi import EcalWSGIApplication
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from gdata.service import RequestError
import logging
import urllib
from... | mit | Python |
452c32ef11ae6470f71dce534bcb6ee6809298c8 | Remove print statements | tony/django-docutils,tony/django-docutils | django_docutils/lib/transforms/font_awesome.py | django_docutils/lib/transforms/font_awesome.py | import re
from docutils import nodes, utils
from docutils.transforms import Transform
from django_docutils.lib.settings import BASED_LIB_RST
url_patterns = BASED_LIB_RST.get('font_awesome', {}).get('url_patterns', {})
class InjectFontAwesome(Transform):
default_priority = 680
def apply(self):
for... | import re
from docutils import nodes, utils
from docutils.transforms import Transform
from django_docutils.lib.settings import BASED_LIB_RST
url_patterns = BASED_LIB_RST.get('font_awesome', {}).get('url_patterns', {})
class InjectFontAwesome(Transform):
default_priority = 680
def apply(self):
for ... | mit | Python |
3f6f2c49fde65e31dc189837ac2f62e8de58dbc4 | set up testing enviroment | amosboldor/Portfolio-Site,amosboldor/Portfolio-Site | portfolio/portfolio/tests/tests.py | portfolio/portfolio/tests/tests.py | """Testing File."""
import unittest
import transaction
import datetime
from portfolio.models.meta import Base
from pyramid import testing
def dummy_request(dbsession):
"""Dummy Request."""
return testing.DummyRequest(dbsession=dbsession)
class BaseTest(unittest.TestCase):
"""Base Test."""
def setUp... | """Testing File."""
import unittest
import transaction
from pyramid import testing
def dummy_request(dbsession):
"""Dummy Request."""
return testing.DummyRequest(dbsession=dbsession)
class BaseTest(unittest.TestCase):
"""Base Test."""
def setUp(self):
"""Test setup."""
self.config ... | mit | Python |
124dc1fb5f60cfb0d82387f66671de39b896407e | add actor_yield functionality | dramatis/dramatis,dramatis/dramatis | lib/dramatis/actor/interface.py | lib/dramatis/actor/interface.py | class Interface(object):
"""provides actors with control over their runtime dynamics
A dramatis.Actor.Interface object provides actors that have mixed
in dramatis.Actor access to their actor name and other actor
operations. An instance of dramatis.Actor.Interface is typically
accessed through via s... | class Interface(object):
def __init__(self,actor):
self._actor = actor
def refuse( self, *args ):
self._actor._gate.refuse( "object", *args )
def accept( self, *args ):
self._actor._gate.accept( "object", *args )
def default( self, *args ):
self._actor._gate.default( ... | mit | Python |
ef883cd173fafac7ca5f28cc7e40a7c0f802645c | Add shadow type to CSV. | Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite | tools/sweep_to_csv.py | tools/sweep_to_csv.py | #!/usr/bin/env python3
import sys
import os
import argparse
import json
def read_stat_file(path):
with open(path, 'r') as f:
json_data = f.read()
parsed = json.loads(json_data)
return parsed
def shadow_type_to_str(cfg):
if cfg['vsm']:
return 'VSM'
else:
return 'PCF... | #!/usr/bin/env python3
import sys
import os
import argparse
import json
def read_stat_file(path):
with open(path, 'r') as f:
json_data = f.read()
parsed = json.loads(json_data)
return parsed
def main():
parser = argparse.ArgumentParser(description = 'Converts a sweep file to CSV.')
... | mit | Python |
8910a61025062a40a3129f7a4330964b20337ec2 | Add first code for NeuralNetwork class. | cn04/insanity | insanity/core.py | insanity/core.py | import numpy as np
import theano
import theano.tensor as T
class NeuralNetwork(object):
def __init__(self, layers, miniBatchSize):
self.miniBatchSize = miniBatchSize
#Initialize layers.
self.layers = layers
self.numLayers = len(self.layers)
self.firstLayer = self.layers[0]
self.lastLayer = self.layer... | import numpy as np
import theano
import theano.tensor as T | cc0-1.0 | Python |
cdaeb29474df423e66cbc79fffa74d937fe2193c | Add logging for api calls. | mgax/czl-scrape,margelatu/czl-scrape,costibleotu/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,lbogdan/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,margelatu/czl-scrape,margelatu/czl-scrap... | justitie/just/pipelines.py | justitie/just/pipelines.py | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import json
import logging
from just.items import JustPublication
import logging
API_KEY = 'justitie-very-sec... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import json
from just.items import JustPublication
import logging
API_KEY = 'justitie-very-secret-key'
API_PU... | mpl-2.0 | Python |
5d653919bc81543e2534bdaed751aa3e1ae1e14d | Add bfs test for directed graph in reverse direction | dhimmel/networkx,chrisnatali/networkx,goulu/networkx,ltiao/networkx,jcurbelo/networkx,yashu-seth/networkx,nathania/networkx,blublud/networkx,harlowja/networkx,debsankha/networkx,ghdk/networkx,aureooms/networkx,sharifulgeo/networkx,jakevdp/networkx,JamesClough/networkx,kernc/networkx,chrisnatali/networkx,dhimmel/network... | networkx/algorithms/traversal/tests/test_bfs.py | networkx/algorithms/traversal/tests/test_bfs.py | #!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestBFS:
def setUp(self):
# simple graph
G=nx.Graph()
G.add_edges_from([(0,1),(1,2),(1,3),(2,4),(3,4)])
self.G=G
def test_successor(self):
assert_equal(nx.bfs_successors(self.G,source=0),
... | #!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestBFS:
def setUp(self):
# simple graph
G=nx.Graph()
G.add_edges_from([(0,1),(1,2),(1,3),(2,4),(3,4)])
self.G=G
def test_successor(self):
assert_equal(nx.bfs_successors(self.G,source=0),
... | bsd-3-clause | Python |
97561670494047c7a6dfa5778572d2362fc435ba | add version 5.4-1 to r-ape (#20804) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/r-ape/package.py | var/spack/repos/builtin/packages/r-ape/package.py | # Copyright 2013-2021 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 RApe(RPackage):
"""Analyses of Phylogenetics and Evolution
Functions for reading, wri... | # Copyright 2013-2021 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 RApe(RPackage):
"""Functions for reading, writing, plotting, and manipulating phylogenetic... | lgpl-2.1 | Python |
4f79a83dd107b059a4ac6e19caf77187d7a461bb | Fix R version (#26047) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/r-ecp/package.py | var/spack/repos/builtin/packages/r-ecp/package.py | # Copyright 2013-2021 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 REcp(RPackage):
"""Non-Parametric Multiple Change-Point Analysis of MultivariateData
... | # Copyright 2013-2021 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 REcp(RPackage):
"""Non-Parametric Multiple Change-Point Analysis of MultivariateData
... | lgpl-2.1 | Python |
0f5f49f7518a463d65d7105156789aa96ce87d2e | set JAVA_HOME for hadoop CLASSPATH fetching (#9439) | iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack,iulian787/spack,iulian787/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/spark/package.py | var/spack/repos/builtin/packages/spark/package.py | # Copyright 2013-2018 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)
import re
from spack import *
class Spark(Package):
"""Apache Spark is a fast and general engine
for large-scal... | # Copyright 2013-2018 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)
import re
from spack import *
class Spark(Package):
"""Apache Spark is a fast and general engine
for large-scal... | lgpl-2.1 | Python |
b18479a2bd3156adeab3bcd641c58a589e5cf976 | add v3.0.0 (#21389) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/swarm/package.py | var/spack/repos/builtin/packages/swarm/package.py | # Copyright 2013-2021 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 Swarm(MakefilePackage):
"""A robust and fast clustering method for amplicon-based studies.... | # Copyright 2013-2021 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 Swarm(MakefilePackage):
"""A robust and fast clustering method for amplicon-based studies.... | lgpl-2.1 | Python |
83a4cb51ce6803782ccc9c6ecd86b63971b5c00b | Add a display function for lit.Test.TestResult. | llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers... | utils/lit/lit/Test.py | utils/lit/lit/Test.py | import os
# Test results.
class TestResult:
def __init__(self, name, isFailure):
self.name = name
self.isFailure = isFailure
def __repr__(self):
return '%s%r' % (self.__class__.__name__,
(self.name, self.isFailure))
PASS = TestResult('PASS', False)
XFA... | import os
# Test results.
class TestResult:
def __init__(self, name, isFailure):
self.name = name
self.isFailure = isFailure
PASS = TestResult('PASS', False)
XFAIL = TestResult('XFAIL', False)
FAIL = TestResult('FAIL', True)
XPASS = TestResult('XPASS', True)
UNRESOLVED ... | apache-2.0 | Python |
7432f4ee70d8a2ef34a485400d1045faab27480f | refactor simulation_exp4p.py | ntucllab/striatum | simulation/simulation_exp4p.py | simulation/simulation_exp4p.py | from striatum.storage import history
from striatum.storage import model
from striatum.bandit import exp4p
import simulation as sm
import numpy as np
def main():
times = 1000
d = 5
actions = [1, 2, 3, 4, 5]
history_context, history_action = sm.data_simulation2(2000, d, actions)
models = sm.expert_t... | from striatum.storage import history
from striatum.storage import model
from striatum.bandit import exp4p
import simulation as sm
import numpy as np
import matplotlib.pyplot as plt
def main():
times = 1000
d = 5
actions = [1, 2, 3, 4, 5]
history_context, history_action = sm.data_simulation2(2000, d, a... | bsd-2-clause | Python |
26a15a97a40336eb1cae59efcbbd37a43983308c | Add registry tests | sncosmo/sncosmo,sncosmo/sncosmo,sncosmo/sncosmo | sncosmo/tests/test_registry.py | sncosmo/tests/test_registry.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test registry functions."""
import numpy as np
import pytest
import sncosmo
def basic_loader(arg, name=None, version=None):
return arg
def basic_loader_no_version(arg, name=None):
return arg
@pytest.fixture
def registry():
# Create a... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test registry functions."""
import numpy as np
import sncosmo
def test_register():
disp = np.array([4000., 4200., 4400., 4600., 4800., 5000.])
trans = np.array([0., 1., 1., 1., 1., 0.])
# create a band, register it, make sure we can get... | bsd-3-clause | Python |
837efcddd6c111dabf14a6017d0ae2f6aacbddac | Add detection of wrong meta data | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur | konstrukteur/HtmlParser.py | konstrukteur/HtmlParser.py | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filenam... | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filenam... | mit | Python |
cdb712f26f0f7eadc90ea22f53dcd9b786937f11 | Bump version | fortyninemaps/picogeojson | picogeojson/__init__.py | picogeojson/__init__.py | __version__ = "0.8.0"
from .types import (Point, LineString, Polygon,
MultiPoint, MultiLineString, MultiPolygon,
GeometryCollection, Feature, FeatureCollection)
from .map import Map
from .deserializer import Deserializer, fromfile, fromstring, fromdict
from .serializer import... | __version__ = "0.7.0"
from .types import (Point, LineString, Polygon,
MultiPoint, MultiLineString, MultiPolygon,
GeometryCollection, Feature, FeatureCollection)
from .map import Map
from .deserializer import Deserializer, fromfile, fromstring, fromdict
from .serializer import... | mit | Python |
d5a0d675d775290d4ee545822115f4e8d55b2da8 | modify mistake | taeguk/github_listener | github_listener/__init__.py | github_listener/__init__.py | from __future__ import absolute_import
from .parser.github import GithubAccount
from .notification import NotificationChange
from .github_listener import GithubListener
__all__ = ['github_listener', 'notification']
| from __future__ import absolute_import
from .parser.common import GithubAccount
from .notification import NotificationChange
from .github_listener import GithubListener
__all__ = ['github_listener', 'notification']
| mit | Python |
26ffa5d9c8d00fd0d077847ad56f165d9095947a | Update JS CDN to cdn.jsdelivr.net | tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi | fastapi/openapi/docs.py | fastapi/openapi/docs.py | from starlette.responses import HTMLResponse
def get_swagger_ui_html(*, openapi_url: str, title: str) -> HTMLResponse:
return HTMLResponse(
"""
<! doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css">
<t... | from starlette.responses import HTMLResponse
def get_swagger_ui_html(*, openapi_url: str, title: str) -> HTMLResponse:
return HTMLResponse(
"""
<! doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css">
<title>
"""
... | mit | Python |
2051867f8ce8a478f89fae49f493fd8dd79da6e0 | Fix headers and errors | ben-cunningham/pybot,ben-cunningham/python-messenger-bot | fbmsgbot/http_client.py | fbmsgbot/http_client.py | import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def __init__(self, api_token):
self.api_token = api_token
def submit_request(self, path, method, payload):
asser... | import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def __init__(self, api_token):
self.api_token = api_token
def submit_request(self, path, method, payload):
asser... | mit | Python |
b0591aa41b67dee47d3af4a7d40a35d93ae0c906 | Move log message to __main__.py, added timestamp | adamgot/python-plexlibrary | plexlibrary/__main__.py | plexlibrary/__main__.py | # -*- coding: utf-8 -*-
from plexlibrary import main
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',
level=logging.INFO)
main()
| # -*- coding: utf-8 -*-
from plexlibrary import main
main()
| bsd-3-clause | Python |
a0a76dd90a1972cbaaf6ab16f931ab38248da96a | Remove store=True and api.depends | SerpentCS/purchase-workflow,SerpentCS/purchase-workflow,SerpentCS/purchase-workflow | purchase_picking_state/purchase.py | purchase_picking_state/purchase.py | # -*- coding: utf-8 -*-
# © 2016 Chafique DELLI @ Akretion
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
@api.model
def get_picking_state(self):
return [
('dr... | # -*- coding: utf-8 -*-
# © 2016 Chafique DELLI @ Akretion
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
@api.model
def get_picking_state(self):
return [
('dr... | agpl-3.0 | Python |
565b7d67ef5ccec6d26cfb73c6221e8c3ca24e8b | Fix cover retrieval | magne4000/festival,magne4000/festival,magne4000/festival | festivallib/coverurl.py | festivallib/coverurl.py | #!/usr/bin/env python3
import urllib.parse
import urllib3
import json
import logging
from app import app
logger = logging.getLogger('coverurl')
class CoverURL:
SEARCH_URL = "https://ws.audioscrobbler.com/2.0/?"
def __init__(self, api_key):
self.params = {
'format': 'json',
'... | #!/usr/bin/env python3
import urllib.parse
import urllib3
import json
import logging
from app import app
logger = logging.getLogger('coverurl')
class CoverURL:
SEARCH_URL = "https://ws.audioscrobbler.com/2.0/?"
def __init__(self, api_key):
self.params = {
'format': 'json',
'... | mit | Python |
a31db91800630520c5b516493bddef76ba8b7edd | Delete useless header transform in extract_params. | auerj/flask-oauthlib,auerj/flask-oauthlib,kevin1024/flask-oauthlib,stianpr/flask-oauthlib,CoreyHyllested/flask-oauthlib,lepture/flask-oauthlib,Ryan-K/flask-oauthlib,tonyseek/flask-oauthlib,RealGeeks/flask-oauthlib,adambard/flask-oauthlib,huxuan/flask-oauthlib,PyBossa/flask-oauthlib,Fleurer/flask-oauthlib,CoreyHyllested... | flask_oauthlib/utils.py | flask_oauthlib/utils.py | # coding: utf-8
import logging
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
log = logging.getLogger('flask_oauthlib')
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.head... | # coding: utf-8
import logging
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
log = logging.getLogger('flask_oauthlib')
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.head... | bsd-3-clause | Python |
ed46725b1e820d4800f1ea5ee1baab5c8af6844f | fix argument parsing | spaceone/tehbot,tehron/tehbot | plugins/wtf/__init__.py | plugins/wtf/__init__.py | import plugins
import urllib2
import urllib
import lxml.html
import shlex
import json
parser = plugins.ThrowingArgumentParser(
prog="wtf",
description="Looks up definitions in Urban Dictionary")
parser.add_argument("search_term", nargs="+")
parser.add_argument("-n", "--nr", type=int, help="request definition n... | import plugins
import urllib2
import urllib
import lxml.html
import shlex
import json
parser = plugins.ThrowingArgumentParser(
prog="wtf",
description="Looks up definitions in Urban Dictionary")
parser.add_argument("search_term", nargs="+")
parser.add_argument("-n", "--nr", help="request definition number NR")... | mit | Python |
a91a04af6b95fa600a0b3ce74b5fffc07ecf590e | Set polymorphic.__version__ from setuptools metadata | skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,chrisglass/django_polymorphic,chrisglass/django_polymorphic | polymorphic/__init__.py | polymorphic/__init__.py | # -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
Copyright:
This code and affiliated files are (C) by Bert Constantin and individual contributors.
Please see LICENSE and AUTHORS for more information.
"""
import pkg_resources
__version__ = pkg_resources.require("django-polymorphic")[0].... | # -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
Copyright:
This code and affiliated files are (C) by Bert Constantin and individual contributors.
Please see LICENSE and AUTHORS for more information.
"""
# See PEP 440 (https://www.python.org/dev/peps/pep-0440/)
__version__ = "1.3"
| bsd-3-clause | Python |
751691015e1770cbd8e7be4f58cac2c460c85a2c | Support DBusProperty flag in generate-manager-file | freedesktop-unofficial-mirror/telepathy__telepathy-python,max-posedon/telepathy-python,detrout/telepathy-python,max-posedon/telepathy-python,detrout/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,PabloCastellano/telepathy-python,epage/telepathy-python,epage/telepathy-python,PabloCastellano/t... | examples/generate-manager-file.py | examples/generate-manager-file.py | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \
CONN_MGR_PARAM_FLAG_REGISTER, \
CONN_MGR_PARAM_FLAG_HAS_DEFAULT, \
... | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \
CONN_MGR_PARAM_FLAG_REGISTER, \
CONN_MGR_PARAM_FLAG_HAS_DEFAULT
if len(sys.argv) >= 2:
ma... | lgpl-2.1 | Python |
fa0c803427751bd3e676c365de525ac9b9024bb8 | Add processing for K8S_HOST_NETWORK to check_zombie_mons script | osixia/ceph-docker,ceph/ceph-docker,JrCs/ceph-docker,JrCs/ceph-docker,mkkie/ceph-docker,rootfs/ceph-docker,mkkie/ceph-docker,cdxvirt/ceph-docker,AcalephStorage/ceph-docker,osixia/ceph-docker,cdxvirt/ceph-docker,JrCs/ceph-docker,ceph/ceph-docker,AcalephStorage/ceph-docker,rootfs/ceph-docker,AcalephStorage/ceph-docker,os... | ceph-releases/kraken/ubuntu/16.04/daemon/check_zombie_mons.py | ceph-releases/kraken/ubuntu/16.04/daemon/check_zombie_mons.py | #!/usr/bin/python2
import re
import os
import subprocess
import json
MON_REGEX = r"^\d: ([0-9\.]*):\d+/\d* mon.([^ ]*)$"
# kubctl_command = 'kubectl get pods --namespace=${CLUSTER} -l daemon=mon -o template --template="{ {{range .items}} \\"{{.metadata.name}}\\": \\"{{.status.podIP}}\\" , {{end}} }"'
if int(os.geten... | #!/usr/bin/python
import re
import subprocess
import json
MON_REGEX = r"^\d: ([0-9\.]*):\d+/\d* mon.([^ ]*)$"
# kubctl_command = 'kubectl get pods --namespace=${CLUSTER} -l daemon=mon -o template --template="{ {{range .items}} \\"{{.metadata.name}}\\": \\"{{.status.podIP}}\\" , {{end}} }"'
kubectl_command = 'kubect... | apache-2.0 | Python |
232032c817d744f164ad640d5c28250ce6b3721f | use the method instead of accessing the field directly. | vnc-biz/openerp-server,MarkusTeufelberger/openobject-server,MarkusTeufelberger/openobject-server,gisce/openobject-server,splbio/openobject-server,splbio/openobject-server,gisce/openobject-server,splbio/openobject-server,vnc-biz/openerp-server,ovnicraft/openerp-server,MarkusTeufelberger/openobject-server,ovnicraft/opene... | openerp/addons/base/ir/osv_memory_autovacuum.py | openerp/addons/base/ir/osv_memory_autovacuum.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | agpl-3.0 | Python |
f53005e96742c26d30bac2cf0b6c898a63cede00 | Update urls.py | DalenWBrauner/FloridaDataOverlay | Starting_Over/Florida_Data_Overlay/Overlay/urls.py | Starting_Over/Florida_Data_Overlay/Overlay/urls.py | from django.conf.urls import url
from Overlay import views
urlpatterns = [
url(r'^$',
views.main,
name='main'),
url(r'^custom/$',
views.custom,
name='custom'),
url(r'^custom/(?P<cnty>[^0-9]+)/$',
views.year,
name='years'),
url(r'^custom/(?P<cnt... | from django.conf.urls import url
from Overlay import views
urlpatterns = [
url(r'^$',
views.basic,
name='basic'),
url(r'^(?P<cnty>[^0-9]+)/$',
views.year,
name='years'),
url(r'^(?P<cnty>[^0-9]+)/(?P<yr>[0-9]{4})/$',
views.att,
name='attribute'),
... | mit | Python |
0f98d04120aac908c22d5361b52419df10300f97 | Update map_resampling_and_superpixels.py | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | examples/map/map_resampling_and_superpixels.py | examples/map/map_resampling_and_superpixels.py | # -*- coding: utf-8 -*-
"""
===============
Resampling Maps
===============
How to resample a map using the resample method, which implements interpolation, or
using superpixels, which combines pixels.
"""
import matplotlib.pyplot as plt
import astropy.units as u
import sunpy.map
import sunpy.data.sample
##########... | # -*- coding: utf-8 -*-
"""
=========================================
Map Resampling and Superpixels
=========================================
In this example you will see how to resample a map using the resample method
(which implements interpolation) and superpixels.
"""
############################################... | bsd-2-clause | Python |
cfcd0519601d990ca0d45c381c5e837d50d1330e | Fix for bug when removing stale answers | eldarion/formly,eldarion/formly | formly/views/results.py | formly/views/results.py | import json
from urllib import unquote
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_or_404
from django.views.generic import DetailView
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.contrib.auth.mixins impor... | import json
from urllib import unquote
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_or_404
from django.views.generic import DetailView
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.contrib.auth.mixins impor... | bsd-3-clause | Python |
017dee71c297032b2b3a9681d60035a0f1b6fc30 | use subprocess to call odk jar file in refresh_odk.py | unicef/rhizome,unicef/polio,SeedScientific/polio,unicef/rhizome,unicef/rhizome,unicef/rhizome,SeedScientific/polio,unicef/polio,SeedScientific/polio,SeedScientific/polio,unicef/polio,SeedScientific/polio,unicef/polio | source_data/ODK/refresh_odk.py | source_data/ODK/refresh_odk.py | #!/bin/python
import sys
import urllib2
import subprocess
def main():
try:
sys.path.append("/Users/johndingee_seed/Desktop/")
import odk_settings as odk_settings
except ImportError:
sys.path.append("/home/ubuntu/ODK/")
import odk_settings
REGION_FORM="VCM_Sett_Coordinates... | #!/bin/python
import sys
import urllib2
def main():
try:
sys.path.append("/Users/johndingee_seed/Desktop/")
import odk_settings as odk_settings
except ImportError:
sys.path.append("/home/ubuntu/ODK/")
import odk_settings
REGION_FORM="VCM_Sett_Coordinates_1.2"
# UUID=$... | agpl-3.0 | Python |
b15d0c211b8e2432cd40acd729519b15773df101 | Clean up copypasta fail | SteveViss/readthedocs.org,istresearch/readthedocs.org,clarkperkins/readthedocs.org,techtonik/readthedocs.org,SteveViss/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,gjtorikian/readthedocs.org,davidfischer/readthedocs.org,gjtorikian/readthedocs.org,stevepiercy/readthedocs.org,SteveViss/readthedocs.or... | readthedocs/restapi/serializers.py | readthedocs/restapi/serializers.py | from rest_framework import serializers
from readthedocs.builds.models import Build, BuildCommandResult, Version
from readthedocs.projects.models import Project, Domain
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'name... | from rest_framework import serializers
from readthedocs.builds.models import Build, BuildCommandResult, Version
from readthedocs.projects.models import Project, Domain
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'name... | mit | Python |
6577c4a89c505aa481edf7380de0b58d4bb81c13 | Set debug to false | ajoyoommen/weblog,ajoyoommen/weblog | django_site/settings.py | django_site/settings.py | """
Django settings for django_site project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... | """
Django settings for django_site project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... | mit | Python |
8cb680c7fbadfe6cfc245fe1eb1261a00c5ffd6d | Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None. | recklessromeo/django-money,rescale/django-money,iXioN/django-money,AlexRiina/django-money,tsouvarev/django-money,iXioN/django-money,tsouvarev/django-money,recklessromeo/django-money | djmoney/forms/fields.py | djmoney/forms/fields.py | from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_wi... | from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_wi... | bsd-3-clause | Python |
c2fd1e92f207ea53392db8bb05859bf4f9187586 | Improve output of ft_check_reqs. | duointeractive/django-fabtastic | fabtastic/management/commands/ft_check_reqs.py | fabtastic/management/commands/ft_check_reqs.py | from django.core.management.base import BaseCommand
from fabric.api import *
import fabfile
from fabtastic.util.req_syncer import compare_reqs_to_env
class Command(BaseCommand):
help = "Compares your current virtualenv to requirements.txt."
def handle(self, *args, **options):
missing_pkgs, wrong_versi... | from django.core.management.base import BaseCommand
from fabric.api import *
import fabfile
from fabtastic.util.req_syncer import compare_reqs_to_env
class Command(BaseCommand):
help = "Compares your current virtualenv to requirements.txt."
def handle(self, *args, **options):
missing_pkgs, wrong_versi... | bsd-3-clause | Python |
327d185ab725214e481d1d7f5a2e1280888c8fdc | remove debugging output | onelab-eu/sfa,onelab-eu/sfa,onelab-eu/sfa,yippeecw/sfa,yippeecw/sfa,yippeecw/sfa | geni/methods/resolve.py | geni/methods/resolve.py | from geni.util.faults import *
from geni.util.excep import *
from geni.util.method import Method
from geni.util.parameter import Parameter, Mixed
from geni.util.auth import Auth
from geni.util.record import GeniRecord
from geni.util.debug import log
class resolve(Method):
"""
Resolve a record.
@param cred... | from geni.util.faults import *
from geni.util.excep import *
from geni.util.method import Method
from geni.util.parameter import Parameter, Mixed
from geni.util.auth import Auth
from geni.util.record import GeniRecord
from geni.util.debug import log
class resolve(Method):
"""
Resolve a record.
@param cred... | mit | Python |
1ffdfffba5a9eccbe318d0c628a10e4f7227bab9 | Update version to v3.4.0 | MatrixCrawler/ansible-lint,willthames/ansible-lint,dataxu/ansible-lint | lib/ansiblelint/version.py | lib/ansiblelint/version.py | __version__ = '3.4.0'
| __version__ = '3.4.0rc4'
| mit | Python |
faff4419422b922a0d6aa6d6ddc600eb36fe08cd | set celery always eager false | justinwp/croplands,justinwp/croplands | gfsad/config/testing.py | gfsad/config/testing.py | # from default import *
import os
from datetime import timedelta
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite://"
CELERY_DEFAULT_QUEUE = 'gfsad-testing'
POSTMARK_API_KEY = 'POSTMARK_API_TEST'
REDISCLOUD_URL = 'redis://127.0.0.1:6379'
RATELIMIT_STORAGE_URL = 'redis://127.0.0.1:6379'
# SQLALCHEMY_ECHO ... | # from default import *
import os
from datetime import timedelta
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite://"
CELERY_DEFAULT_QUEUE = 'gfsad-testing'
POSTMARK_API_KEY = 'POSTMARK_API_TEST'
REDISCLOUD_URL = 'redis://127.0.0.1:6379'
RATELIMIT_STORAGE_URL = 'redis://127.0.0.1:6379'
# SQLALCHEMY_ECHO ... | mit | Python |
2abcbaffb4e8624fb7bfc4712847fa234e53ce02 | Use StringIO on Python 3 in capture_stdio. Fixes failing tests reported in #14. Fixes #14. | jaraco/hgtools | hgtools/managers/reentry.py | hgtools/managers/reentry.py | from __future__ import absolute_import
import sys
import io
import collections
import contextlib
SavedIO = collections.namedtuple('SavedIO', 'stdout stderr')
@contextlib.contextmanager
def capture_stdio():
io_class = io.StringIO if sys.version_info > (3,) else io.BytesIO
sys_stdout, sys.stdout = sys.stdout, io_cla... | from __future__ import absolute_import
import sys
import io
import collections
import contextlib
SavedIO = collections.namedtuple('SavedIO', 'stdout stderr')
@contextlib.contextmanager
def capture_stdio():
sys_stdout, sys.stdout = sys.stdout, io.BytesIO()
sys_stderr, sys.stderr = sys.stderr, io.BytesIO()
try:
y... | mit | Python |
3e8ca6b6b5aeb41b87803077256da241ef0ec484 | Support for ElasticSearch queries returning large result set | uhjish/link,dhrod5/link | link/wrappers/elasticsearchwrappers.py | link/wrappers/elasticsearchwrappers.py | from link import Wrapper
from link.utils import list_to_dataframe
class ElasticSearch(Wrapper):
"""
wraps an ElasticSearch connection and extends the functionality
to do tasks like put queries into dataframes
"""
def __init__(self, wrap_name = None, **kwargs):
self.options = {}
if k... | from link import Wrapper
from link.utils import list_to_dataframe
class ElasticSearch(Wrapper):
"""
wraps an ElasticSearch connection and extends the functionality
to do tasks like put queries into dataframes
"""
def __init__(self, wrap_name = None, **kwargs):
self.options = {}
if k... | apache-2.0 | Python |
40cf469fa1e5d585c3867d8823a5f55a2fa8826c | fix error message | ergo/ziggurat_foundations,ergo/ziggurat_foundations | ziggurat_foundations/ext/pyramid/get_user.py | ziggurat_foundations/ext/pyramid/get_user.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import importlib
import logging
from ziggurat_foundations.exc import ZigguratException
from ziggurat_foundations.models.base import get_db_session
CONFIG_KEY = 'ziggurat_foundations'
log = logging.getLogger(__name__)
def includeme(config):
setting... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import importlib
import logging
from ziggurat_foundations.exc import ZigguratException
from ziggurat_foundations.models.base import get_db_session
CONFIG_KEY = 'ziggurat_foundations'
log = logging.getLogger(__name__)
def includeme(config):
setting... | bsd-3-clause | Python |
e93d3fcaa57db179b85f2ba36e32b3ce0de57e0c | use full path to find cr_limits | rpavlik/chromium,rpavlik/chromium,rpavlik/chromium,rpavlik/chromium,rpavlik/chromium | packer/pack_currentheader.py | packer/pack_currentheader.py | # Copyright (c) 2001, Stanford University
# All rights reserved.
#
# See the file LICENSE.txt for information on redistributing this software.
# This script generates the include/state/cr_currentpointers.h file.
import sys
sys.path.append( "../glapi_parser" )
import apiutil
from pack_currenttypes import *
apiutil.C... | # Copyright (c) 2001, Stanford University
# All rights reserved.
#
# See the file LICENSE.txt for information on redistributing this software.
# This script generates the include/state/cr_currentpointers.h file.
import sys
sys.path.append( "../glapi_parser" )
import apiutil
from pack_currenttypes import *
apiutil.C... | bsd-3-clause | Python |
545483f2327609b2c6e08608f862ddd29fd6bc1e | Fix testinfra deprecation errors | nephelaiio/ansible-role-i3,nephelaiio/ansible-role-i3 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_command(host):
assert host.command('i3 --version').rc == 0
assert host.command('pactl --version').rc == 0
assert host.comma... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_command(Command):
assert Command('i3 --version').rc == 0
assert Command('pactl --version').rc == 0
assert Command('Xorg -ve... | mit | Python |
4b12d272a226287e1a14d663e4d3514af90d82c3 | Update combinations.py | tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015 | Python/combinations.py | Python/combinations.py | # Time: O(k * C(n, k))
# Space: O(k)
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
#
# For example,
# If n = 4 and k = 2, a solution is:
#
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
class Solution(object):
def combine(self, n, k):
... | # Time: O(n!)
# Space: O(n)
#
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
#
# For example,
# If n = 4 and k = 2, a solution is:
#
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
#
class Solution:
# @return a list of lists of integers
... | mit | Python |
98ca37ed174e281542df2f1026a298387845b524 | Cut down on the loading of families in the normal GenerateReactionsTest | nickvandewiele/RMG-Py,nyee/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py | rmgpy/tools/data/generate/input.py | rmgpy/tools/data/generate/input.py | # Data sources for kinetics
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = 'default',
#this section lists possible reaction families to find reactioons with
kineticsFamilies = ['R_Recombination'],
kineticsEstimator... | # Data sources for kinetics
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = 'default',
#this section lists possible reaction families to find reactioons with
kineticsFamilies = ['!Intra_Disproportionation','!Substitutio... | mit | Python |
cfa3c44a3fd4eef817d576e824cb6994ad767118 | switch debug voice settings to true | exshin/verify-lnkdn,exshin/verify-lnkdn,exshin/verify-lnkdn | googlevoice/settings.py | googlevoice/settings.py | DEFAULT_CONFIG = """
[auth]
# Google Account email address (one associated w/ your Voice account)
email=
# Raw password used or login
password=
[gvoice]
# Number to place calls from (eg, your google voice number)
forwardingNumber=
# Default phoneType for your forwardingNumber as defined below
# 1 - Home
# 2 - Mobi... | DEFAULT_CONFIG = """
[auth]
# Google Account email address (one associated w/ your Voice account)
email=
# Raw password used or login
password=
[gvoice]
# Number to place calls from (eg, your google voice number)
forwardingNumber=
# Default phoneType for your forwardingNumber as defined below
# 1 - Home
# 2 - Mobi... | bsd-3-clause | Python |
25695e927fbbf46df385b4c68fa4d80b81283ace | Add lastmod to existing profile picture metadata | pferreir/indico,indico/indico,pferreir/indico,indico/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,ThiefMaster/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,DirkHoffmann/indico,DirkHoffmann/indico | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_source_column.py | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_source_column.py | """Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from werkzeug.http import http_date
from indico.core.db.sqlalchemy import PyIntEnum
from indico.util.date_ti... | """Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d5... | mit | Python |
2681e88b2bec654010e51e937c943271a6eb8fb6 | Add docstrings to LinearKernel | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch | gpytorch/kernels/linear_kernel.py | gpytorch/kernels/linear_kernel.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
from gpytorch.kernels import Kernel
from gpytorch.lazy import MatmulLazyVariable, RootLazyVariable
from gpytorch.priors._compatibility import _bounds_to_prio... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
from gpytorch.kernels import Kernel
from gpytorch.lazy import MatmulLazyVariable, RootLazyVariable
from gpytorch.priors._compatibility import _bounds_to_prio... | mit | Python |
b31943769837ffb0a25dc35b2b93eff6f71753f2 | Return free'd request | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | groundstation/request_registry.py | groundstation/request_registry.py | import logger
log = logger.getLogger(__name__)
class RequestRegistry(object):
def __init__(self):
self._reg = {}
@property
def contents(self):
return self._reg
def __contains__(self, other):
return str(other) in self._reg
def register(self, req):
if req.id in self... | import logger
log = logger.getLogger(__name__)
class RequestRegistry(object):
def __init__(self):
self._reg = {}
@property
def contents(self):
return self._reg
def __contains__(self, other):
return str(other) in self._reg
def register(self, req):
if req.id in self... | mit | Python |
7badd9119d868b9589ff375a698c95798dc8de0b | Fix dataIO | kallerdaller/Cogs-Yorkfield | russianroulette/russianroulette.py | russianroulette/russianroulette.py | import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
class Mycog:
"""Russian Roulette"""
def __init__(self, bot):
self.bot = bot
self.file_path = data/russianroulette/russianroulette.json"
self.json_data = dataIO.load_json(self.file_path)
... | import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
class Mycog:
"""Russian Roulette"""
def __init__(self, bot):
self.bot = bot
self.file_path = data/russianroulette/russianroulette.json"
self.json_data = dataIO.load_json(self.file_path)
... | mit | Python |
e2ba4deb350a95c73edd623dfe828e9d317c8bb8 | change video thumbnail provider display name | rmrector/script.artwork.beef | lib/providers/videofile.py | lib/providers/videofile.py | import re
import urllib
from abc import ABCMeta
from lib.libs import mediatypes
from lib.libs.addonsettings import settings
from lib.libs.utils import SortedDisplay, get_movie_path_list
class VideoFileAbstractProvider(object):
__metaclass__ = ABCMeta
name = SortedDisplay('video:thumb', 'video file')
def ... | import re
import urllib
from abc import ABCMeta
from lib.libs import mediatypes
from lib.libs.addonsettings import settings
from lib.libs.utils import SortedDisplay, get_movie_path_list
class VideoFileAbstractProvider(object):
__metaclass__ = ABCMeta
# 21371 = Thumbnail
name = SortedDisplay('video:thumb',... | mit | Python |
c5018280db0c01f3656f69fa6e791386c03eda47 | Add missing attributes to Network model | lxc/pylxd,lxc/pylxd | pylxd/models/network.py | pylxd/models/network.py | # Copyright (c) 2016 Canonical Ltd
#
# 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 ... | # Copyright (c) 2016 Canonical Ltd
#
# 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 ... | apache-2.0 | Python |
9e45880dd4b4015f2f425736cc80b5e586923423 | Update the mul XLMR model to properly tokenize apostrophe | hankcs/HanLP,hankcs/HanLP | hanlp/pretrained/mtl.py | hanlp/pretrained/mtl.py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-22 13:16
from hanlp_common.constant import HANLP_URL
OPEN_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH = HANLP_URL + 'mtl/open_tok_pos_ner_srl_dep_sdp_con_electra_small_20201223_035557.zip'
"Electra small version of joint tok, pos, ner, srl, dep, sdp and con mode... | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-22 13:16
from hanlp_common.constant import HANLP_URL
OPEN_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH = HANLP_URL + 'mtl/open_tok_pos_ner_srl_dep_sdp_con_electra_small_20201223_035557.zip'
"Electra small version of joint tok, pos, ner, srl, dep, sdp and con mode... | apache-2.0 | Python |
6384fd52a4d271f0f3403ae613dd66cbeb217ddf | Update test to use new API | johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy | indra/tests/test_biogrid.py | indra/tests/test_biogrid.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
from nose.plugins.attrib import attr
from indra.statements import Complex
from indra.databases import biogrid_client
from indra.util import unicode_strs
from indra.sources.biogrid import BiogridProcessor
t... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import biogrid_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
from indra.sources.biogrid import process_file
from indra.statements import Complex
import os
this_... | bsd-2-clause | Python |
b121003f16914feb59b0a065d8317e50d687a92d | add demodulation function | Vskilet/UMTS-Multiplexing,Vskilet/UMTS-Multiplexing | initializeCommunications.py | initializeCommunications.py | from ovsfGenerator import ovsfGenerator
from Mobile import Mobile
def bitToString(a):
return (bin(a)[2:])
def demodulateSignal(sig, cellPhone):
k=0
multipliedSignal=[]
for i in sig :
if(bitToString(cellPhone.ovsfCode)[sig.index(i)]=='1'):
multipliedSignal.append(i)
else:
... | from ovsfGenerator import ovsfGenerator
from Mobile import Mobile
listCodes = ovsfGenerator(4)
listMobile = [Mobile("A",listCodes[0]),Mobile("B",listCodes[1]),Mobile("C",listCodes[2]),Mobile("D",listCodes[3])]
for mobile in listMobile :
print(mobile)
signal = [0,0,0,0]
for i in range(0,4):
for mobile in list... | mit | Python |
f1d64edd072bb292b58deefb535542f4ddc640d8 | Fix lint. | tonybaloney/st2,lakshmi-kannan/st2,nzlosh/st2,Plexxi/st2,emedvedev/st2,pixelrebel/st2,Plexxi/st2,emedvedev/st2,StackStorm/st2,dennybaa/st2,peak6/st2,punalpatel/st2,punalpatel/st2,punalpatel/st2,StackStorm/st2,emedvedev/st2,dennybaa/st2,peak6/st2,Plexxi/st2,tonybaloney/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,lakshmi-kannan... | contrib/linux/actions/wait_for_ssh.py | contrib/linux/actions/wait_for_ssh.py | #!/usr/bin/env python
import time
from oslo_config import cfg
from st2actions.runners.pythonrunner import Action
from st2actions.runners.ssh.paramiko_ssh import ParamikoSSHClient
class BaseAction(Action):
def run(self, hostname, port, username, password=None, keyfile=None, ssh_timeout=5,
sleep_dela... | #!/usr/bin/env python
import time
from oslo_config import cfg
from st2actions.runners.pythonrunner import Action
from st2actions.runners.ssh.paramiko_ssh import ParamikoSSHClient
class BaseAction(Action):
def run(self, hostname, port, username, password=None, keyfile=None, ssh_timeout=5,
sleep_dela... | apache-2.0 | Python |
7828ff098bd88b2884f5ba18c90094b6f3d8f3d8 | Apply Black formatting rules | MinchinWeb/minchin.pelican.jinja_filters | pelican/plugins/jinja_filters/jinja_filters.py | pelican/plugins/jinja_filters/jinja_filters.py | """Various filters for Jinja."""
from titlecase import titlecase as _titlecase
__all__ = ["datetime", "article_date", "breaking_spaces", "titlecase"]
def datetime(value, format_str="%Y/%m/%d %H:%M"):
"""
Convert a datetime to a different format.
The default format looks like --> 2016/11/25 12:34
A... | """Various filters for Jinja."""
from titlecase import titlecase as _titlecase
__all__ = ['datetime',
'article_date',
'breaking_spaces',
'titlecase']
def datetime(value, format_str='%Y/%m/%d %H:%M'):
"""
Convert a datetime to a different format.
The default format looks... | mit | Python |
746763f109fdd3dcc63ec9873b5f0d157dfd16dd | add SplitExportColumn to __init__ | dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | corehq/apps/export/models/__init__.py | corehq/apps/export/models/__init__.py | from .deprecated import QuestionMeta, FormQuestionSchema
from .new import (
ExportItem,
ExportColumn,
RowNumberColumn,
SplitExportColumn,
StockExportColumn,
ExportRow,
ExportInstance,
FormExportInstance,
CaseExportInstance,
ExportDataSchema,
FormExportDataSchema,
CaseExpo... | from .deprecated import QuestionMeta, FormQuestionSchema
from .new import (
ExportItem,
ExportColumn,
RowNumberColumn,
StockExportColumn,
ExportRow,
ExportInstance,
FormExportInstance,
CaseExportInstance,
ExportDataSchema,
FormExportDataSchema,
CaseExportDataSchema,
Expor... | bsd-3-clause | Python |
01c04bad0bb9261c024b4ab3cd78fbb10a56c1fd | add bubble sort | liuyonggg/learning_python,liuyonggg/learning_python,liuyonggg/learning_python,liuyonggg/learning_python | leetcode/sort.py | leetcode/sort.py | import random
import copy
import timeit
class Solution:
def sort(self,nums):
vs = copy.deepcopy(nums)
num = []
for i in xrange(len(vs)):
minf = min(vs)
num.append(minf)
vs.remove(minf)
return num
def bubbleSort(self, nums):
vs = copy... | import random
import copy
import timeit
class Solution:
def sort(self,nums):
num = []
for i in xrange(len(nums)):
minf = min(nums)
num.append(minf)
nums.remove(minf)
return num
def test_1(m, refm):
assert (Solution().sort(m) == refm)
if __name_... | mit | Python |
9a0570d2549bb9b7bffb79a8ddfae159240d7119 | prepare ocr full text | datamade/django-councilmatic,CivicTechTO/django-councilmatic,datamade/django-councilmatic,CivicTechTO/django-councilmatic,datamade/django-councilmatic,CivicTechTO/django-councilmatic,CivicTechTO/django-councilmatic,datamade/django-councilmatic | councilmatic_core/haystack_indexes.py | councilmatic_core/haystack_indexes.py | from councilmatic_core.models import Bill
from haystack import indexes
from councilmatic_core.templatetags.extras import clean_html
class BillIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/councilmatic_core/bill_text.txt")
slug = indexes.Ch... |
from councilmatic_core.models import Bill
from haystack import indexes
from councilmatic_core.templatetags.extras import clean_html
class BillIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/councilmatic_core/bill_text.txt")
slug = indexes.C... | mit | Python |
220e99d307371b7f7ec95016135aedef6a219d36 | Comment out debugging info. | ebegoli/SynthNotes | synthnotes/generators/lengthgenerator.py | synthnotes/generators/lengthgenerator.py | from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename(__name__,
'resources/note_lengths.csv')):
# print(length_file)
df = pd... | from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename(__name__,
'resources/note_lengths.csv')):
print(length_file)
df = pd.r... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.