commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
dc57d4b95e39f756858dc1d73c8f221f0bb1956c
add stubs
tests/commands/test__vi_cc.py
tests/commands/test__vi_cc.py
import unittest from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL from Vintageous.vi.constants import MODE_NORMAL from Vintageous.vi.constants import MODE_VISUAL from Vintageous.vi.constants import MODE_VISUAL_LINE from Vintageous.tests.commands import set_text from Vintageous.tests.commands import ad...
import unittest from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL from Vintageous.vi.constants import MODE_NORMAL from Vintageous.vi.constants import MODE_VISUAL from Vintageous.vi.constants import MODE_VISUAL_LINE from Vintageous.tests.commands import set_text from Vintageous.tests.commands import ad...
Python
0.000001
6755255332039ab3c0ea60346f61420b52e2f474
Fix intermittent failure in l10n language selector test
tests/functional/test_l10n.py
tests/functional/test_l10n.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(b...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(b...
Python
0.000003
da6c8f6daee4baa3798ab2c4b49fbc780e46ee3a
Rename test case for ObjectLoader to match
tests.py
tests.py
#!/usr/bin/env python import sys import os import unittest from straight.plugin import loaders class ModuleLoaderTestCase(unittest.TestCase): def setUp(self): self.loader = loaders.ModuleLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'test-packages', 'more-test-plugins')) ...
#!/usr/bin/env python import sys import os import unittest from straight.plugin import loaders class ModuleLoaderTestCase(unittest.TestCase): def setUp(self): self.loader = loaders.ModuleLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'test-packages', 'more-test-plugins')) ...
Python
0
d8737e4b2a0b41b139edbed6535e834a9aa17699
Remove ShCommandContext
modules/command/cmd_sh.py
modules/command/cmd_sh.py
# -*- coding: utf-8 -*- from models import CommandInfo from cmd import Command, CommandContext, validator, cmd_indicator class ShCommand(Command): """ NAME: sh - execute shell command within application container on remote machine SYNOPSIS: sh [--env|-e <ENV>] <marathin_app_id> <raw bash command> DE...
# -*- coding: utf-8 -*- from models import CommandInfo from cmd import Command, CommandContext, validator, cmd_indicator class ShCommand(Command): """ NAME: sh - execute shell command within application container on remote machine SYNOPSIS: sh [--env|-e <ENV>] <marathin_app_id> <raw bash command> DE...
Python
0.000007
a18e195734983849a90786a4631987466952a232
Set vestion to 0.4.2 in __init__.py
lib/recordclass/__init__.py
lib/recordclass/__init__.py
# The MIT License (MIT) # # Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com> # # 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 witho...
# The MIT License (MIT) # # Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com> # # 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 witho...
Python
0.000106
ba1fa9d47ae725774807a0aa97cdde476e572266
improve readbility and remove unuse function.
timer.py
timer.py
from time import strftime import time import os import datetime from datetime import timedelta import sys def to_hour(sec): return get_time(sec) def get_time(second): sec = timedelta(seconds=second) d = datetime.datetime(1,1,1) + sec return "%dh %dm" % (d.hour, d.minute) class Timer(object): de...
from time import strftime import time import os import datetime import sys def to_min(sec): return int(sec/60) def to_hour(sec): return int(sec/60/60) class Timer(object): def __init__(self): self._key = self._initial() self._target_working_sec = 9 * 60 * 60 # 9 hour def _initial(...
Python
0
d537ea32462c7ef46634d1527702c4c4a6d37e1e
Fix UDF test, take two
tests/query_test/test_udfs.py
tests/query_test/test_udfs.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): ...
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): ...
Python
0.999732
9c0a83da524831cf557e24ad0a61c160c856dec9
move definitions to the bottom again
tools.py
tools.py
# coding: utf-8 from pyquery import PyQuery as q import json from collections import OrderedDict this = None BASE = 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/' def load(filename='resource.json'): schema = json.load(open(filename), object_pairs_hook=OrderedDict) return schema def get_pq...
# coding: utf-8 from pyquery import PyQuery as q import json from collections import OrderedDict this = None BASE = 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/' def load(filename='resource.json'): schema = json.load(open(filename), object_pairs_hook=OrderedDict) return schema def get_pq...
Python
0
586cd6c864fdbdb3ac20aa49bdc6c550fa93aa2f
fix a testdir stragler
tests/test_latex_formatter.py
tests/test_latex_formatter.py
# -*- coding: utf-8 -*- """ Pygments LaTeX formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2006-2007 by Georg Brandl. :license: BSD, see LICENSE for more details. """ import os import unittest import tempfile from pygments.formatters import LatexFormatter from pygments.lexers import Python...
# -*- coding: utf-8 -*- """ Pygments LaTeX formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2006-2007 by Georg Brandl. :license: BSD, see LICENSE for more details. """ import os import unittest import tempfile from pygments.formatters import LatexFormatter from pygments.lexers import Python...
Python
0.99996
592b8a1a97a3c6d4c17eaeb6e748134501240894
Increase the default number of training epoch
train.py
train.py
#!/usr/bin/env python __author__ = 'Tony Beltramelli www.tonybeltramelli.com - 19/08/2016' import os import argparse from modules.Model import * from modules.Batch import * def main(): parser = argparse.ArgumentParser() parser.add_argument('--training_file', type=str, required=True) parser.add_argument('...
#!/usr/bin/env python __author__ = 'Tony Beltramelli www.tonybeltramelli.com - 19/08/2016' import os import argparse from modules.Model import * from modules.Batch import * def main(): parser = argparse.ArgumentParser() parser.add_argument('--training_file', type=str, required=True) parser.add_argument('...
Python
0.000005
07cfc39e50251384ddb647ccc7f73c98ed8cf7b9
Save model with an interval of 1000 steps
train.py
train.py
import tensorflow as tf from model import CycleGAN from reader import Reader from datetime import datetime import os X_TRAIN_FILE = 'data/tfrecords/apple.tfrecords' Y_TRAIN_FILE = 'data/tfrecords/orange.tfrecords' BATCH_SIZE = 1 def train(): current_time = datetime.now().strftime("%Y%m%d-%H%M") checkpoints_dir =...
import tensorflow as tf from model import CycleGAN from reader import Reader from datetime import datetime import os X_TRAIN_FILE = 'data/tfrecords/apple.tfrecords' Y_TRAIN_FILE = 'data/tfrecords/orange.tfrecords' BATCH_SIZE = 1 def train(): current_time = datetime.now().strftime("%Y%m%d-%H%M") checkpoints_dir =...
Python
0
1970bad9d9933432154de2042c4ed74a8696b7f0
fix timeout when no options are specified
teuthology/task/thrashosds.py
teuthology/task/thrashosds.py
import contextlib import logging import ceph_manager from teuthology import misc as teuthology log = logging.getLogger(__name__) @contextlib.contextmanager def task(ctx, config): """ "Thrash" the OSDs by randomly marking them out/down (and then back in) until the task is ended. This loops, and every op_d...
import contextlib import logging import ceph_manager from teuthology import misc as teuthology log = logging.getLogger(__name__) @contextlib.contextmanager def task(ctx, config): """ "Thrash" the OSDs by randomly marking them out/down (and then back in) until the task is ended. This loops, and every op_d...
Python
0.000003
e7b7709784e105114d490eaab655a16e9842a1ed
optimize post processor shouldn't run 'call' with shell and pipe.
thumbnails/post_processors.py
thumbnails/post_processors.py
import imghdr import os from subprocess import call import tempfile import uuid from django.core.files import File def get_or_create_temp_dir(): temp_dir = os.path.join(tempfile.gettempdir(), 'thumbnails') if not os.path.exists(temp_dir): os.mkdir(temp_dir) return temp_dir def process(thumbnail...
import imghdr import os from subprocess import call, PIPE import tempfile import uuid from django.core.files import File def get_or_create_temp_dir(): temp_dir = os.path.join(tempfile.gettempdir(), 'thumbnails') if not os.path.exists(temp_dir): os.mkdir(temp_dir) return temp_dir def process(thu...
Python
0
58b5cd41be50ee72a8cae46504273e0760a5446b
Corrected docker_host docker driver doc
molecule/driver/docker.py
molecule/driver/docker.py
# Copyright (c) 2015-2017 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge...
# Copyright (c) 2015-2017 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge...
Python
0.999971
27e30c4172f2da79168640799188f0394b88c9ec
Fix circular import between querysets.workflow and models.domain
swf/models/domain.py
swf/models/domain.py
# -*- coding: utf-8 -*- from boto.swf.exceptions import SWFResponseError, SWFDomainAlreadyExistsError from swf.constants import REGISTERED from swf.core import ConnectedSWFObject from swf.exceptions import AlreadyExistsError, DoesNotExistError class Domain(ConnectedSWFObject): """Simple Workflow Domain wrapper ...
# -*- coding: utf-8 -*- from boto.swf.exceptions import SWFResponseError, SWFDomainAlreadyExistsError from swf.constants import REGISTERED from swf.core import ConnectedSWFObject from swf.querysets.workflow import WorkflowTypeQuerySet from swf.exceptions import AlreadyExistsError, DoesNotExistError class Domain(Con...
Python
0.000025
6e013f4c5f9f71e3b4386c3b401449922ffdfad8
fix colorization
utils.py
utils.py
import torch import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.initialized = False self.val = None self.avg = None self.sum = None self.count = None def initialize(self, val, weight): ...
import torch import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.initialized = False self.val = None self.avg = None self.sum = None self.count = None def initialize(self, val, weight): ...
Python
0.000004
157a09187bccfbfae9b4698159f3a889cb619dd6
Call resp.json()
utils.py
utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2015–2020 Molly White # # 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...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2015–2020 Molly White # # 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...
Python
0.000001
e2dd97f16f4f8223c25dbaf661863b3e7323a302
add more make errors. i now need to add context lines.
mozharness/base/errors.py
mozharness/base/errors.py
#!/usr/bin/env python """Generic error regexes. We could also create classes that generate these, but with the appropriate level (please don't die on any errors; please die on any warning; etc.) """ # ErrorLists {{{1 """ TODO: more of these. We could have a generic shell command error list (e.g. File not found, perm...
#!/usr/bin/env python """Generic error regexes. We could also create classes that generate these, but with the appropriate level (please don't die on any errors; please die on any warning; etc.) """ # ErrorLists {{{1 """ TODO: more of these. We could have a generic shell command error list (e.g. File not found, perm...
Python
0.000017
c967f59da33dec46ccbe73d7e7878e01715da236
Add docstrings and comments to video module
video.py
video.py
import graphics class VideoController(): """Represents a computer system's video controller.""" def power_on(self): """Powers on this video controller.""" print("VideoController.power_on()") self._create_terminal_window() def _create_terminal_window(self): # Creates t...
import graphics class VideoController(): def power_on(self): print("VideoController.power_on()") self._create_terminal_window() def _create_terminal_window(self): win = graphics.GraphWin("RichEmu86", 890, 408) win.setBackground("black") s = "RichEmu86 " * 8 i ...
Python
0
c705ef83607e09b2ed6e2b8d14aa6a6a7f9f57ea
Update __init__.py
newspaperdemo/__init__.py
newspaperdemo/__init__.py
from flask import Flask, request, render_template, redirect, url_for from newspaper import Article from xml.etree import ElementTree app = Flask(__name__) # Debug logging import logging import sys # Defaults to stdout logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) try: log.info('Loggi...
from flask import Flask, request, render_template, redirect, url_for, json from newspaper import Article from xml.etree import ElementTree app = Flask(__name__) # Debug logging import logging import sys # Defaults to stdout logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) try: log.info(...
Python
0.000072
90c4340dcc578b8ea3532b46058772c4ddda56c0
add missing import
views.py
views.py
# -*- encoding: utf-8 --------------------------------------------------------- from flask import render_template from operator import attrgetter from serve import * from models import * @app.route('/') @app.route('/index.html') def index(): datasets = Dataset.query.all() return render_template('index.html...
# -*- encoding: utf-8 --------------------------------------------------------- from operator import attrgetter from serve import * from models import * @app.route('/') @app.route('/index.html') def index(): datasets = Dataset.query.all() return render_template('index.html', datasets=datasets) @app.route...
Python
0.000042
950436b6c48c279891c762e699f91a08c2101312
Remove stale logging code
nodeconductor/core/log.py
nodeconductor/core/log.py
from nodeconductor.logging.log import EventLogger, event_logger from nodeconductor.core.models import User, SshPublicKey class AuthEventLogger(EventLogger): user = User class Meta: event_types = ('auth_logged_in_with_username', 'auth_logged_in_with_pki', ...
from nodeconductor.logging.log import EventLogger, event_logger from nodeconductor.core.models import User, SshPublicKey class AuthEventLogger(EventLogger): user = User class Meta: event_types = ('auth_logged_in_with_username', 'auth_logged_in_with_pki', ...
Python
0
844270b6eee2eabfaa1b43c73ed8ffcab833586f
Bump to version 0.19.4
tabutils/__init__.py
tabutils/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ tabutils ~~~~~~~~ Provides methods for reading and processing data from tabular formatted files Attributes: CURRENCIES [tuple(unicode)]: Currency symbols to remove from decimal strings. ENCODING (str): Default file encoding....
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ tabutils ~~~~~~~~ Provides methods for reading and processing data from tabular formatted files Attributes: CURRENCIES [tuple(unicode)]: Currency symbols to remove from decimal strings. ENCODING (str): Default file encoding....
Python
0
c7665ba1988215fd27f0eb7f547a34104d8b921f
add MA
nsnqtlib/tkpi/momentum.py
nsnqtlib/tkpi/momentum.py
import numpy as np import pandas as pd #Moving average def MA(data=[], timeperiod=10): ma = [] ma_a = pd.DataFrame(data,columns=['MA']).rolling(window=timeperiod).mean() for i in ma_a['MA']: ma.append(i) return ma #MACD related indicators #Moving average: there will be unstable period i...
import numpy as np #MACD related indicators #Moving average: there will be unstable period in the beginning #input: list of close price def EMA(close=[], timeperiod=10): ema = [] current = close[0] for i in close: current = (current*(timeperiod-1)+ 2*i)/(timeperiod+1) ema.append(current) ...
Python
0.999026
1045f8a2cedf86a401a2868f4092f5d416e8f3e9
Bump to 0.26
octave_kernel/__init__.py
octave_kernel/__init__.py
"""An Octave kernel for Jupyter""" __version__ = '0.26.0'
"""An Octave kernel for Jupyter""" __version__ = '0.25.1'
Python
0.000005
389f892fcd3903b936226a2e464d26a0df359e7b
Determine what wheels should be built, don't attempt to build them if they've been built, don't continue if they fail to build.
wheel.py
wheel.py
#!/usr/bin/env python import os import sys import urllib2 import argparse import subprocess from os.path import abspath, dirname, join, basename, exists import yaml WHEELS_DIST_DIR = abspath(join(dirname(__file__), 'wheels', 'dist')) WHEELS_BUILD_DIR = abspath(join(dirname(__file__), 'wheels', 'build')) WHEELS_YML ...
#!/usr/bin/env python import os import sys import urllib2 import argparse import subprocess from os.path import abspath, dirname, join, basename import yaml WHEELS_DIST_DIR = abspath(join(dirname(__file__), 'wheels', 'dist')) WHEELS_BUILD_DIR = abspath(join(dirname(__file__), 'wheels', 'build')) WHEELS_YML = join(W...
Python
0.001012
7567f63b5bf967a8dc2b370c0deecef41ded3dcd
add LoadBalancer API
Client.py
Client.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # # # Copyright 2012 Netsco Inc. # Copyright 2012 Minsu Kang from urllib import quote_plus as quote from urllib2 import urlopen, HTTPError from base64 import b64encode import hmac import hashlib import json import re UCLOUD_API_KEY = '' UCLOUD_SECRET = '' UCLOUD_API_URLS...
#!/usr/bin/env python # -*- coding:utf-8 -*- # # # Copyright 2012 Netsco Inc. # Copyright 2012 Minsu Kang from urllib import quote_plus as quote from urllib2 import urlopen, HTTPError from base64 import b64encode import hmac import hashlib import json import re UCLOUD_API_KEY = '' UCLOUD_SECRET = '' UCLOUD_API_URL ...
Python
0
dcc89b0d4757a4d2e0a541172ce3ded1f7e92014
Create CDAP's HDFS directory
package/scripts/master.py
package/scripts/master.py
import sys import ambari_helpers as helpers from resource_management import * class Master(Script): def install(self, env): print 'Install the CDAP Master'; import params self.configure(env) # Add repository file helpers.add_repo(params.files_dir + params.repo_file, params.os_repo_dir) # Inst...
import sys import ambari_helpers as helpers from resource_management import * class Master(Script): def install(self, env): print 'Install the CDAP Master'; import params self.configure(env) # Add repository file helpers.add_repo(params.files_dir + params.repo_file, params.os_repo_dir) # Inst...
Python
0
00bfbae48af80fd12db31aecc663373dce3fa1a8
Format code
megaprojects/core/models.py
megaprojects/core/models.py
import uuid from django.conf import settings from django.db import models class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = models.DateTimeField( auto_now_add=True, help_text='The time wh...
import uuid from django.conf import settings from django.db import models class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = models.DateTimeField( auto_now_add=True, help_text='The time wh...
Python
0.000002
93b25421bb1cca24e6927304d23501edf1484a22
Add sstable count metric
metartg/checks/cassandra.py
metartg/checks/cassandra.py
#!/usr/bin/env python import simplejson as json from time import time import subprocess import os def tpstats_metrics(): p = subprocess.Popen([ '/usr/bin/java', '-jar', '/usr/share/metartg/contrib/GenericJMXLogJSON.jar', 'localhost', '8080', 'org.apache.cassandra.concurrent:*', ], stdou...
#!/usr/bin/env python import simplejson as json from time import time import subprocess import os def tpstats_metrics(): p = subprocess.Popen([ '/usr/bin/java', '-jar', '/usr/share/metartg/contrib/GenericJMXLogJSON.jar', 'localhost', '8080', 'org.apache.cassandra.concurrent:*', ], stdou...
Python
0.002345
cdcae64d095a7cbab99e439bc37ee7009fe5c482
Mark version 0.3.1
mezzanine_polls/__init__.py
mezzanine_polls/__init__.py
__version__ = 0.3.1
__version__ = 0.3
Python
0.000008
afaa2dd700a7474b81b981b266ee5aaa977d28d5
Update team_rank_request.py to use response.json()
team_rank_request.py
team_rank_request.py
import requests from requests.auth import HTTPBasicAuth import secret import json x = 0 y = 0 parameters = 'teamstats' response = requests.get( 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/playoff_team_standings.json?teamstats', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) d...
import requests from requests.auth import HTTPBasicAuth import secret import json x = 0 y = 0 parameters = 'teamstats' response = requests.get( 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/playoff_team_standings.json?teamstats', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) r...
Python
0.000001
e16fbffeaa31fcffe2a2b511828427473217d3c2
Fix iOS template by adding checking on string icon corresponding to identifier
templates/tpl.ios.py
templates/tpl.ios.py
from string import Template ### Strings licence = """The MIT License (MIT) Copyright (c) 2015 Cobaltians 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 l...
from string import Template ### Strings licence = """The MIT License (MIT) Copyright (c) 2015 Cobaltians 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 l...
Python
0
f326dd569e9240c2b883e9c5f436728f321a0c61
Add TransactionMiddleware
tenant/middleware.py
tenant/middleware.py
from django.core.urlresolvers import resolve from django.shortcuts import get_object_or_404 from django.db import transaction from tenant.models import Tenant from tenant.utils import connect_tenant_provider, disconnect_tenant_provider class TenantMiddleware(object): def process_request(self, request): r...
from django.core.urlresolvers import resolve from django.shortcuts import get_object_or_404 from tenant.models import Tenant from tenant.utils import connect_tenant_provider, disconnect_tenant_provider class TenantMiddleware(object): def process_request(self, request): request.tenant = None name ...
Python
0
28332ebd6292223d5b5197b98160b0b3831c1ed4
Fix conversion warning
modules/nettokom/backend.py
modules/nettokom/backend.py
# -*- coding: utf-8 -*- # Copyright(C) 2012 Florent Fourcot # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
# -*- coding: utf-8 -*- # Copyright(C) 2012 Florent Fourcot # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
Python
0
48d4b35f92d848613297bdb9b5154f32b2c45d3b
rename 'set', add a missing return and fix a couple of other mode bugs
modules/python/ircclient.py
modules/python/ircclient.py
# Copyright (c) 2012 Stuart Walsh # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish...
# Copyright (c) 2012 Stuart Walsh # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish...
Python
0
83184a9ada18a82f3dfa4d73539f7a927ce50f01
Fix contact search breadcrumbs which were not correctly referencing parents
molly/apps/contact/views.py
molly/apps/contact/views.py
import simplejson import hashlib import urllib2 from datetime import timedelta from django.http import HttpResponse, Http404 from django.utils.translation import ugettext as _ from molly.utils.views import BaseView from molly.utils.breadcrumbs import * from molly.apps.contact.providers import BaseContactProvider, Too...
import simplejson import hashlib import urllib2 from datetime import timedelta from django.http import HttpResponse from django.utils.translation import ugettext as _ from molly.utils.views import BaseView from molly.utils.breadcrumbs import * from molly.apps.contact.providers import TooManyResults from .forms impor...
Python
0.000002
5168c98ea9b903a06cb52c79da81fe598abcb570
use correct import
mpf/devices/shot_profile.py
mpf/devices/shot_profile.py
"""Shot profiles.""" from mpf.core.mode import Mode from mpf.core.system_wide_device import SystemWideDevice from mpf.core.mode_device import ModeDevice class ShotProfile(ModeDevice, SystemWideDevice): """A shot profile.""" config_section = 'shot_profiles' collection = 'shot_profiles' class_label ...
"""Shot profiles.""" from mpfmc.core.mode import Mode from mpf.core.system_wide_device import SystemWideDevice from mpf.core.mode_device import ModeDevice class ShotProfile(ModeDevice, SystemWideDevice): """A shot profile.""" config_section = 'shot_profiles' collection = 'shot_profiles' class_labe...
Python
0.000013
119677750f88be27d1f7df8652e5457e5a424008
Fix syntax error.
myfedora/widgets/widgets.py
myfedora/widgets/widgets.py
# Copyright (C) 2008 Red Hat, Inc. All rights reserved. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be useful, but WITHOU...
# Copyright (C) 2008 Red Hat, Inc. All rights reserved. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be useful, but WITHOU...
Python
0.000004
3020bda26a6aa248f04b924cb6475ade4df8e511
use named arguments in jamfile.py
needy/generators/jamfile.py
needy/generators/jamfile.py
from ..generator import Generator import os import sys class JamfileGenerator(Generator): @staticmethod def identifier(): return 'jamfile' def generate(self, needy): path = os.path.join(needy.needs_directory(), 'Jamfile') target_args = { 'ios': '-t ios', '...
from ..generator import Generator import os import sys class JamfileGenerator(Generator): @staticmethod def identifier(): return 'jamfile' def generate(self, needy): path = os.path.join(needy.needs_directory(), 'Jamfile') target_args = { 'ios': '-t ios', '...
Python
0.000001
2626be18570958cca7665168f34166f1845ec6da
add test
test/service_test.py
test/service_test.py
# vim: set expandtab sw=4 ts=4: # # Unit tests for Service # # Copyright (C) 2014-2015 Dieter Adriaenssens <ruleant@users.sourceforge.net> # # This file is part of buildtimetrend/service # <https://github.com/buildtimetrend/service/> # # This program is free software: you can redistribute it and/or modify # it under th...
# vim: set expandtab sw=4 ts=4: # # Unit tests for Service # # Copyright (C) 2014-2015 Dieter Adriaenssens <ruleant@users.sourceforge.net> # # This file is part of buildtimetrend/service # <https://github.com/buildtimetrend/service/> # # This program is free software: you can redistribute it and/or modify # it under th...
Python
0.000002
b39ac9a59c4e6a36baa67a7ec57e687ee673aa68
Check for required UFO info fields
Lib/fontbakery/specifications/ufo_sources.py
Lib/fontbakery/specifications/ufo_sources.py
# -*- coding: utf-8 -*- # # This file has been automatically formatted with `yapf --style ' # {based_on_style: google}'` and `docformatter`. from __future__ import (absolute_import, division, print_function, unicode_literals) from fontbakery.callable import check, condition from fontbakery.chec...
# -*- coding: utf-8 -*- # # This file has been automatically formatted with `yapf --style ' # {based_on_style: google}'` and `docformatter`. from __future__ import (absolute_import, division, print_function, unicode_literals) from fontbakery.callable import check, condition from fontbakery.chec...
Python
0
6e6e2e03da2f4ef141b51843ca16fdb52f0770ca
Use tokenized no-reply address in send_test_email.
zerver/management/commands/send_test_email.py
zerver/management/commands/send_test_email.py
from typing import Any from django.conf import settings from django.core.mail import mail_admins, mail_managers, send_mail from django.core.management import CommandError from django.core.management.commands import sendtestemail from zerver.lib.send_email import FromAddress class Command(sendtestemail.Command): ...
from typing import Any from django.conf import settings from django.core.mail import mail_admins, mail_managers, send_mail from django.core.management import CommandError from django.core.management.commands import sendtestemail from zerver.lib.send_email import FromAddress class Command(sendtestemail.Command): ...
Python
0
90af4693dce351499e6898f02a5b2f6c2a0ca99f
Fix https://github.com/mottosso/Qt.py/issues/24
Qt.py
Qt.py
"""Map all bindings to PySide2 This module replaces itself with the most desirable binding. Resolution order: - PySide2 - PyQt5 - PySide - PyQt4 Usage: >>> import sys >>> from Qt import QtWidgets >>> app = QtWidgets.QApplication(sys.argv) >>> button = QtWidgets.QPushButton("Hello Worl...
"""Map all bindings to PySide2 This module replaces itself with the most desirable binding. Resolution order: - PySide2 - PyQt5 - PySide - PyQt4 Usage: >>> import sys >>> from Qt import QtWidgets >>> app = QtWidgets.QApplication(sys.argv) >>> button = QtWidgets.QPushButton("Hello Worl...
Python
0.000003
a971b84541b991bbc14be73e94b633c88edcd567
Remove unused vars
programs/ledcube/audio.py
programs/ledcube/audio.py
# # Copyright (c) 2014 PolyFloyd # import numpy.fft import os class Source: def get_spectrum(self, signal): signal = numpy.array([(s + 1) / 2 for s in signal], dtype=float) spectrum = numpy.abs(numpy.fft.rfft(signal)) freqs = numpy.fft.fftfreq(spectrum.size, 1 / self.get_sample_rate(...
# # Copyright (c) 2014 PolyFloyd # import io import numpy.fft import os import pyaudio class Source: def get_spectrum(self, signal): n = len(signal) signal = numpy.array([(s + 1) / 2 for s in signal], dtype=float) spectrum = numpy.abs(numpy.fft.rfft(signal)) freqs = numpy.fft...
Python
0.000001
573b34ef9a07b47549d8074548fc0b7a7238b016
fix flake8 error
project/ctnotify/views.py
project/ctnotify/views.py
# -*- coding: utf-8 -*- import json # from werkzeug import Response from boto.s3.connection import S3Connection from boto.s3.key import Key from google.appengine.api import urlfetch from google.appengine.ext import deferred from kay.utils import render_to_response from ctnotify.queue import get_process_que, get_s...
# -*- coding: utf-8 -*- import json # from werkzeug import Response from boto.s3.connection import S3Connection from boto.s3.key import Key from google.appengine.api import urlfetch from google.appengine.ext import deferred from kay.utils import render_to_response from ctnotify.queue import get_process_que, get_s...
Python
0
60887e7ffb6954bc78b0be7ece93690211837149
remove debug code
hs.py
hs.py
#!/usr/bin/python3 ################################################################################ # hs.py - Hokie Stalker # Query the Virginia Tech people search service for information about a person. # Licensed under the New BSD License. # # https://github.com/mutantmonkey/hokiestalker # author: mutantmonkey <mutan...
#!/usr/bin/python3 ################################################################################ # hs.py - Hokie Stalker # Query the Virginia Tech people search service for information about a person. # Licensed under the New BSD License. # # https://github.com/mutantmonkey/hokiestalker # author: mutantmonkey <mutan...
Python
0.02323
50628685c310703fb24f266dfd4d72b666eecfa4
Update version to 1.0.0 (not yet tagged)
py/desisurvey/_version.py
py/desisurvey/_version.py
__version__ = '1.0.0'
__version__ = '0.8.2.dev415'
Python
0
5934d94c9644eaea850a27773db5890b68078477
Load all api items
pybossa_analyst/client.py
pybossa_analyst/client.py
# -*- coding: utf8 -*- """API client module for pybossa-analyst.""" import enki class PyBossaClient(object): """A class for interacting with PyBossa.""" def __init__(self, app=None): """Init method.""" self.app = app if app is not None: # pragma: no cover self.init_app(a...
# -*- coding: utf8 -*- """API client module for pybossa-analyst.""" import enki class PyBossaClient(object): """A class for interacting with PyBossa.""" def __init__(self, app=None): """Init method.""" self.app = app if app is not None: # pragma: no cover self.init_app(a...
Python
0
73b7d0670414ec65a152d239a5c5c60464ce8ff9
Fix bad import. Fixes #2196
pymatgen/core/__init__.py
pymatgen/core/__init__.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This package contains core modules and classes for representing structures and operations on them. """ import os try: from ruamel import yaml except ImportError: try: import ruamel_yaml as...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This package contains core modules and classes for representing structures and operations on them. """ import os try: from ruamal import yaml except ImportError: try: import ruamel_yaml as...
Python
0.000001
afd6afa06e60676d1d633de9529dde0a5c4b6683
Remove unnecessary yield
python/ciphers/polyval.py
python/ciphers/polyval.py
# Copyright 2021 Google LLC # # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. import ciphers.cipher import ciphers.gf import parsers.polyval class Hash(ciphers.cipher.Cipher): def make_testvector(self, input, descr...
# Copyright 2021 Google LLC # # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. import ciphers.cipher import ciphers.gf import parsers.polyval class Hash(ciphers.cipher.Cipher): def make_testvector(self, input, descr...
Python
0.000015
d55f2b98822faa7d71f5fce2bfa980f8265e0610
Use take() instead of takeSample() in PySpark kmeans example.
python/examples/kmeans.py
python/examples/kmeans.py
""" This example requires numpy (http://www.numpy.org/) """ import sys import numpy as np from pyspark import SparkContext def parseVector(line): return np.array([float(x) for x in line.split(' ')]) def closestPoint(p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): ...
""" This example requires numpy (http://www.numpy.org/) """ import sys import numpy as np from pyspark import SparkContext def parseVector(line): return np.array([float(x) for x in line.split(' ')]) def closestPoint(p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): ...
Python
0
b5f2e4127a36d8509cd4ab3932ae20408726229d
rename clear_list() -> clear_object(), add random_string()
pywincffi/dev/testutil.py
pywincffi/dev/testutil.py
""" Test Utility ------------ This module is used by the unittests. """ import os import subprocess import sys from random import choice from string import ascii_lowercase, ascii_uppercase from cffi import FFI, CDefError try: # The setup.py file installs unittest2 for Python 2 # which backports newer test f...
""" Test Utility ------------ This module is used by the unittests. """ import os import subprocess import sys from cffi import FFI, CDefError try: # The setup.py file installs unittest2 for Python 2 # which backports newer test framework features. from unittest2 import TestCase as _TestCase except Impo...
Python
0.000059
e6104a60ba37cf7c34d371d51bce107ce69a0d06
rename handlers to handler-names in tests
src/unittest/python/cli_tests.py
src/unittest/python/cli_tests.py
from __future__ import print_function, absolute_import, division from unittest import TestCase import monocyte.cli as cli class CliTest(TestCase): def test_cloudwatch_can_be_deactivated(self): test_config = { "cloudwatchlogs": {} } expected_config = { "cloudw...
from __future__ import print_function, absolute_import, division from unittest import TestCase import monocyte.cli as cli class CliTest(TestCase): def test_cloudwatch_can_be_deactivated(self): test_config = { "cloudwatchlogs": {} } expected_config = { "cloudw...
Python
0
d680fca8bef783bd6fad7c71989ca51fb4725bc8
upgrade to latest chatexchange+fix
ws.py
ws.py
#requires https://pypi.python.org/pypi/websocket-client/ import websocket import threading import json,os,sys,getpass,time from findspam import FindSpam from ChatExchange.chatexchange.client import * import HTMLParser parser=HTMLParser.HTMLParser() if("ChatExchangeU" in os.environ): username=os.environ["ChatExchang...
#requires https://pypi.python.org/pypi/websocket-client/ import websocket import threading import json,os,sys,getpass,time from findspam import FindSpam from ChatExchange.chatexchange.client import * import HTMLParser parser=HTMLParser.HTMLParser() if("ChatExchangeU" in os.environ): username=os.environ["ChatExchang...
Python
0
e480a5e93015989d87331c5d8c0b251c73d40e2c
Use raw_id_fields in the TokenAdmin
readthedocs/core/admin.py
readthedocs/core/admin.py
# -*- coding: utf-8 -*- """Django admin interface for core models.""" from datetime import timedelta from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ ...
# -*- coding: utf-8 -*- """Django admin interface for core models.""" from datetime import timedelta from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ ...
Python
0
af5b574fb785e65fd1292bb28e90d005be1ecd03
Fix pep8 errors
reporter/test/test_osm.py
reporter/test/test_osm.py
# coding=utf-8 """Test cases for the OSM module. :copyright: (c) 2013 by Tim Sutton :license: GPLv3, see LICENSE for more details. """ import os from reporter.utilities import LOGGER from reporter.osm import load_osm_document, extract_buildings_shapefile from reporter.test.helpers import FIXTURE_PATH from reporter.te...
# coding=utf-8 """Test cases for the OSM module. :copyright: (c) 2013 by Tim Sutton :license: GPLv3, see LICENSE for more details. """ import os from reporter.utilities import LOGGER from reporter.osm import load_osm_document, extract_buildings_shapefile from reporter.test.helpers import FIXTURE_PATH from reporter.te...
Python
0.000217
acf2d57fa49a5ed25275a279d04946178f8cedde
Fix formatting and add doc strings
reporting_scripts/base.py
reporting_scripts/base.py
import csv from pymongo import MongoClient class BaseEdX(object): def __init__(self, args): self.url = args.url client = MongoClient(self.url) self.db = client[args.db_name] self.collections = None self.output_directory = args.output_directory self.row_limit = args...
import csv from pymongo import MongoClient class BaseEdX(object): def __init__(self, args): self.url = args.url client = MongoClient(self.url) self.db = client[args.db_name] self.collections = None self.output_directory = args.output_directory self.row_limit = args...
Python
0.000002
6d74c9d233aa44fd7072a269fa200bea610026b7
move WSfactory declaration for insecure connections to work
Web.py
Web.py
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS from twisted.web.server import Site from twisted.web.static import File from twisted.internet import reactor, task, ssl from twisted.web.util import Redirect from twisted.web.resource import Resource from Addresses import C...
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS from twisted.web.server import Site from twisted.web.static import File from twisted.internet import reactor, task, ssl from twisted.web.util import Redirect from twisted.web.resource import Resource from Addresses import C...
Python
0
0e58ef45f45df0192be6c52cd34df5f1b5c5a028
correct if condition
app.py
app.py
#!/usr/bin/env python import urllib import json import os from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json(silent=True, force=True) ...
#!/usr/bin/env python import urllib import json import os from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json(silent=True, force=True) ...
Python
0.999998
925ccb3c563da694866aa7396b71222d3ef1c2d6
Update path again
app.py
app.py
import json import datetime import random import os from flask import Flask from flask import render_template app = Flask(__name__) def isWeekend(date): if date.weekday() == 5 or date.weekday() == 6: return True else: return False def fuckShitUp(s): # Divide into words words = s.sp...
import json import datetime import random import os from flask import Flask from flask import render_template app = Flask(__name__) def isWeekend(date): if date.weekday() == 5 or date.weekday() == 6: return True else: return False def fuckShitUp(s): # Divide into words words = s.sp...
Python
0
e33a06ad4d4a7494f925a96e9d272e32e4dc18ba
Return json when error occurs
app.py
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser import logging import threading logging.basicConfig(level=logging.INFO) logging.getLogger("gospellibrary").setLevel(logging.WARNING) logging.getLogger("requests").setLevel...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser import logging import threading logging.basicConfig(level=logging.INFO) logging.getLogger("gospellibrary").setLevel(logging.WARNING) logging.getLogger("requests").setLevel...
Python
0.000142
d177d63ebc87208fdba4227377b2e1aebda8f077
Add port code for Heroku
app.py
app.py
import os from flask import Flask, Response, request from hypermedia_resource import HypermediaResource from hypermedia_resource.wrappers import HypermediaResponse, ResponseBuilder import maze app = Flask(__name__) # Helper functions for the views def maze_resource(type_of): """ Sets up a HypermediaResource ...
from flask import Flask, Response, request from hypermedia_resource import HypermediaResource from hypermedia_resource.wrappers import HypermediaResponse, ResponseBuilder import maze app = Flask(__name__) # Helper functions for the views def maze_resource(type_of): """ Sets up a HypermediaResource for the re...
Python
0.000003
874f63fff012c00a39c553e7eb9ca0ffcb4dcd18
error message: ERROR
app.py
app.py
#System Imports import sys, os import json import static import time import random from shutil import copyfile import operator import urllib2 import itertools import subprocess import math # from filechunkio import FileChunkIO from celery import Celery from collections import defaultdict, OrderedDict import collections...
#System Imports import sys, os import json import static import time import random from shutil import copyfile import operator import urllib2 import itertools import subprocess import math # from filechunkio import FileChunkIO from celery import Celery from collections import defaultdict, OrderedDict import collections...
Python
0.999999
096cd81f318e8446855fb806772c674328adc6b2
Create app.py
app.py
app.py
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError import json import os from flask import Flask from flask impor...
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError import json import os from flask import Flask from flask impor...
Python
0.000003
948100fde4a648e0f269c08fcb22ebdbc16948f1
move every get method into the new condor
app.py
app.py
# bultin library # external libraries from sanic import Sanic from sanic.response import text, json from condor.dbutil import requires_db from condor.models import Bibliography, RankingMatrix, TermDocumentMatrix, Document app = Sanic(__name__) @app.route("/ping") async def start(request): return text("pong") ...
# bultin library # external libraries from sanic import Sanic from sanic.response import text, json from condor.dbutil import requires_db from condor.models import Bibliography, RankingMatrix, TermDocumentMatrix, Document app = Sanic(__name__) @app.route("/ping") async def start(request): return text("pong") ...
Python
0
8fc38abecd4a9cba6579c7a422b957748115f450
disable CSRF token
app.py
app.py
from flask import Flask, render_template, flash from flask_wtf import Form from flask_wtf.file import FileField from tools import s3_upload import json app = Flask(__name__) app.config.from_object('config') class UploadForm(Form): example = FileField('Example File') @app.route('/', methods=['POS...
from flask import Flask, render_template, flash from flask_wtf import Form from flask_wtf.file import FileField from tools import s3_upload import json app = Flask(__name__) app.config.from_object('config') class UploadForm(Form): example = FileField('Example File') @app.route('/', methods=['POS...
Python
0.000001
e33174b6fcf8110478ec84016781ed65df7eb055
Add web-interface to utility
app.py
app.py
#!notify/bin/python3 import hug import os from pushbullet import Pushbullet @hug.get() @hug.cli() def create_note(title: hug.types.text, content: hug.types.text): api_key = os.environ["PB_API_KEY"] pb = Pushbullet(api_key) pb.push_note(title, content) if __name__ == '__main__': create_note.interfac...
#!notify/bin/python3 import hug import os from pushbullet import Pushbullet @hug.cli() def create_note(title: hug.types.text, content: hug.types.text): api_key = os.environ["PB_API_KEY"] pb = Pushbullet(api_key) pb.push_note(title, content) if __name__ == '__main__': create_note.interface.cli()
Python
0.999987
ed3ee7caae9ce754e2ec098e8889bfbed2198aa6
Print log msg before trying to write to log file
bot.py
bot.py
#!/usr/bin/python import init_twit as tw import markovgen, time, re, random, codecs # make a separate file for these reusable functions: bot.py # main bot-specific app logic in app.py corpus_file = 'corpus.txt' with open(corpus_file) as text: markov = markovgen.Markov(text) def log(msg): print msg with codecs.ope...
#!/usr/bin/python import init_twit as tw import markovgen, time, re, random, codecs # make a separate file for these reusable functions: bot.py # main bot-specific app logic in app.py corpus_file = 'corpus.txt' with open(corpus_file) as text: markov = markovgen.Markov(text) def log(msg): with codecs.open('log','a'...
Python
0
132b422e81c8a3f3de4d1600acdc6a71327bfc1e
Update bro .py
bro.py
bro.py
def bro(verbose, files=[]): import subprocess import os import time files = files.split("\n") files.pop(-1) if verbose == False: epoch = time.time() path = os.getcwd() os.mkdir(path + "/" + str(epoch)) os.chdir(path + "/" + str(epoch)) for file in files: subprocess.check_output(["bro","-r",file]) ...
def combiner(verbose, files=[]): import subprocess import os import time files = files.split("\n") files.pop(-1) if verbose == False: epoch = time.time() path = os.getcwd() os.mkdir(path + "/" + str(epoch)) os.chdir(path + "/" + str(epoch)) for file in files: subprocess.check_output(["bro","-r",fil...
Python
0.000001
4aad9aeb5acf0c8aba609a53f20107ec48cdfa2b
Initialise gpio
car.py
car.py
import time, os, sys import wiringpi as io class light(object): def __init__(self, pin): #make pins into output io.pinMode(pin,1) #set output low io.digitalWrite(pin,0) #set variables self.status = 0 self.pin = pin def on(self): #turn light on ...
import time, os, sys import wiringpi as io class light(object): def __init__(self, pin): #make pins into output io.pinMode(pin,1) #set output low io.digitalWrite(pin,0) #set variables self.status = 0 self.pin = pin def on(self): #turn light on ...
Python
0.000003
43a26a77d84fb8547564518a8469be69ed852cf1
add discourse to csp
csp.py
csp.py
csp = { 'default-src': '\'self\'', 'style-src': [ '\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com' ], 'script-src': [ '\'self\'', 'cdn.httparchive.org', 'www.google-analytics.com', 'use.fontawesome.com', 'cdn.speedcurve.com', 'spdcrv.global.ssl.fastly.net' ], 'font-src': [ '\'self\'', ...
csp = { 'default-src': '\'self\'', 'style-src': [ '\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com' ], 'script-src': [ '\'self\'', 'cdn.httparchive.org', 'www.google-analytics.com', 'use.fontawesome.com', 'cdn.speedcurve.com', 'spdcrv.global.ssl.fastly.net' ], 'font-src': [ '\'self\'', ...
Python
0.002031
fa954f6db40cf59779dcdb2303f6afc1b18388f0
Remove debugging prints and increase float precision.
csv.py
csv.py
#!/usr/bin/python #This script will slurp in a trace file and output a CSV formatted #file with the timestamp as the first column and subsequent vehicle #data keys as separate columns in undefined order. #TODO: This implementation is dead simple -- it will read through the #tracefile once to identify all unique keys ...
#!/usr/bin/python #This script will slurp in a trace file and output a CSV formatted #file with the timestamp as the first column and subsequent vehicle #data keys as separate columns in undefined order. #TODO: This implementation is dead simple -- it will read through the #tracefile once to identify all unique keys ...
Python
0
5000dc1045d2771b85528b60991e9ac2aad7d69d
fix bug to merge dict
sync_settings/libs/exceptions.py
sync_settings/libs/exceptions.py
# -*- coding: utf-8 -*- import json import sys import traceback class GistException(Exception): def to_json(self): json_error = json.loads(json.dumps(self.args[0])) trace = traceback.extract_tb(sys.exc_info()[2])[-1] return dict({ 'filename': str(trace[0]), 'line': str(trace[1]) }, **js...
# -*- coding: utf-8 -*- import json import sys import traceback class GistException(Exception): def to_json(self): json_error = json.loads(json.dumps(self.args[0])) trace = traceback.extract_tb(sys.exc_info()[2])[-1] return json_error.update({ 'filename': str(trace[0]), 'line': str(trace[1]...
Python
0
94c30a0efe0c3597678c64f46735ca7cd9990ccd
Revert Settings.py, only added admin schema
templatesAndSettings/settings.py
templatesAndSettings/settings.py
""" Keep this file untracked """ # SECURITY WARNING: keep the secret key used in production secret! secret_key = 'random_secret_key_like_so_7472873649836' media_root = 'C:/Users/leonmi/Google Drive/ODM2Djangoadmin/ODM2CZOData/upfiles/' media_url = '/odm2testapp/upfiles/' # Application definition custom_template_path...
""" Keep this file untracked """ # SECURITY WARNING: keep the secret key used in production secret! secret_key = 'random_secret_key_like_so_7472873649836' media_root = '/Users/lsetiawan/Desktop/shared_ubuntu/APL/ODM2/ODM2-Admin/ODM2CZOData/upfiles/' media_url = '/odm2testapp/upfiles/' # Application definition custom...
Python
0
2536526a383d1b2a921277970584ef5d3ba6073d
revert LIF base model
lif.py
lif.py
from numpy import * from pylab import * ## setup parameters and state variables T = 200 # total time to simulate (msec) dt = 0.125 # simulation time step (msec) time = arange(0, T+dt, dt) # time array t_rest = 0 # initial refractory time ## LIF propertie...
from numpy import * from pylab import * ## setup parameters and state variables T = 1000 # total time to simulate (msec) dt = 0.125 # simulation time step (msec) time = arange(0, T+dt, dt) # time array t_rest = 0 # initial refractory time ## LIF properti...
Python
0
ff7365e780624a1ef66c12a6d7b61448a3f9294c
fix flake8 warnings in zapwallettxes.py
test/functional/zapwallettxes.py
test/functional/zapwallettxes.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the zapwallettxes functionality. - start three bitcoind nodes - create four transactions on node ...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the zapwallettxes functionality. - start three bitcoind nodes - create four transactions on node ...
Python
0
74799081cd800cecd10e3b2248cf39c37ff42818
Move credentials so we can use them throughout the application
run.py
run.py
import json import os from google.cloud import pubsub import google.auth from micromanager import MicroManager from micromanager.resources import Resource from stackdriver import StackdriverParser # Load configuration project_id = os.environ.get('PROJECT_ID') subscription_name = os.environ.get('SUBSCRIPTION_NAME') ...
import json import os from google.cloud import pubsub import google.auth from micromanager import MicroManager from micromanager.resources import Resource from stackdriver import StackdriverParser # Load configuration project_id = os.environ.get('PROJECT_ID') subscription_name = os.environ.get('SUBSCRIPTION_NAME') ...
Python
0
3228b640d74dd1b06e9d96fb8265cc8c952074f6
solve Flatten layer issue
run.py
run.py
from keras.models import Model, Sequential from keras.layers import (Activation, Dropout, AveragePooling2D, Input, Flatten, MaxPooling2D, Convolution2D) from firemodule import FireModule from keras.datasets import cifar10, mnist from keras.optimizers import SGD from keras.utils import np_utils ...
from keras.models import Model from keras.layers import (Activation, Dropout, AveragePooling2D, Input, Flatten, MaxPooling2D, Convolution2D) from firemodule import FireModule from keras.datasets import cifar10, mnist from keras.optimizers import SGD from keras.utils import np_utils import nump...
Python
0.000002
454740f2657efa88efa16abdba93dc427bcf4d70
Add try catch to capture all the exceptions that might generate anywhere todo: need to capture exceptions in specific places and raise them to log from the main catch
run.py
run.py
from PdfProcessor import * import argparse from datetime import datetime import ConfigParser import ProcessLogger import traceback parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text') parser.add_argument('-i','--infile', help='File path of the input pdf file.', required=True) parser....
from PdfProcessor import * import argparse from datetime import datetime import ConfigParser import ProcessLogger parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text') parser.add_argument('-i','--infile', help='File path of the input pdf file.', required=True) parser.add_argument('-o'...
Python
0.000002
ec09e3b35d431232feb0df1577b3fe6578b68704
Remove old SSL code from run.py
run.py
run.py
import logging import os import sys import json import uvloop import asyncio from aiohttp import web from setproctitle import setproctitle from virtool.app import create_app from virtool.app_init import get_args, configure sys.dont_write_bytecode = True logger = logging.getLogger("aiohttp.server") setproctitle("vir...
import logging import os import sys import ssl import json import uvloop import asyncio from aiohttp import web from setproctitle import setproctitle from virtool.app import create_app from virtool.app_init import get_args, configure sys.dont_write_bytecode = True logger = logging.getLogger("aiohttp.server") setpro...
Python
0.000002
c15de13fa8dae840349463f6853f3edd3784ba6d
Update connect_db.py
connect_db.py
connect_db.py
#!/usr/bin/python from couchdb import Server # server = Server() # connects to the local_server # >>> remote_server = Server('http://example.com:5984/') # >>> secure_remote_server = Server('https://username:password@example.com:5984/') class db_server(object): def __init__(self,username,login): self.se...
from couchdb import Server # server = Server() # connects to the local_server # >>> remote_server = Server('http://example.com:5984/') # >>> secure_remote_server = Server('https://username:password@example.com:5984/') class db_server(object): def __init__(self,username,login): self.secure_server=Serve...
Python
0
73f335371db10008a2d221b777350f0b584abde6
use new TimingGenerator
nexys_video.py
nexys_video.py
#!/usr/bin/env python3 from nexys_base import * from litevideo.output.hdmi.s7 import S7HDMIOutClocking from litevideo.output.hdmi.s7 import S7HDMIOutPHY from litevideo.output.core import TimingGenerator class VideoOutSoC(BaseSoC): def __init__(self, platform, *args, **kwargs): BaseSoC.__init__(self, pla...
#!/usr/bin/env python3 from nexys_base import * from litevideo.output.hdmi.s7 import S7HDMIOutClocking from litevideo.output.hdmi.s7 import S7HDMIOutPHY from litevideo.output.core import TimingGenerator class VideoOutSoC(BaseSoC): def __init__(self, platform, *args, **kwargs): BaseSoC.__init__(self, p...
Python
0
3e7d2c771d6335411eb602240914b5cd3e15c227
Maintain only one list instead of two
crawler/crawler.py
crawler/crawler.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re import requests from lxml import html import redis redis_server = redis.StrictRedis(host='localhost', port=6379) def extract_num(raw): """Extract num from the unicode string.""" matched = re.se...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import requests from lxml import html import redis redis_server = redis.StrictRedis(host='localhost', port=6379) def extract_num(raw): """Extract num from the unicode string.""" matched = re.search(r'\d+', raw).group() return matched def update_...
Python
0.00033
2ab9c74041b998e1cad3a7a9c1f5be6feb7b63ac
Add todo for config validation
scd/config.py
scd/config.py
# -*- coding: utf-8 -*- # TODO Config validation from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import collections import logging import os.path import six import scd.files import scd.utils import scd.version Parser = collections.namedtuple("P...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import collections import logging import os.path import six import scd.files import scd.utils import scd.version Parser = collections.namedtuple("Parser", ["name", "func"])...
Python
0
398157d2b7e42a5de028af2a074c4465c6360e13
add timestamps to result in mongo
results.py
results.py
# experiment result wrapper import numpy as np import uuid import h5py from git import Repo from pymongo import MongoClient from datetime import datetime from time import time path_to_repo = '~/Documents/Thesis/latent_ssvm' path_to_datafile = '/home/dmitry/Documents/Thesis/latent_ssvm/notebooks/experiment_data.hdf...
# experiment result wrapper import numpy as np import uuid import h5py from git import Repo from pymongo import MongoClient path_to_repo = '~/Documents/Thesis/latent_ssvm' path_to_datafile = '/home/dmitry/Documents/Thesis/latent_ssvm/notebooks/experiment_data.hdf5' class experiment(object): def __init__(self...
Python
0.000007
18b53441a0136071db94c72b112a746e056ef971
refactor function to fetch datasets data for precomputes
wqflask/wqflask/correlation/pre_computes.py
wqflask/wqflask/correlation/pre_computes.py
import json import os import hashlib from base.data_set import query_table_timestamp from base.webqtlConfig import TMPDIR from json.decoder import JSONDecodeError from redis import Redis r = Redis() def generate_filename(base_dataset_name, target_dataset_name, base_timestamp, target_dataset_timestamp): """gener...
import json import os import hashlib from base.data_set import query_table_timestamp from base.webqtlConfig import TMPDIR from json.decoder import JSONDecodeError from redis import Redis r = Redis() def generate_filename(base_dataset_name, target_dataset_name, base_timestamp, target_dataset_timestamp): """gener...
Python
0.000001
8c8d6147f51d8c036f9d7cf9f7aa72e99cd6f4dd
fix list of unselected projects
rhw/models.py
rhw/models.py
from ckeditor.fields import RichTextField from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Idea(models.Model): title = models.CharField(max_length=100, u...
from ckeditor.fields import RichTextField from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Idea(models.Model): title = models.CharField(max_length=100, u...
Python
0.000003
76a7b89cd8c935dec87ac89ec36b174c9a0636c4
change lambda with broken typing to def
rich/pager.py
rich/pager.py
from abc import ABC, abstractmethod from typing import Any, Callable class Pager(ABC): """Base class for a pager.""" @abstractmethod def show(self, content: str) -> None: """Show content in pager. Args: content (str): Content to be displayed. """ class SystemPager(P...
from abc import ABC, abstractmethod from typing import Any, Callable class Pager(ABC): """Base class for a pager.""" @abstractmethod def show(self, content: str) -> None: """Show content in pager. Args: content (str): Content to be displayed. """ class SystemPager(P...
Python
0.000003
9bd5662194007d995c924d2d57f6af5c75075472
fix dashboard json output
ctfengine/views.py
ctfengine/views.py
import hashlib from flask import abort, flash, jsonify, render_template, request, redirect, \ url_for from ctfengine import app from ctfengine import database from ctfengine import lib from ctfengine import models @app.route('/') def index(): scores = models.Handle.topscores() total_points = database....
import hashlib from flask import abort, flash, jsonify, render_template, request, redirect, \ url_for from ctfengine import app from ctfengine import database from ctfengine import lib from ctfengine import models @app.route('/') def index(): scores = models.Handle.topscores() total_points = database....
Python
0.000129
821e87d574ec4eeb3c8e740c82dba3a979d9bae9
allow for Decimal and other types not inherently addable to float in SMA calculator.
cubes/statutils.py
cubes/statutils.py
from collections import deque from cubes.model import Attribute def _wma(values): n = len(values) denom = n * (n + 1) / 2 total = 0.0 idx = 1 for val in values: total += float(idx) * float(val) idx += 1 return round(total / denom, 4) def _sma(values): # use all the values ...
from collections import deque from cubes.model import Attribute def _wma(values): n = len(values) denom = n * (n + 1) / 2 total = 0.0 idx = 1 for val in values: total += float(idx) * float(val) idx += 1 return round(total / denom, 4) def _sma(values): # use all the values ...
Python
0
65e8aba17517247770ba27d796016c49fa41e0ab
correct handling of measure.ref() and aggregation selection in statutils' calculated aggregations
cubes/statutils.py
cubes/statutils.py
from collections import deque from cubes.model import Attribute def _wma(values): n = len(values) denom = n * (n + 1) / 2 total = 0.0 idx = 1 for val in values: total += float(idx) * float(val) idx += 1 return round(total / denom, 4) def _sma(values): # use all the values ...
from collections import deque from cubes.model import Attribute def _wma(values): n = len(values) denom = n * (n + 1) / 2 total = 0.0 idx = 1 for val in values: total += float(idx) * float(val) idx += 1 return round(total / denom, 4) def _sma(values): # use all the values ...
Python
0
582cacac1411312ad5e5dc132562883693f3877a
bump version
cyvcf2/__init__.py
cyvcf2/__init__.py
from .cyvcf2 import (VCF, Variant, Writer, r_ as r_unphased, par_relatedness, par_het) Reader = VCFReader = VCF __version__ = "0.8.7"
from .cyvcf2 import (VCF, Variant, Writer, r_ as r_unphased, par_relatedness, par_het) Reader = VCFReader = VCF __version__ = "0.8.6"
Python
0
e53ae572ac6c232a6afc01ae9ad2988ea1ef456a
Bump version.
robobrowser/__init__.py
robobrowser/__init__.py
__version__ = '0.4.1' from .browser import RoboBrowser
__version__ = '0.4.0' from .browser import RoboBrowser
Python
0
9efc16a9ce2187636d2ba75ff7982033854dbbe8
optimise apriltags
robotd/vision/vision.py
robotd/vision/vision.py
"""Classes for handling vision""" from robotd.native.apriltag._apriltag import ffi, lib from robotd.vision.camera import Camera from robotd.vision.camera_base import CameraBase from robotd.vision.tokens import Token class Vision: """Class that handles the vision library""" def __init__(self, camera: Camera...
"""Classes for handling vision""" from robotd.native.apriltag._apriltag import ffi, lib from robotd.vision.camera import Camera from robotd.vision.camera_base import CameraBase from robotd.vision.tokens import Token class Vision: """Class that handles the vision library""" def __init__(self, camera: Camera...
Python
0.999998
70b4be757d671bc86876b4568632bb6fe6064001
Fix a Django deprecation warning
admin_interface/templatetags/admin_interface_tags.py
admin_interface/templatetags/admin_interface_tags.py
# -*- coding: utf-8 -*- from django import template from admin_interface.models import Theme register = template.Library() @register.simple_tag(takes_context = True) def get_admin_interface_theme(context): theme = None request = context.get('request', None) if request: theme = getattr(reques...
# -*- coding: utf-8 -*- from django import template from admin_interface.models import Theme register = template.Library() @register.assignment_tag(takes_context = True) def get_admin_interface_theme(context): theme = None request = context.get('request', None) if request: theme = getattr(re...
Python
0.006582
2f3b5a6e0600f92ae0803ad3df44948dd5408444
comment out stdout log handler
cssbot/log.py
cssbot/log.py
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import logging from datetime import date import utils def __configure_logging(): # configure the base logger for the pkg l = logging.getLogger("cssbot") l.setLevel(logging.DEBUG) #...
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import logging from datetime import date import utils def __configure_logging(): # configure the base logger for the pkg l = logging.getLogger("cssbot") l.setLevel(logging.DEBUG) #...
Python
0
9abce530e50e4c1132e512abd51f39a60e4bd261
change max_depth check to >=
ai/minimax.py
ai/minimax.py
# http://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning def minimax(game, player, depth, max_depth): if game.game_over() or depth >= max_depth: return game.heuristic_value(player), [] best_score = -float('inf') if game.current_player == player else float('inf') best_moves = [] for move in ...
# http://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning def minimax(game, player, depth, max_depth): if game.game_over() or depth > max_depth: return game.heuristic_value(player), [] best_score = -float('inf') if game.current_player == player else float('inf') best_moves = [] for move in l...
Python
0
057110e3aa4007ad7221873029bed383ee1e0e3b
Remove platform check
aiotkinter.py
aiotkinter.py
import asyncio import tkinter class _TkinterSelector(asyncio.selectors._BaseSelectorImpl): def __init__(self): super().__init__() self._tk = tkinter.Tk(useTk=0) self._ready = [] def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) ...
import asyncio import tkinter import sys if sys.platform == 'win32': raise ImportError('%s is not available on your platform'.format(__name__)) class _TkinterSelector(asyncio.selectors._BaseSelectorImpl): def __init__(self): super().__init__() self._tk = tkinter.Tk(useTk=0) self._read...
Python
0
7ab744fe8464ce85a27431adf94039c45551010f
Remove Google analytics code.
publishconf.py
publishconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://dicasdejava.com.br' RELATIVE_URLS = F...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://dicasdejava.com.br' RELATIVE_URLS = F...
Python
0.000001