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
d3409629c120e366c9c7500bc111f61b13e74dc8
Change port.
bot.py
bot.py
import os import json import requests from flask import Flask from flask_restful import Resource, Api, reqparse from slackclient import SlackClient app = Flask(__name__) api = Api(app) token = os.environ.get('SLACK_KEY') sc = SlackClient(token) print sc.api_call('api.test') class RealName(Resource): def user_id...
import os import json import requests from flask import Flask from flask_restful import Resource, Api, reqparse from slackclient import SlackClient app = Flask(__name__) api = Api(app) token = os.environ.get('SLACK_KEY') sc = SlackClient(token) print sc.api_call('api.test') class RealName(Resource): def user_id...
Python
0
9ab748de8ca86b2f62bda30c5f2f3f0b2bde7047
Handle TimeoutException and improve code structure
bot.py
bot.py
import os import re import time import json import schedule import config from slackclient import SlackClient from handlers import HandlerManager from storage import Storage BOT_ID = '' sc = SlackClient(os.environ['SLACK_BOT_TOKEN']) storage = Storage() def post(channel, text, as_user=None): if as_user is None...
import os import re import time import json import schedule import config from slackclient import SlackClient from handlers import HandlerManager from storage import Storage BOT_ID = '' sc = SlackClient(os.environ['SLACK_BOT_TOKEN']) storage = Storage() def post(channel, text, as_user=None): if as_user is None...
Python
0
b367ff9e032d01f15aaaedc7e93446e9dda2649a
Fix outputing
bot.py
bot.py
import evaluation import sys settings = {} current_grid = [[0]] current_round = 0 me = -1 op = -1 def play(grid, column, color): grid = [x[:] for x in grid] for row in reversed(grid): if row[column] == 0: row[column] = color return grid # Can't play there return None d...
import evaluation settings = {} current_grid = [[0]] current_round = 0 me = -1 op = -1 def play(grid, column, color): grid = [x[:] for x in grid] for row in reversed(grid): if row[column] == 0: row[column] = color return grid # Can't play there return None def nodes(gr...
Python
0.999986
fae0989a5dc6886b11896f6ba5c6484cd1c1f735
Fix error on unknown command and blank game name
bot.py
bot.py
import asyncio import discord import text_adventure class Bot(object): def __init__(self, client, config): self.client = client self.config = config self.game_obj = None @asyncio.coroutine def do_command(self, message, command, *args): try: yield from getattr(se...
import asyncio import discord import text_adventure class Bot(object): def __init__(self, client, config): self.client = client self.config = config self.game_obj = None @asyncio.coroutine def do_command(self, message, command, *args): yield from getattr(self, command)(mess...
Python
0.000011
0958e4760264fcf232e655c47d88a03bf38896b0
Renamed subreddit command to reddit
bot.py
bot.py
import praw import discord from discord.ext import commands import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) reddit = praw.Reddit(client_id = os.environ.get("REDDIT_CLIENT_ID"), client_secret = os.environ.get("REDDIT_CLIENT_SECRET"), user_agent...
import praw import discord from discord.ext import commands import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) reddit = praw.Reddit(client_id = os.environ.get("REDDIT_CLIENT_ID"), client_secret = os.environ.get("REDDIT_CLIENT_SECRET"), user_agent...
Python
0.999985
af7af25ed5a13a4ce45f358ec5548c2f9e6a492e
remove wiki from DNL
bot.py
bot.py
import json import traceback from datetime import datetime from pathlib import Path import aiohttp import aredis import asyncpg from discord.ext import commands from utils.custom_context import CustomContext class QTBot(commands.Bot): def __init__(self, config_file, *args, **kwargs): self...
import json import traceback from datetime import datetime from pathlib import Path import aiohttp import aredis import asyncpg from discord.ext import commands from utils.custom_context import CustomContext class QTBot(commands.Bot): def __init__(self, config_file, *args, **kwargs): self...
Python
0
b8fb30a06ff15000a2d7542e7089b6c8ac1074e5
Add --allow-drilled flag to cli.py, and increase recursion limit
cli.py
cli.py
# Copyright (c) 2015 Matthew Earl # # 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, distr...
# Copyright (c) 2015 Matthew Earl # # 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, distr...
Python
0.000001
2352ce413cebb9f0fd7b1f26bb33bd0325abedfd
make more pylint friendly
csw.py
csw.py
#!/usr/bin/python -u # -*- coding: ISO-8859-15 -*- # ================================================================= # # $Id$ # # Authors: Tom Kralidis <tomkralidis@hotmail.com> # # Copyright (c) 2010 Tom Kralidis # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and ...
#!/usr/bin/python -u # -*- coding: ISO-8859-15 -*- # ================================================================= # # $Id$ # # Authors: Tom Kralidis <tomkralidis@hotmail.com> # # Copyright (c) 2010 Tom Kralidis # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and ...
Python
0.000002
12c7d473e2a270d46722b936a8fe9b62eb7548f1
Add test for issue 203
h5py/_hl/tests/test_slicing.py
h5py/_hl/tests/test_slicing.py
import numpy as np from .common import ut, TestCase import h5py from h5py.highlevel import File class BaseSlicing(TestCase): def setUp(self): self.f = File(self.mktemp(), 'w') def tearDown(self): if self.f: self.f.close() class TestSingleElement(BaseSlicing): """ F...
import numpy as np from .common import ut, TestCase import h5py from h5py.highlevel import File class BaseSlicing(TestCase): def setUp(self): self.f = File(self.mktemp(), 'w') def tearDown(self): if self.f: self.f.close() class TestSingleElement(BaseSlicing): """ F...
Python
0
8c87da20876c6b633988063eac81ff2b0f602dbb
Fix url encoding
ptscrape.py
ptscrape.py
#======================================================================= # Screen-scraping framework #======================================================================= import logging try: import bs4 as soup except ImportError: import BeautifulSoup as soup import urllib2 from urllib import urlencode ...
#======================================================================= # Screen-scraping framework #======================================================================= import logging try: import bs4 as soup except ImportError: import BeautifulSoup as soup import urllib2 from urllib import urlencode ...
Python
0.998718
51f46c57e209e35063f67055e45ff6e26f8aa552
Format error on urlfetch.get fail
heat/engine/resources/stack.py
heat/engine/resources/stack.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicab...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicab...
Python
0.000002
22aead72594e5aa7047858c04beb3018e93c59fe
Revert "started 0.2.x"
api/apps.py
api/apps.py
from __future__ import unicode_literals from django.apps import AppConfig APP_NAME = 'vsemionov.notes.api' APP_VERSION = '0.1.0' class ApiConfig(AppConfig): name = 'api'
from __future__ import unicode_literals from django.apps import AppConfig APP_NAME = 'vsemionov.notes.api' APP_VERSION = '0.2' class ApiConfig(AppConfig): name = 'api'
Python
0
492005db9a7c34b2648de8b7335bdbdd18ffb13b
Update setup.py with release version.
py/setup.py
py/setup.py
# Lint as: python3 # Copyright 2020 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 agr...
# Lint as: python3 # Copyright 2020 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 agr...
Python
0
71b93971486ac4bf80284de43962d4704642a890
add missing _ on line 37
riskroll.py
riskroll.py
from sys import exit from app.RollDice import roll def get_number_of_combatants(): """Take no input and return tuple of ints.""" num_of_attackers = [1,2,3] num_of_defenders = [1,2] attackers = 0 defenders = 0 while attackers not in num_of_attackers: attackers = int(raw_input('How...
from sys import exit from app.RollDice import roll def get_number_of_combatants(): """Take no input and return tuple of ints.""" num_of_attackers = [1,2,3] num_of_defenders = [1,2] attackers = 0 defenders = 0 while attackers not in num_of_attackers: attackers = int(raw_input('How...
Python
0.999982
d31d767ec4c4452e8a1d5f9dd896ade19e4ac645
Fix tests
run_test.py
run_test.py
import asynctwitch as at class Bot(at.CommandBot, at.RankedBot): pass bot = Bot( user='justinfan100' # read-only client ) @bot.command("test", desc="Some test command") async def test(m, arg1:int): pass bot.add_rank("test rank", points=10) @bot.override async def raw_event(data): print(data) @bot...
import asynctwitch as at class Bot(at.CommandBot, at.RankedBot): pass bot = Bot( user='justinfan100' # read-only client ) @bot.command("test", desc="Some test command") async def test(m, arg1:int): pass bot.add_rank("test rank", points=10) @bot.override async def raw_event(data): print(data) @bot...
Python
0.000003
38a086d2c5ebf73f7ad0108def2304262a2e0452
Add trailing comma
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "pinax.likes", "pinax.likes...
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "pinax.likes", "pinax.likes...
Python
0.999944
3cc083e08a586e61a8e89a549ba63c6bc5ede2bb
Add :mod:`firmant.writers.staticrst` to tests
runtests.py
runtests.py
#!/usr/bin/python import gettext import unittest import doctest import sys from optparse import OptionParser from minimock import Mock from pprint import pprint from pysettings.modules import get_module gettext.install('firmant') def safe_displayhook(s): if s is not None: sys.stdout.write('%r\n' % s) ...
#!/usr/bin/python import gettext import unittest import doctest import sys from optparse import OptionParser from minimock import Mock from pprint import pprint from pysettings.modules import get_module gettext.install('firmant') def safe_displayhook(s): if s is not None: sys.stdout.write('%r\n' % s) ...
Python
0
98109c41048bb8330348cd0ab51a175328b056d6
make runtests executable
runtests.py
runtests.py
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INST...
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INST...
Python
0.000003
8830fece0992a6e1360440b51956c6ae6a4b034a
Add `SECRET_KEY` to django config
runtests.py
runtests.py
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings from django.utils.crypto import get_random_string sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( SECRET_KEY=get_random_string(), INS...
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings import django sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'djan...
Python
0.000009
d9caaf949e9fe59a656c5986180038b9b3dc34fe
remove league alias
bot/module/commands/command_processor.py
bot/module/commands/command_processor.py
import logging from bot.module.commands.calendar.calendar_processor import CalendarProcessor from bot.module.commands.info.info_processor import InfoProcessor from bot.module.commands.crs.crs_processor import CrsProcessor from bot.module.commands.wiki.wiki_processor import WikiProcessor class CommandProcessor(InfoPr...
import logging from bot.module.commands.calendar.calendar_processor import CalendarProcessor from bot.module.commands.info.info_processor import InfoProcessor from bot.module.commands.crs.crs_processor import CrsProcessor from bot.module.commands.wiki.wiki_processor import WikiProcessor class CommandProcessor(InfoPr...
Python
0.000395
cc626bef4bb9ad4888362476a3ce9f92154f7d53
Resolve #74 -- Use result.get instastad of ready
health_check/contrib/celery/plugin_health_check.py
health_check/contrib/celery/plugin_health_check.py
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.conf import settings from health_check.backends.base import ( BaseHealthCheckBackend, ServiceUnavailable, ServiceReturnedUnexpectedResult) from health_check.plugins import plugin_dir from .tasks import add class CeleryHealthCheck(B...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from time import sleep from django.conf import settings from health_check.backends.base import ( BaseHealthCheckBackend, ServiceUnavailable ) from health_check.plugins import plugin_dir from .tasks import add class CeleryHealthCheck(BaseHealthChec...
Python
0
ac6302f506299ed881ad4971ec30367e083c9433
remove unneeded lower() call on repo name in require.rpm.repo(), as we're doing it early in the method
fabtools/require/rpm.py
fabtools/require/rpm.py
""" Rpm packages =============== This module provides high-level tools for managing CentOS/RHEL/SL packages and repositories. """ from __future__ import with_statement from fabtools.system import get_arch from fabtools.rpm import * def package(pkg_name, repos=None, yes=None, options=None): """ Require a rp...
""" Rpm packages =============== This module provides high-level tools for managing CentOS/RHEL/SL packages and repositories. """ from __future__ import with_statement from fabtools.system import get_arch from fabtools.rpm import * def package(pkg_name, repos=None, yes=None, options=None): """ Require a rp...
Python
0
f641c4be6e88aac1e1968ca8f07c5294d4dfe6fa
Bump version
facturapdf/__about__.py
facturapdf/__about__.py
__title__ = 'facturapdf' __summary__ = 'Create PDF invoice according to Spanish regulations.' __version__ = '0.0.3' __license__ = 'BSD 3-Clause License' __uri__ = 'https://github.com/initios/factura-pdf' __author__ = 'Carlos Goce' __email__ = 'cgonzalez@initios.com'
__title__ = 'facturapdf' __summary__ = 'Create PDF invoice according to Spanish regulations.' __version__ = '0.0.2' __license__ = 'BSD 3-Clause License' __uri__ = 'https://github.com/initios/factura-pdf' __author__ = 'Carlos Goce' __email__ = 'cgonzalez@initios.com'
Python
0
1e3199618f55be86fa5e4259d1c6e4a7074e57ca
Update environment.py
features/environment.py
features/environment.py
""" Copyright 2017 Raul Alvarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ...
""" Copyright 2017 Raul Alvarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ...
Python
0.000001
44a41555d4f2ec3eed090711f34b233085e1aebf
add missing config entries
feedservice/settings.py
feedservice/settings.py
# -*- coding: utf-8 -*- import os, os.path def bool_env(val, default): """Replaces string based environment values with Python booleans""" if not val in os.environ: return default return True if os.environ.get(val) == 'True' else False DEBUG = bool_env('MYGPOFS_DEBUG', True) TEMPLATE_DEBUG = ...
# -*- coding: utf-8 -*- import os, os.path def bool_env(val, default): """Replaces string based environment values with Python booleans""" if not val in os.environ: return default return True if os.environ.get(val) == 'True' else False DEBUG = bool_env('MYGPOFS_DEBUG', True) TEMPLATE_DEBUG = ...
Python
0.000002
576ea74646935c00e051a46244b8f56165710df0
Add multicast send
circuits/node/server.py
circuits/node/server.py
# Module: server # Date: ... # Author: ... """Server ... """ from circuits.net.sockets import TCPServer from circuits import handler, BaseComponent from .protocol import Protocol class Server(BaseComponent): """Server ... """ channel = 'node' __protocol = {} def __init__(self, b...
# Module: server # Date: ... # Author: ... """Server ... """ from circuits.net.sockets import TCPServer from circuits import handler, BaseComponent from .protocol import Protocol class Server(BaseComponent): """Server ... """ channel = 'node' __protocol = {} def __init__(self, b...
Python
0.000001
8c68031928f54d38c92308504bc93bf61ead57f5
Update clashcallerbot_reply.py added get list of messages older than current datetime, updated outline
clashcallerbot_reply.py
clashcallerbot_reply.py
#! python3 # -*- coding: utf-8 -*- """Checks messages in database and sends PM if expiration time passed. This module checks messages saved in a MySQL-compatible database and sends a reminder via PM if the expiration time has passed. If so, the message is removed from the database. """ import praw import praw.excepti...
#! python3 # -*- coding: utf-8 -*- """Checks messages in database and sends PM if expiration time passed. This module checks messages saved in a MySQL-compatible database and sends a reminder via PM if the expiration time has passed. If so, the message is removed from the database. """ import praw import praw.excepti...
Python
0
f7f16611754181c28b1c8c6a3e5942731f851c46
add some docstring
fileparser/extractor.py
fileparser/extractor.py
#!/usr/bin/env python # -*- coding: utf-8 -*- r""" # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------....
#!/usr/bin/env python # -*- coding: utf-8 -*- r""" # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------....
Python
0.000041
42923355855a53cd7d6df23f666c2c74a07c7068
fix healpix_helper to take of nans
lib/healpix_helper.py
lib/healpix_helper.py
import pyfits import numpy as np try: import pywcs except ImportError: import astropy.pywcs as pywcs import healpy import warnings class HealpixData(object): def __init__(self, nside, data, coord=None, nested=False, flipy=False): self._nside = nside self._data = data self._nested...
import pyfits import numpy as np try: import pywcs except ImportError: import astropy.pywcs as pywcs import healpy import warnings class HealpixData(object): def __init__(self, nside, data, coord=None, nested=False, flipy=False): self._nside = nside self._data = data self._nested...
Python
0
2cbae4650422f7982ef50e564e9e27e7fd294be8
Add ability to nix product to admin
fjord/feedback/admin.py
fjord/feedback/admin.py
from django.contrib import admin from django.core.exceptions import PermissionDenied from fjord.feedback.models import Product, Response class ProductAdmin(admin.ModelAdmin): list_display = ( 'id', 'enabled', 'on_dashboard', 'display_name', 'db_name', 'translation_...
from django.contrib import admin from django.core.exceptions import PermissionDenied from fjord.feedback.models import Product, Response class ProductAdmin(admin.ModelAdmin): list_display = ( 'id', 'enabled', 'on_dashboard', 'display_name', 'db_name', 'translation_...
Python
0
e19e2d69baabac3adedfae4e7a8c6ef5bb3d6f53
Fix alembic script
alembic/versions/4e0500347ce7_add_multigame_tables.py
alembic/versions/4e0500347ce7_add_multigame_tables.py
"""add multigame tables Revision ID: 4e0500347ce7 Revises: 29344aa34d9 Create Date: 2016-04-05 23:51:58.647657 """ # revision identifiers, used by Alembic. revision = '4e0500347ce7' down_revision = '29344aa34d9' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alemb...
"""add multigame tables Revision ID: 4e0500347ce7 Revises: 29344aa34d9 Create Date: 2016-03-30 12:26:36.632566 """ # revision identifiers, used by Alembic. revision = '4e0500347ce7' down_revision = '29344aa34d9' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'publisher'...
Python
0.000033
10f8deb343d17e73185bef916396a80c73b718ed
Add link to migration guide (#10821)
conans/pylint_plugin.py
conans/pylint_plugin.py
"""Pylint plugin for ConanFile""" import re import astroid from astroid import MANAGER from pylint.checkers import BaseChecker from pylint.interfaces import IRawChecker def register(linter): """required method to auto register this checker""" linter.register_checker(ConanDeprecatedImportsChecker(linter)) d...
"""Pylint plugin for ConanFile""" import re import astroid from astroid import MANAGER from pylint.checkers import BaseChecker from pylint.interfaces import IRawChecker def register(linter): """required method to auto register this checker""" linter.register_checker(ConanDeprecatedImportsChecker(linter)) d...
Python
0
6fb6fdee06410d1d051134f0b9dcb47ad2ac1885
Simplify code around re-raising an error.
azurectl/setup_account_task.py
azurectl/setup_account_task.py
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
Python
0.999998
e642a82c4ed1e146fe64f97e3694355310abbcf7
Add load and save methods
dem.py
dem.py
""" Classes for loading digital elevation models as numeric grids """ import os, sys import numpy as np from osgeo import gdal, gdalconst import osr class CalculationMixin(object): def _caclulate_slope(self): PAD_DX = 2 PAD_DY = 2 z_pad = self._pad_boundary(PAD_DX, PAD_DY) ...
""" Classes for loading digital elevation models as numeric grids """ import os, sys import numpy as np from osgeo import gdal, gdal_const class CalculationMixin(object): def _caclulate_slope(self): PAD_DX = 2 PAD_DY = 2 z_pad = self._pad_boundary(PAD_DX, PAD_DY) slope_x = (z_pad...
Python
0
bd98a1b1119b34a5435855478d733ca582ebcf0c
Update version to dev
powerpool/__init__.py
powerpool/__init__.py
__version__ = "0.6.3-dev" __version_info__ = (0, 6, 3)
__version__ = "0.6.2" __version_info__ = (0, 6, 2)
Python
0
49cf5af6c62bb23c8fce660f4b649bb0775ecdbc
494. Target Sum
problems/test_0494.py
problems/test_0494.py
import unittest from typing import List import utils # O(len(nums) * (sum(nums) + max(nums))) time. O(len(nums) * (sum(nums) + max(nums))) space. DP, 0-1 knapsack. class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: if not nums: return 1 if S == 0 else 0 sum_...
import unittest from typing import List import utils # O(len(nums) * sum(nums)) time. O(len(nums) * sum(nums)) space. DP, 0-1 knapsack. class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: sum_nums = sum(nums) if not (-sum_nums <= S <= sum_nums): return 0 ...
Python
0.999999
6da626bf1a999101af188d3d20710a6dddc8dbae
shell=True
ide.py
ide.py
# NOTE: pass -d to this to print debugging info when the server crashes. from flask import Flask, render_template, url_for, request from subprocess import Popen, PIPE, check_call import sys, os, string, glob, logging app = Flask(__name__) app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(lo...
# NOTE: pass -d to this to print debugging info when the server crashes. from flask import Flask, render_template, url_for, request from subprocess import Popen, PIPE, check_call import sys, os, string, glob, logging app = Flask(__name__) app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(lo...
Python
0.999989
ff99addf5ac6589b4ee2c53ef1debf4e9c07b47d
Bump version 0.2 Stable
__tryton__.py
__tryton__.py
#This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. { 'name': 'Nereid Catalog', 'version': '2.0.0.2', 'author': 'Openlabs Technologies & Consulting (P) LTD', 'email': 'info@openlabs.co.in', 'website': 'http://w...
#This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. { 'name': 'Nereid Catalog', 'version': '2.0.0.1', 'author': 'Openlabs Technologies & Consulting (P) LTD', 'email': 'info@openlabs.co.in', 'website': 'http://w...
Python
0.000001
d826e54996bc504d245286b50f7ab5671f1999ae
Update solution.py
data_structures/linked_list/problems/find_pattern_in_linked_list/py/solution.py
data_structures/linked_list/problems/find_pattern_in_linked_list/py/solution.py
import LinkedList # Problem description: Find a string pattern represented as a linked list in a target linked list. # Solution time complexity: O(n^2) # Comments: A brute force solution w/o any optimizations. Simply traverse a list looking for the pattern. # If the node ...
import LinkedList # Problem description: Find a pattern represented as a linked list in a target linked list. # Solution time complexity: O(n^2) # Comments: A brute force solution w/o any optimizations. Simply traverse a list looking for the pattern. # If the node travers...
Python
0.000001
7ceaec12381e8bc7f597b1cc32d50655d30d9843
use inplace installs (#5865)
nox.py
nox.py
# Copyright 2017, Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2017, Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Python
0
7c527f486e2e129861915f73e0625ec00388e15e
Fix failing MPI tests
test/hoomd_script/test_multiple_contexts.py
test/hoomd_script/test_multiple_contexts.py
# -*- coding: iso-8859-1 -*- from hoomd_script import * import hoomd_script; context.initialize() import unittest import os # unit test to run a simple polymer system with pair and bond potentials class multi_context(unittest.TestCase): def test_run(self): self.c1 = context.SimulationContext() sel...
# -*- coding: iso-8859-1 -*- from hoomd_script import * import hoomd_script; context.initialize() import unittest import os # unit test to run a simple polymer system with pair and bond potentials class multi_context(unittest.TestCase): def test_run(self): self.c1 = context.SimulationContext() sel...
Python
0.000013
988ed4be9152632b2844e962e225adac63d869db
Fix crash on windows
spd.py
spd.py
#!/usr/bin/env python3 import os import re import sys from platform import system as operatingSystem from subprocess import call from urllib.request import Request, urlopen def getWebPage(url): print("\ngetting: "+url) h = Request(url) h.add_header('User-Agent', 'SPD/1.0') webpage = urlopen(h).read(...
#!/usr/bin/env python3 import os import re import sys from subprocess import call from urllib.request import Request, urlopen def getWebPage(url): print("\ngetting: "+url) h = Request(url) h.add_header('User-Agent', 'SPD/1.0') webpage = urlopen(h).read() return str(webpage) # convert from bytes...
Python
0
1e8094a187284961a380bea94bbc806aa4430a3d
fix to t2m.py
t2m.py
t2m.py
#! /usr/bin/env python # Requires python 2.7 import sys import socket import datetime import json import logging import os if os.path.exists('/vagrant'): logfilename = '/vagrant/.t2m.log' else: logfilename = '/tmp/.t2m.log' logging.basicConfig( filename=logfilename, level=logging.DEBUG) BUFSIZE = ...
#! /usr/bin/env python # Requires python 2.7 import sys import socket import datetime import json import logging if os.path.exists('/vagrant'): logfilename = '/vagrant/.t2m.log' else: logfilename = '/tmp/.t2m.log' logging.basicConfig( filename=logfilename, level=logging.DEBUG) BUFSIZE = 1024 DEBUG ...
Python
0.999996
96f93e39ad12d893d8672dd2bb2abea4e6020799
update the file name in the send file to uri
bin/utils/sftp_transactions.py
bin/utils/sftp_transactions.py
import pysftp as sftp import sys import os from email_transactions import email_transactions import paramiko # This addresses the issues with relative paths file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../") proj_root = os.path.abspath(goal_dir)+'/' sys.path.insert(0, proj_...
import pysftp as sftp import sys import os from email_transactions import email_transactions import paramiko # This addresses the issues with relative paths file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../") proj_root = os.path.abspath(goal_dir)+'/' sys.path.insert(0, proj_...
Python
0.000001
0d4c041d239e7d7ed234f359ae483523b05e367b
correct the 'View Credentials' icon
openstack_dashboard/dashboards/project/access_and_security/api_access/tables.py
openstack_dashboard/dashboards/project/access_and_security/api_access/tables.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
Python
0.000003
402e9515419f0db7f449eac9f810389a4608b878
Comment out venue for now, since we don't have one yet
settings.py
settings.py
# -*- encoding: utf-8 -*- import os from wafer.settings import * try: from localsettings import * except ImportError: pass from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse_lazy pyconzadir = os.path.dirname(__file__) STATICFILES_DIRS = ( os.path.join(...
# -*- encoding: utf-8 -*- import os from wafer.settings import * try: from localsettings import * except ImportError: pass from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse_lazy pyconzadir = os.path.dirname(__file__) STATICFILES_DIRS = ( os.path.join(...
Python
0
39586322784382e9dfd4a961bda4253bb27bca5f
Add support for the django debug toolbar
settings.py
settings.py
# Django settings for authentic project. import os DEBUG = True USE_DEBUG_TOOLBAR = True TEMPLATE_DEBUG = DEBUG PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends...
# Django settings for authentic project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgre...
Python
0
145c31a283bb458bdce72169ea16f07040236ee5
add comment about settings.py
settings.py
settings.py
""" To run `django-admin.py syncdb --settings settings --noinput` before testing. """ SECRET_KEY = 'x' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'travis_ci_test', } } INSTALLED_APPS=( 'django.contrib.admin', 'django.contrib.auth', 'djan...
SECRET_KEY = 'x' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'travis_ci_test', } } INSTALLED_APPS=( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'boundaries', )
Python
0
417ab5241c852cdcd072143bc2444f20f2117623
Update capture profiler to new spec of providing board instead of string.
tests/execution_profiles/capture_profile.py
tests/execution_profiles/capture_profile.py
import cProfile from pqhelper import capture def main(): cProfile.run('test_solution(catapult)') def test_solution(board_string): board = capture.Board(board_string) print capture.capture(board) skeleton = ''' ..*..*.. .gm..mg. .ms..sm. .rs..sr. .ggmmgg. .rsggsr. .rsrrsr. ssgssgss''' giant_rat = ''' ...
import cProfile from pqhelper import capture def main(): cProfile.run('test_solution(catapult)') def test_solution(board_string): print capture.capture(board_string) skeleton = ''' ..*..*.. .gm..mg. .ms..sm. .rs..sr. .ggmmgg. .rsggsr. .rsrrsr. ssgssgss''' giant_rat = ''' ...mm... ..mrym.. .mgyrgm. mygryg...
Python
0
5829afb4345d09a04fca61e51624f580a95c408d
remove None.appspot.com from settings.PLAYGROUND_HOSTS
settings.py
settings.py
"""Module containing global playground constants and functions.""" import os from google.appengine.api import app_identity from google.appengine.api import backends import appids import secret DEBUG = True # user content hostname prefix USER_CONTENT_PREFIX = 'user-content' # RFC1113 formatted 'Expires' to preve...
"""Module containing global playground constants and functions.""" import os from google.appengine.api import app_identity from google.appengine.api import backends import appids import secret DEBUG = True # user content hostname prefix USER_CONTENT_PREFIX = 'user-content' # RFC1113 formatted 'Expires' to preve...
Python
0.000005
08edcd99f379962cbd761c743a727e86095b7a48
Convert to list in case it is not
setup.in.py
setup.in.py
# # Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL # from __future__ import print_function try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import hashlib impo...
# # Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL # from __future__ import print_function try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import hashlib impo...
Python
1
a12d61e9a9b85c436d5b21b39862497b7e3ed903
update tpp.py for gen3
tpp.py
tpp.py
#This script will show updates to the Twitch Plays Pokemon live feed on reddit. #You can only show important updates by passing the --important flag when you run the script #This could be easily adapted for other live feeds (or totally generic) but for now #it is hardcoded for the TPP feed. #python-requests is require...
#This script will show updates to the Twitch Plays Pokemon live feed on reddit. #You can only show important updates by passing the --important flag when you run the script #This could be easily adapted for other live feeds (or totally generic) but for now #it is hardcoded for the TPP feed. #python-requests is require...
Python
0
c81eb510c72511c1f692f02f7bb63ef4caa51d27
Add management functions for migration
apps/concept/management/commands/update_concept_totals.py
apps/concept/management/commands/update_concept_totals.py
from optparse import make_option import sys from django.core.management.base import BaseCommand from concept.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.obj...
from optparse import make_option import sys from django.core.management.base import BaseCommand from education.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.o...
Python
0
6a39a514ae82f412c107dd87944cdb17b6a9d036
remove isinstance assert in test_remove_site_packages_64bit
tests/test_server32_remove_site_packages.py
tests/test_server32_remove_site_packages.py
import os import sys try: import pytest except ImportError: # the 32-bit server does not need pytest installed class Mark(object): @staticmethod def skipif(condition, reason=None): def func(function): return function return func class pytest(object)...
import os import sys try: import pytest except ImportError: # the 32-bit server does not need pytest installed class Mark(object): @staticmethod def skipif(condition, reason=None): def func(function): return function return func class pytest(object)...
Python
0.000007
7d47ab3aed3fb1c591966fe1a84e7c5f8d4ce909
Print usage if only an optional option sent
qos.py
qos.py
#!/usr/bin/python # Author: Anthony Ruhier # Set QoS rules import os import subprocess import argparse import sys import logging try: from config import DEBUG except ImportError: DEBUG = False import tools def run_as_root(): """ Restart the script as root """ # Need to be root if os.get...
#!/usr/bin/python # Author: Anthony Ruhier # Set QoS rules import os import subprocess import argparse import sys import logging try: from config import DEBUG except ImportError: DEBUG = False import tools def run_as_root(): """ Restart the script as root """ # Need to be root if os.get...
Python
0.000005
6fc065dc2f88c0c59037f5a6efa89738d963977e
Support XML-RPC marshalling of mx.DateTime.
rpc.py
rpc.py
import xmlrpclib import traceback from cStringIO import StringIO allowed = ('package_releases', 'package_urls', 'package_data', 'search', 'list_packages', 'release_urls', 'release_data', 'updated_releases', 'changelog', 'post_cheesecake_for_release') # monkey-patch xmlrpclib to marshal mx.DateTime correctly. ...
import xmlrpclib import traceback from cStringIO import StringIO allowed = ('package_releases', 'package_urls', 'package_data', 'search', 'list_packages', 'release_urls', 'release_data', 'updated_releases', 'changelog', 'post_cheesecake_for_release') def handle_request(webui_obj): webui_obj.handler.send_r...
Python
0
79ef0fe21b136b80889a8e6e06339074ac73a1f1
Comment out section
run.py
run.py
__author__ = 'matt' # import datetime import blockbuster # blockbuster.app.debug = blockbuster.config.debug_mode # # blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") # blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " " # ...
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " " ...
Python
0
35028b84d4757e1343a97da653670db049ac5e8d
replace default handler with static handler
web.py
web.py
#!/usr/bin/env python2 import tornado import log from tornado import web, httpserver _http_server = None _https_server = None _html_root = './' _log = None # TODO: SSL needs this # ssl_options['certfile'] - server certificate # ssl_options['keyfile'] - server key # ssl_options['ca_certs'] - CA certificate def run_s...
#!/usr/bin/env python2 import tornado import log import magic from tornado import web, httpserver _http_server = None _https_server = None _html_root = './' _log = None _magic = None class DefaultHandler(tornado.web.RequestHandler): def get(self, match): _log.info("incoming request: {}".format(self.reque...
Python
0
d3f03d6e2cf48929f8233e52720b07242ccd64da
Put tweets back
web.py
web.py
""" Heroku/Python Quickstart: https://blog.heroku.com/archives/2011/9/28/python_and_django""" import os import random import requests from flask import Flask import tweepy import settings app = Flask(__name__) @app.route('/') def home_page(): return 'Hello from the SPARK learn-a-thon!' def get_instagram_im...
""" Heroku/Python Quickstart: https://blog.heroku.com/archives/2011/9/28/python_and_django""" import os import random import requests from flask import Flask import tweepy import settings app = Flask(__name__) @app.route('/') def home_page(): return 'Hello from the SPARK learn-a-thon!' def get_instagram_im...
Python
0
c772951ffbe06be23ff56d0281b78d7b9eac456b
Add option to generate executable name from the current branch
pycket/entry_point.py
pycket/entry_point.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # from pycket.expand import load_json_ast_rpython, expand_to_ast, PermException from pycket.interpreter import interpret_one, ToplevelEnv, interpret_module, GlobalConfig from pycket.error import SchemeException from pycket.option_helper import parse_args, ensure_json_ast f...
#! /usr/bin/env python # -*- coding: utf-8 -*- # from pycket.expand import load_json_ast_rpython, expand_to_ast, PermException from pycket.interpreter import interpret_one, ToplevelEnv, interpret_module, GlobalConfig from pycket.error import SchemeException from pycket.option_helper import parse_args, ensure_json_ast f...
Python
0.000001
b5431978c51107ba9e6475fc489fbd6dc7110332
clean up camera class
pymba/vimba_camera.py
pymba/vimba_camera.py
from ctypes import byref, sizeof from typing import Optional from .vimba_object import VimbaObject from .vimba_exception import VimbaException from .vimba_frame import VimbaFrame from . import vimba_c class VimbaCamera(VimbaObject): """ A Vimba camera object. """ def __init__(self, id_string: str): ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from . import vimba_structure as structs from .vimba_object import VimbaObject from .vimba_exception import VimbaException from .vimba_frame import VimbaFrame from .vimba_dll import VimbaDLL from ctypes import * # camera features are automatically readable...
Python
0
17fe4613518def551e637764e644c5d58b1665d9
Add BodeAnalyser instrument to instrument table
pymoku/instruments.py
pymoku/instruments.py
import sys from . import _instrument from . import _oscilloscope from . import _waveform_generator from . import _phasemeter from . import _specan from . import _lockinamp from . import _datalogger from . import _bodeanalyser from . import _stream_instrument from . import _frame_instrument from . import _input_instrum...
import sys from . import _instrument from . import _oscilloscope from . import _waveform_generator from . import _phasemeter from . import _specan from . import _lockinamp from . import _datalogger from . import _bodeanalyser from . import _stream_instrument from . import _frame_instrument from . import _input_instrum...
Python
0
5a506ff7005f09b14faa4d6036563e0125ca00f4
Fix indent
pymystrom/__init__.py
pymystrom/__init__.py
""" Copyright (c) 2015-2017 Fabian Affolter <fabian@affolter-engineering.ch> Licensed under MIT. All rights reserved. """ import requests from . import exceptions class MyStromPlug(object): """A class for a myStrom switch.""" def __init__(self, host): """Initialize the switch.""" self.resou...
""" Copyright (c) 2015-2017 Fabian Affolter <fabian@affolter-engineering.ch> Licensed under MIT. All rights reserved. """ import requests from . import exceptions class MyStromPlug(object): """A class for a myStrom switch.""" def __init__(self, host): """Initialize the switch.""" self.resour...
Python
0.000854
c034282423d47a6530ed0bb77c54e133de72115b
add more verbose output to PushwooshClient when debut=True
pypushwoosh/client.py
pypushwoosh/client.py
import logging import requests from .base import PushwooshBaseClient log = logging.getLogger('pypushwoosh.client.log') class PushwooshClient(PushwooshBaseClient): """ Implementation of the Pushwoosh API Client. """ headers = {'User-Agent': 'PyPushwooshClient', 'Content-Type': 'appli...
import logging import requests from .base import PushwooshBaseClient log = logging.getLogger('pypushwoosh.client.log') class PushwooshClient(PushwooshBaseClient): """ Implementation of the Pushwoosh API Client. """ headers = {'User-Agent': 'PyPushwooshClient', 'Content-Type': 'appli...
Python
0.003164
b7ed71cc0b620f460a0d24eeef7891e9770fc39e
Modify & Access time in pyls.
pysh/shell/builtin.py
pysh/shell/builtin.py
import collections import csv import datetime import os import pwd import StringIO from pysh.shell.pycmd import register_pycmd from pysh.shell.pycmd import pycmd from pysh.shell.pycmd import IOType from pysh.shell.table import Table def file_to_array(f): return map(lambda line: line.rstrip('\r\n'), f.readlines()) ...
import collections import csv import os import pwd import StringIO from pysh.shell.pycmd import register_pycmd from pysh.shell.pycmd import pycmd from pysh.shell.pycmd import IOType from pysh.shell.table import Table def file_to_array(f): return map(lambda line: line.rstrip('\r\n'), f.readlines()) class Permissio...
Python
0
933e3193bbd1ceb45d33a9b2dc37f3bb80b5bc7b
fix in broadcasting code
broadcast/broadcast_service.py
broadcast/broadcast_service.py
#!/usr/bin/python #broadcast_service.py # # <<<COPYRIGHT>>> # # # # """ .. module:: broadcast_service @author: Veselin """ #------------------------------------------------------------------------------ _Debug = True _DebugLevel = 6 #------------------------------------------------------------------------------ ...
#!/usr/bin/python #broadcast_service.py # # <<<COPYRIGHT>>> # # # # """ .. module:: broadcast_service @author: Veselin """ #------------------------------------------------------------------------------ _Debug = True _DebugLevel = 6 #------------------------------------------------------------------------------ ...
Python
0.00014
f56cc7acae3c3b295febafec384bcfdf3b2dcee0
koda za python
Koda.py
Koda.py
import csv import numpy as np import matplotlib.pyplot as plt from datetime import datetime from scipy.stats import multivariate_normal as mvn from scipy.stats import beta from csv import DictReader import pandas as pa def fileReaderSmucNesrece(): fp = open("evidencanesrecnasmuciscihV1.csv", "rt", encoding=" ut...
from csv import DictReader import pandas as ps def fileReaderSmucNesrece(): fp = open("evidencanesrecnasmuciscihV1.csv", "rt", encoding=" utf -8 ") reader = DictReader(fp) return [line for line in reader] #branje SmucNes = fileReaderSmucNesrece() SmucNes = ps.DataFrame(SmucNes) # uporaba pandas prin...
Python
0.999999
dd526ef40d3eb13681dca602b82390d66363783f
fix FlipDimension for LinearDimension
src/Mod/Draft/draftguitools/gui_dimension_ops.py
src/Mod/Draft/draftguitools/gui_dimension_ops.py
# *************************************************************************** # * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> * # * (c) 2009, 2010 Ken Cline <cline@frii.com> * # * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> * # * ...
# *************************************************************************** # * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> * # * (c) 2009, 2010 Ken Cline <cline@frii.com> * # * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> * # * ...
Python
0
3b41b94b4ad7b249a2ff1040d6bf2d4759d48b14
revise task error handling (exceptions bubble up now)
ape/main.py
ape/main.py
import argparse import inspect import importlib import sys import os import traceback from ape import tasks, TaskNotFound, FeatureNotFound, EnvironmentIncomplete from featuremonkey import get_features_from_equation_file def get_task_parser(task): ''' construct an ArgumentParser for task this function retur...
import argparse import inspect import importlib import sys import os from ape import tasks, TaskNotFound, FeatureNotFound, EnvironmentIncomplete from featuremonkey import get_features_from_equation_file def get_task_parser(task): ''' construct an ArgumentParser for task this function returns a tuple (parse...
Python
0
17474a74a8c382c1cc5923c0e2128e4a4e776553
Add method I am yet to use
eva/util/nutil.py
eva/util/nutil.py
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): return (generate(size=arr.shape) < arr).astype('i') def quantisize(arr, levels): return (np.digitize(arr, np.arange(levels) / levels) - 1).astype('i')
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): return (generate(size=arr.shape) < arr).astype('i')
Python
0
57773e149ae2c7634e262b103a10cc35f6e138b2
Ids are strings.
src/scim/schema/core.py
src/scim/schema/core.py
# -*- coding: utf-8 -*- from . import attributes, types class Metadata(attributes.Base): """A complex attribute containing resource metadata. """ #! The DateTime the Resource was added to the Service Provider. created = attributes.Singular(types.DateTime) #! The most recent DateTime the details ...
# -*- coding: utf-8 -*- from . import attributes, types class Metadata(attributes.Base): """A complex attribute containing resource metadata. """ #! The DateTime the Resource was added to the Service Provider. created = attributes.Singular(types.DateTime) #! The most recent DateTime the details ...
Python
0.999944
fb2cfe4759fb98de644932af17a247428b2cc0f5
Fix Auth API key check causing error 500s
api/auth.py
api/auth.py
from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from api.models import AuthAPIKey class APIKeyAuthentication(object): def is_authenticated(self, request): params = {} for key,value in request.GET.items(): params[key.lower()] = value ...
from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from api.models import AuthAPIKey class APIKeyAuthentication(object): def is_authenticated(self, request): params = {} for key,value in request.GET.items(): params[key.lower()] = value ...
Python
0
1d67f755ea0f638c3cabef9e9359665d5b50ff86
Clean up BeamConstellation
cactusbot/services/beam/constellation.py
cactusbot/services/beam/constellation.py
"""Interact with Beam Constellation.""" import re import json from .. import WebSocket class BeamConstellation(WebSocket): """Interact with Beam Constellation.""" URL = "wss://constellation.beam.pro" RESPONSE_EXPR = re.compile(r'^(\d+)(.+)?$') INTERFACE_EXPR = re.compile(r'^([a-z]+):\d+:([a-z]+)')...
"""Interact with Beam Constellation.""" from logging import getLogger import re import json import asyncio from .. import WebSocket class BeamConstellation(WebSocket): """Interact with Beam Constellation.""" URL = "wss://constellation.beam.pro" RESPONSE_EXPR = re.compile(r'^(\d+)(.+)?$') INTERFA...
Python
0.000041
948dadbd4aa262c86e561c56e7cd7748cdefa18b
Extend teacher column for institute courses
data_center/models.py
data_center/models.py
# -*- coding: utf-8 -*- from datetime import datetime from django.db import models class Course(models.Model): """Course database schema""" no = models.CharField(max_length=20, blank=True) code = models.CharField(max_length=20, blank=True) eng_title = models.CharField(max_length=200, blank=True) ...
# -*- coding: utf-8 -*- from datetime import datetime from django.db import models class Course(models.Model): """Course database schema""" no = models.CharField(max_length=20, blank=True) code = models.CharField(max_length=20, blank=True) eng_title = models.CharField(max_length=200, blank=True) ...
Python
0
1e3ea59bb631bb78dd0525dcf92a96a6a39053d8
fix hooks may not been assignment #148
py12306/helpers/request.py
py12306/helpers/request.py
import requests from requests.exceptions import * from py12306.helpers.func import * from requests_html import HTMLSession, HTMLResponse requests.packages.urllib3.disable_warnings() class Request(HTMLSession): """ 请求处理类 """ # session = {} def save_to_file(self, url, path): response = se...
import requests from requests.exceptions import * from py12306.helpers.func import * from requests_html import HTMLSession, HTMLResponse requests.packages.urllib3.disable_warnings() class Request(HTMLSession): """ 请求处理类 """ # session = {} def save_to_file(self, url, path): response = se...
Python
0
89aa3cbc62a947b3623380f7d1fe631bdf070b98
fix the need of admin to run
homeassistant/components/influxdb.py
homeassistant/components/influxdb.py
""" homeassistant.components.influxdb ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InfluxDB component which allows you to send data to an Influx database. For more details about this component, please refer to the documentation at https://home-assistant.io/components/influxdb/ """ import logging import homeassistant.util as util...
""" homeassistant.components.influxdb ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InfluxDB component which allows you to send data to an Influx database. For more details about this component, please refer to the documentation at https://home-assistant.io/components/influxdb/ """ import logging import homeassistant.util as util...
Python
0
f0243e8ab8897d218bcf45af91a7cd03a3f83c5e
Add section comments.
cloudkitpy/container.py
cloudkitpy/container.py
# # container.py # CloudKitPy # # Created by James Barrow on 28/04/2016. # Copyright (c) 2013-2016 Pig on a Hill Productions. All rights reserved. # # !/usr/bin/env python class Container: # Getting the Public and Private Databases public_cloud_database = None private_cloud_database = None # Getti...
# # container.py # CloudKitPy # # Created by James Barrow on 28/04/2016. # Copyright (c) 2013-2016 Pig on a Hill Productions. All rights reserved. # # !/usr/bin/env python class Container: public_cloud_database = None private_cloud_database = None container_identifier = None environment = None a...
Python
0
9274ec308974b0d6702e7f98a0b8a2c3be1cbe11
FIX #170 Throw Python34 compatible exception
autosklearn/util/dependencies.py
autosklearn/util/dependencies.py
from warnings import warn import pkg_resources import re from distutils.version import LooseVersion RE_PATTERN = re.compile('^(?P<name>[\w\-]+)((?P<operation>==|>=|>)(?P<version>(\d+\.)?(\d+\.)?(\d+)))?$') def verify_packages(packages): if not packages: return if isinstance(packages, str): ...
from warnings import warn import pkg_resources import re from distutils.version import LooseVersion RE_PATTERN = re.compile('^(?P<name>[\w\-]+)((?P<operation>==|>=|>)(?P<version>(\d+\.)?(\d+\.)?(\d+)))?$') def verify_packages(packages): if not packages: return if isinstance(packages, str): ...
Python
0
07e767f9c19ece3c41e33cca24dd2b0317244292
Update the latest version
src/site/sphinx/conf.py
src/site/sphinx/conf.py
# -*- coding: utf-8 -*- import sys, os, re import xml.etree.ElementTree as etree from datetime import date from collections import defaultdict def etree_to_dict(t): t.tag = re.sub(r'\{[^\}]*\}', '', t.tag) d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(li...
# -*- coding: utf-8 -*- import sys, os, re import xml.etree.ElementTree as etree from datetime import date from collections import defaultdict def etree_to_dict(t): t.tag = re.sub(r'\{[^\}]*\}', '', t.tag) d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(li...
Python
0
7965ce3036f98a9b880f19f688e7e282644e63cf
remove server_name
app/main.py
app/main.py
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def show_about(): return render_template('aboutme.html') if __name__ == '__main__': app.run()
from flask import Flask, render_template app = Flask(__name__) app.config['DEBUG'] = True app.config['SERVER_NAME'] = "vcaen.com" @app.route('/') def show_about(): return render_template('aboutme.html') if __name__ == '__main__': app.run()
Python
0.000008
a1d9312e1ac6f66aaf558652d890ac2a6bd67e40
Add parent so we can track versions.
backend/loader/model/datafile.py
backend/loader/model/datafile.py
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self....
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self....
Python
0
424b50960e7ca42c61ccc98864f9876e9688dcd4
remove empty elements
example/models.py
example/models.py
from django.db import models class Cake(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Meta: verbose_name = 'Cake' verbose_name_plural = 'Cakes' def __unicode__(self): return unicode('{}'.format(self.name)) def get_summary_d...
from django.db import models class Cake(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Meta: verbose_name = 'Cake' verbose_name_plural = 'Cakes' def __unicode__(self): return unicode('{}'.format(self.name)) def get_summary_d...
Python
0.319064
bcc7692e14b7b695f08dfb39aaccf3dbfa67d857
Add safeGetInt to BMConfigParser
src/configparser.py
src/configparser.py
import ConfigParser from singleton import Singleton @Singleton class BMConfigParser(ConfigParser.SafeConfigParser): def set(self, section, option, value=None): if self._optcre is self.OPTCRE or value: if not isinstance(value, basestring): raise TypeError("option values must be...
import ConfigParser from singleton import Singleton @Singleton class BMConfigParser(ConfigParser.SafeConfigParser): def set(self, section, option, value=None): if self._optcre is self.OPTCRE or value: if not isinstance(value, basestring): raise TypeError("option values must be...
Python
0.000001
5bce4bb123a086dd116abbd0932d34fa170a83cd
Update view to point to corrected template path
search/views.py
search/views.py
# GNU MediaGoblin -- federated, autonomous media hosting # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either versio...
# GNU MediaGoblin -- federated, autonomous media hosting # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either versio...
Python
0
d77777c2a011e77b284748d1dfbd3cd31e6c8565
make verifier regexing more robust
c_test_environment/verifier.py
c_test_environment/verifier.py
import re import sys def verify(testout, expected, ordered): numpat = re.compile(r'(\d+)') tuplepat = re.compile(r'Materialized') test = ({}, []) expect = ({}, []) def addTuple(tc, t): if ordered: tcl = tc[1] tcl.append(t) else: tcs = tc[0] ...
import re import sys def verify(testout, expected, ordered): test = ({}, []) expect = ({}, []) def addTuple(tc, t): if ordered: tcl = tc[1] tcl.append(t) else: tcs = tc[0] if t not in tcs: tcs[t] = 1 else: ...
Python
0.000004
82641a936b2215480e29896cdafed3872c2928c6
Remove xfails for newly passing tests in test_recipe_integration.py
test/test_recipes_integration.py
test/test_recipes_integration.py
import pytest import os import subprocess import json # Each test with recipe and appropriate parameters in one line # Using bracket annotation to set it optional (xfail) TEST_CASES = [ "activedata_usage", "backout_rate", ["code_coverage --path caps --rev 45715ece25fc"], "code_coverage_by_suite --path ...
import pytest import os import subprocess import json # Each test with recipe and appropriate parameters in one line # Using bracket annotation to set it optional (xfail) TEST_CASES = [ "activedata_usage", ["backout_rate"], ["code_coverage --path caps --rev 45715ece25fc"], "code_coverage_by_suite --pat...
Python
0.000004
4be67b6f46c5f4a7f8a2b89199cff2373dcc7a43
Fix casing
ca_qc_trois_rivieres/people.py
ca_qc_trois_rivieres/people.py
# coding: utf-8 from utils import CanadianScraper, CanadianPerson as Person import re COUNCIL_PAGE = 'http://www.v3r.net/a-propos-de-la-ville/vie-democratique/conseil-municipal/conseillers-municipaux' MAYOR_URL = 'http://www.v3r.net/a-propos-de-la-ville/vie-democratique/mairie' class TroisRivieresPersonScraper(Can...
# coding: utf-8 from utils import CanadianScraper, CanadianPerson as Person import re COUNCIL_PAGE = 'http://www.v3r.net/a-propos-de-la-ville/vie-democratique/conseil-municipal/conseillers-municipaux' MAYOR_URL = 'http://www.v3r.net/a-propos-de-la-ville/vie-democratique/mairie' class TroisRivieresPersonScraper(Can...
Python
0.000006
5ecab61cd66b821d70e73006f60d8f7908bfb403
Remove comment
capstone/mdp/fixed_game_mdp.py
capstone/mdp/fixed_game_mdp.py
from .mdp import MDP from .game_mdp import GameMDP from ..utils import utility class FixedGameMDP(GameMDP): def __init__(self, game, opp_player, opp_idx): ''' opp_player: the opponent player opp_idx: the idx of the opponent player in the game ''' self._game = game ...
from .mdp import MDP from .game_mdp import GameMDP from ..utils import utility class FixedGameMDP(GameMDP): def __init__(self, game, opp_player, opp_idx): ''' opp_player: the opponent player opp_idx: the idx of the opponent player in the game ''' self._game = game ...
Python
0
b8c3ad8c9eb4cdf2618839b425b8413181a443ff
Fix bug in writePrecisePathToSnapshot not bactracking prperly to the initial structure
AdaptivePELE/analysis/writePrecisePathToSnapshot.py
AdaptivePELE/analysis/writePrecisePathToSnapshot.py
""" Recreate the trajectory fragments to the led to the discovery of a snapshot, specified by the tuple (epoch, trajectory, snapshot) and write as a pdb file """ import os import sys import argparse import glob import itertools from AdaptivePELE.utilities import utilities def parseArguments(): """ ...
""" Recreate the trajectory fragments to the led to the discovery of a snapshot, specified by the tuple (epoch, trajectory, snapshot) and write as a pdb file """ import os import sys import argparse import glob import itertools from AdaptivePELE.utilities import utilities def parseArguments(): """ ...
Python
0
1549510fd9371818cff6644984896a5a9060cb36
Fix print statements with python3 syntax.
benchmarks/TSP/compare_to_BKS.py
benchmarks/TSP/compare_to_BKS.py
# -*- coding: utf-8 -*- import json, sys, os import numpy as np # Compare a set of computed solutions to best known solutions on the # same problems. def s_round(v, d): if d == 0: return str(int(v)) else: return str(round(v, d)) def log_comparisons(BKS, files): print(','.join(["Instance", "Jobs", "Vehi...
# -*- coding: utf-8 -*- import json, sys, os import numpy as np # Compare a set of computed solutions to best known solutions on the # same problems. def s_round(v, d): if d == 0: return str(int(v)) else: return str(round(v, d)) def log_comparisons(BKS, files): print ','.join(["Instance", "Jobs", "Vehi...
Python
0.000038
63bd0d8905ea9392e56f501381c054ba3a4ed1a7
Update __init__.py
chainer/optimizers/__init__.py
chainer/optimizers/__init__.py
-# import classes and functions from chainer.optimizers.ada_delta import AdaDelta # NOQA from chainer.optimizers.ada_grad import AdaGrad # NOQA from chainer.optimizers.adam import Adam # NOQA from chainer.optimizers.momentum_sgd import MomentumSGD # NOQA from chainer.optimizers.msvag import MSVAG # NOQA from chain...
from chainer.optimizers.ada_delta import AdaDelta # NOQA from chainer.optimizers.ada_grad import AdaGrad # NOQA from chainer.optimizers.adam import Adam # NOQA from chainer.optimizers.momentum_sgd import MomentumSGD # NOQA from chainer.optimizers.msvag import MSVAG # NOQA from chainer.optimizers.nesterov_ag import...
Python
0.000072
7a7661bd03c947212ee46ca598cae5cd316757c1
Fix flake8
chainercv/datasets/__init__.py
chainercv/datasets/__init__.py
from chainercv.datasets.camvid.camvid_dataset import camvid_ignore_label_color # NOQA from chainercv.datasets.camvid.camvid_dataset import camvid_label_colors # NOQA from chainercv.datasets.camvid.camvid_dataset import camvid_label_names # NOQA from chainercv.datasets.camvid.camvid_dataset import CamVidDataset # NO...
from chainercv.datasets.camvid.camvid_dataset import camvid_ignore_label_color # NOQA from chainercv.datasets.camvid.camvid_dataset import camvid_label_colors # NOQA from chainercv.datasets.camvid.camvid_dataset import camvid_label_names # NOQA from chainercv.datasets.camvid.camvid_dataset import CamVidDataset # NO...
Python
0
b27398e4dd246d542c0a82ecc35da60911edc9fd
revert to dev version
regionmask/version.py
regionmask/version.py
version = "0.7.0+dev"
version = "0.7.0"
Python
0
b318ced455f13477743a6d2d81b3556695b27374
Make to_factorized_noisy support args
chainerrl/links/noisy_chain.py
chainerrl/links/noisy_chain.py
import chainer from chainer.links import Linear from chainerrl.links.noisy_linear import FactorizedNoisyLinear def to_factorized_noisy(link, *args, **kwargs): """Add noisiness to components of given link Currently this function supports L.Linear (with and without bias) """ def func_to_factorized_no...
import chainer from chainer.links import Linear from chainerrl.links.noisy_linear import FactorizedNoisyLinear def to_factorized_noisy(link): """Add noisiness to components of given link Currently this function supports L.Linear (with and without bias) """ _map_links(_func_to_factorized_noisy, link)...
Python
0.000001
af9006169d6f537d26f58926873334312bd6ed99
Add simple bounded cache decorator
pykit/utils/convenience.py
pykit/utils/convenience.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import try: import __builtin__ as builtins except ImportError: import builtins import string import functools import collections from itertools import chain map = lambda *args: list(builtins.map(*args)) invert = lambda d: di...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import try: import __builtin__ as builtins except ImportError: import builtins import string import functools import collections from itertools import chain map = lambda *args: list(builtins.map(*args)) invert = lambda d: di...
Python
0
a5da284b70e3e04a919679475e9cf2e276430077
Fix "--attribution" option (doesn't need an argument)
renderchan/manager.py
renderchan/manager.py
__author__ = 'Konstantin Dmitriev' from gettext import gettext as _ from optparse import OptionParser import os.path from renderchan.core import RenderChan from renderchan.core import Attribution from renderchan.file import RenderChanFile from renderchan.project import RenderChanProject def process_args(): pars...
__author__ = 'Konstantin Dmitriev' from gettext import gettext as _ from optparse import OptionParser import os.path from renderchan.core import RenderChan from renderchan.core import Attribution from renderchan.file import RenderChanFile from renderchan.project import RenderChanProject def process_args(): pars...
Python
0.001461
629d8a699e0ab944d4775bd6a31709546d4ca839
add doc string
contacts/models/misc.py
contacts/models/misc.py
#!/usr/bin/python #Django Imports from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from jsonfield import JSONField #Local Imports import transports from utils.models import TimeStampedModel,BaseQuerySet cla...
#!/usr/bin/python #Django Imports from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from jsonfield import JSONField #Local Imports import transports from utils.models import TimeStampedModel,BaseQuerySet cla...
Python
0.000002
6535755cfdc914efc5e1efc6a89ed9dca7c78b87
Correct docstrings of result_suite/sample.py
checker/result_suite/sample.py
checker/result_suite/sample.py
from checker.base import BakeryTestCase as TestCase class SampleTest(TestCase): target = 'result' path = '.' def setUp(self): # read ttf # self.font = fontforge.open(self.path) pass def test_ok(self): """ This test succeeds """ self.assertTrue(True) def t...
from checker.base import BakeryTestCase as TestCase class SampleTest(TestCase): target = 'result' path = '.' def setUp(self): # read ttf # self.font = fontforge.open(self.path) pass def test_ok(self): """ This test failed """ self.assertTrue(True) def tes...
Python
0.000002
0df292fbb34a66ee66fce919ea63b68a5f9eff1a
Set up data structures for parsing projects
app/data.py
app/data.py
import json import os from typing import Dict, List from app.util import cached_function class Projects(): def __init__(self) -> None: self.languages: List[Language] = [] @staticmethod def load_from_file() -> 'Projects': current_directory = os.path.dirname(os.path.realpath(__file__)) ...
import json import os from typing import Dict, List from app.util import cached_function class Projects(): def __init__(self) -> None: self.data: Dict[str, Dict[str, Dict[str, str]]] = {} @staticmethod def load() -> 'Projects': current_directory = os.path.dirname(os.path.realpath(__file_...
Python
0.000003
75a93ae0e55e240a5f8595c0d58d15b1d846948a
Add support for spectate after starting the game
chillin_server/gui/protocol.py
chillin_server/gui/protocol.py
# -*- coding: utf-8 -*- # python imports from threading import Thread, Lock, Event import sys if sys.version_info > (3,): from queue import Queue else: from Queue import Queue # project imports from ..config import Config from .network import Network from .parser import Parser from .messages import Auth cl...
# -*- coding: utf-8 -*- # python imports from threading import Thread, Lock, Event import sys if sys.version_info > (3,): from queue import Queue else: from Queue import Queue # project imports from ..config import Config from .network import Network from .parser import Parser from .messages import Auth cl...
Python
0