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 |
|---|---|---|---|---|---|---|---|
3020472569a49f01331ebb150f004e2684196b8e | add expression to improve the domain | bin/tools/expression.py | bin/tools/expression.py | #!/usr/bin/env python
def _is_operator( element ):
return isinstance( element, str ) and element in ['&','|']
def _is_leaf( element ):
return isinstance( element, tuple ) and len( element ) == 3 and element[1] in ['=', '<>', '!=', '<=', '<', '>', '>=', 'like', 'not like', 'ilike', 'not ilike']
def _is_expre... | Python | 0.000012 | |
0226bec54c30a31c0005e7318b69c58a379cfbc9 | refactor output function | mystarspilot/view.py | mystarspilot/view.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from colorama import Fore, Back, Style
class SearchResultView(object):
def print_search_result(self, search_result, keywords=None):
if search_result is not None:
fo... | Python | 0.998671 | |
245e661c50df41942ca3f0c8ee794532e3c02c4c | Translate PowerShell sample NCM.ExecuteScript.ps1 to python | samples/ncm_execute_script.py | samples/ncm_execute_script.py | from __future__ import print_function
import re
import requests
from orionsdk import SwisClient
from time import sleep
def main():
npm_server = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(npm_server, username, password)
ip = '10.199.252.6'
data = swis.query('SELECT NodeID FROM Cirrus.Nodes ... | Python | 0.999999 | |
7e91549abc8d185deb231c937d7740606f9454ec | add pmi element unit test | test_pmi_element.py | test_pmi_element.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# The unit test case for pmi.TopkHeap and PMIElement
#
# @author: Jason Wu (Jasonwbw@yahoo.com)
from pmi import PMIElement
import sys
import unittest
class PMIElementTestCase(unittest.TestCase):
def setUp(self):
pass
def tearGt(self):
... | Python | 0 | |
3c52683e759f146ad247c6e397d5d49dd1cc9966 | Create __init__.py | testing/__init__.py | testing/__init__.py | Python | 0.000429 | ||
a770c91ea6761d890387b4b6e130cb495817eea0 | Improve the sc2parse debugging script. | sc2reader/scripts/sc2parse.py | sc2reader/scripts/sc2parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import sc2reader
import traceback
def main():
for argument in sys.argv[1:]:
for path in sc2reader.utils.get_files(argument):
try:
replay = sc2reader.load_replay(path, debug=True)
except sc2reader.exceptions.ReadError as e:
print e.replay.filena... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import sc2reader
def main():
for replay in sc2reader.load_replays(sys.argv[1:], verbose=True):
pass
if __name__ == '__main__':
main() | Python | 0 |
98295608a2ba4519d12212532380253bba4372ed | Add script that recommends scrape task schedule based on recent run timings | scripts/frequency_analysis.py | scripts/frequency_analysis.py | import asyncio
import attr
import pprint
import dateutil.parser
from datetime import timedelta
from bobsled.core import bobsled
from bobsled.base import Status
def recommend_frequency_for_task(runs):
total_duration = timedelta(seconds=0)
longest_duration = timedelta(seconds=0)
for run in runs:
sta... | Python | 0 | |
dd22ea800dbbeffaace1927804d50da60ee77a30 | Fix TestPages.test_homepage_with_anonymous_giver. | tests/test_pages.py | tests/test_pages.py | from __future__ import print_function, unicode_literals
import datetime
from mock import patch
import pytz
from gittip.elsewhere.twitter import TwitterAccount
from gittip.testing import GITHUB_USER_UNREGISTERED_LGTEST, Harness
from gittip.testing.client import TestClient
from gittip.utils import update_homepage_quer... | from __future__ import print_function, unicode_literals
import datetime
from mock import patch
import pytz
from gittip.elsewhere.twitter import TwitterAccount
from gittip.testing import GITHUB_USER_UNREGISTERED_LGTEST, Harness
from gittip.testing.client import TestClient
from gittip.utils import update_homepage_quer... | Python | 0 |
e6642dd9c9cad6aca3cb70e4cca53afe51494d4b | Add a test for checking setup.py | tests/test_setup.py | tests/test_setup.py | r""" Testspectra_gen functions"""
def test_setup():
import os
cmd = "python3 setup.py check"
os.system(cmd) | Python | 0.000002 | |
0424eb7dd8e55e2f88f088c3a84c8e962d89f06e | build perf from source | tools/perf_build.py | tools/perf_build.py | #!/usr/bin/env python
import platform
import subprocess
if subprocess.call('which sudo', shell=True) == 0:
with_sudo = 'sudo '
else:
with_sudo = ''
major = int(platform.release().split('.')[0])
minor = int(platform.release().split('.')[1])
revision = int(platform.release().split('.')[2].split('-')[0])
url_k... | Python | 0 | |
ef3e07794d4245b9d4a1d0007a0b9099d5bafaf9 | Add asteval wrapper | project/asteval_wrapper.py | project/asteval_wrapper.py | from asteval import Interpreter
import functools
import re
class Script(object):
def __init__(self):
"""
Sets up an interpreter.
"""
self.interpreter = Interpreter()
self.symtable['re'] = re
@property
def symtable(self):
"""
Expose the internal sym... | Python | 0.000001 | |
126863fd6c2a13491b92d546d3e886d0e0da492b | Add experiment for nodejs. | swig/node/binding.gyp | swig/node/binding.gyp | {
"targets": [
{
"target_name": "velocypack",
"sources": [ "../../src/asm-functions.cpp",
"../../src/AttributeTranslator.cpp",
"../../src/Builder.cpp",
"../../src/Collection.cpp",
"../../src/Dumper.cpp",
".... | Python | 0 | |
ad0a1bf70dc2776c88115389400fd6958e49ecc8 | Add rsync package | var/spack/packages/rsync/package.py | var/spack/packages/rsync/package.py | from spack import *
class Rsync(Package):
"""rsync is an open source utility that provides fast incremental file transfer."""
homepage = "https://rsync.samba.org"
url = "https://download.samba.org/pub/rsync/rsync-3.1.1.tar.gz"
version('3.1.1', '43bd6676f0b404326eee2d63be3cdcfe')
# depends_on... | Python | 0.000001 | |
5869091cc63afbe9c8bde2bf6e9f934c46d3c3f5 | Create generate_api_error.py | vnpy/api/tap/generator/generate_api_error.py | vnpy/api/tap/generator/generate_api_error.py | """"""
class DataTypeGenerator:
"""DataType生成器"""
def __init__(self, filename: str, prefix: str, name: str) -> None:
"""Constructor"""
self.filename: str = filename
self.prefix: str = prefix
self.name: str = name
def run(self) -> None:
"""主函数"""
self.f_cpp... | Python | 0.000126 | |
d205284e21f5fad8195d796ad356042cb5c47894 | add log test | py_logging/test_logging.py | py_logging/test_logging.py | #!/usr/bin/env python
# encoding: utf-8
import logging
import os
import time
from unittest import TestCase
class TestLogging(TestCase):
def setUp(self):
dir_path = os.path.dirname(__file__)
self.logfile = os.path.join(dir_path, "tmp.log")
self.logger = logging.getLogger(
"test... | Python | 0.000001 | |
9b2e0396f1121f94d6b66daa26c83bb85bc1a79a | format string tests | pychecker2/utest/format.py | pychecker2/utest/format.py | from pychecker2 import TestSupport
from pychecker2 import FormatStringChecks
class FormatTestCase(TestSupport.WarningTester):
def testGoodFormats(self):
self.silent('def f(x):\n'
' return "%s" % x\n')
self.silent('def f(x):\n'
" return ('%s' + '%s') %... | Python | 0.000005 | |
2e2bae00f7b098e5fd20f2901b4f70554e250d2d | add program to plot offset distribution | python/plot_offset_dist.py | python/plot_offset_dist.py | #!/usr/bin/env python
import argparse
import numpy as np
import glob
import matplotlib as mpl
mpl.use('Agg')
mpl.rcParams.update({'font.size': 10})
import matplotlib.pyplot as plt
def add_stat_legend(x):
textstr = '$\mathrm{N}=%d$\n$\mathrm{mean}=%.2f$\n$\mathrm{median}=%.2f$\n$\mathrm{std}=%.2f$' % (
l... | Python | 0 | |
091432b795e3b5571887eb924fb831060d2fd53b | Add logging setup | turbinia/config/logger.py | turbinia/config/logger.py | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Python | 0.000001 | |
99866bc8e47e1457bb12730e0190d6690ad024e2 | Create pj_cpp_petlje.py | pj_cpp_petlje.py | pj_cpp_petlje.py | from pj import *
class CPP(enum.Enum):
FOR = 'for'
COUT = 'cout'
ENDL = 'endl'
OOTV, OZATV, VOTV, VZATV = '(){}'
MANJE, JEDNAKO, TOČKAZ = '<=;'
PLUSP = '++'
PLUSJ = '+='
IZLAZ = '<<'
BROJ = 34545
IME = 'varijabla'
def cpp_lex(source):
lex = Tokenizer(source)
for znak i... | Python | 0.000125 | |
f9998701bafa24fce25156751fefdfa97074c801 | Add protocol conformance map | utils/gyb_syntax_support/protocolsMap.py | utils/gyb_syntax_support/protocolsMap.py | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAs... | Python | 0 | |
143eb4665e76065ec67b5dd42cfe84e238d50094 | use per post winner count if available to overide settings | candidates/constants.py | candidates/constants.py | ELECTION_ID_REGEX = r'(?P<election>[^/]+)'
POST_ID_REGEX = r'(?P<post_id>[^/]+)'
| Python | 0 | |
6aef9ab419b09822b2255141349144ac8978e862 | Add migration for h5p kind. | kolibri/core/content/migrations/0025_add_h5p_kind.py | kolibri/core/content/migrations/0025_add_h5p_kind.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-12-19 02:29
from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
("content", "0024_channelmetadata_public"),
]
operations = [
... | Python | 0 | |
39b00572d7888895bcf552999f80b712c1738142 | Create BillboardIter.py | BillboardIter.py | BillboardIter.py | from datetime import date, timedelta
class BillboardDates():
'''Iterator over valid Billboard Chart weeks, which is
supposed to be a per-class singleton for start quantization'''
def __init__(self, endDate=date.today()):
assert type(endDate) is str or type(endDate) is date
self.endDate =... | Python | 0 | |
566850c873f6bdbed6632388330f8e4df6fbe613 | add migration for accordeon block on homepage | meinberlin/apps/cms/migrations/0021_add_accordeon_block.py | meinberlin/apps/cms/migrations/0021_add_accordeon_block.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-08 12:57
from __future__ import unicode_literals
from django.db import migrations
import meinberlin.apps.cms.blocks
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailimages.blocks
class Migration(migrations.Migra... | Python | 0 | |
ecfadf8478b8775d8579812a7bd835f6ebb1ffd4 | Add file lister for rclone export | util/rclone-list-files.py | util/rclone-list-files.py | #!/usr/bin/env python3
import glob
# For use with --files-from argument for Rclone
# This suits Edgar's structure with is
# SPECIESNAME/{occurrences|projected-distributions}/[2nd-to-latest-file-is-the-latest].zip
for folder in glob.glob('*'):
occurrences = glob.glob(folder + '/occurrences/*')
projected_distrib... | Python | 0 | |
47e3a59dd05f30f1ce0c41e0aa531987fb33606c | Generate watersheds for new EM dataset | new-em-watersheds.py | new-em-watersheds.py | from gala import morpho
from gala import imio
import numpy as np
pr = imio.read_image_stack('membrane/*.tiff')
ws = morpho.watershed_sequence(pr / pr.max(), axis=0, connectivity=2, smooth_thresh=0.02, minimum_seed_size=2)
imio.write_h5_stack(ws, 'watershed.lzf.h5', compression='lzf')
slices = [(slice(None), slice(None,... | Python | 0.999865 | |
629bd006bfd7e6210dcc95198be9b65614e4f051 | Convert optimization_test.py to PyTorch | optimization_test_pytorch.py | optimization_test_pytorch.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... | Python | 0.999999 | |
101bb07375d2a36a65d07d3de32625cdef8f916d | Add parser for Vietnamese edition. | parser/parse_vi.py | parser/parse_vi.py | import re
from bs4 import BeautifulSoup, Tag
import requests
tested_url = [
"https://vi.wiktionary.org/wiki/kh%C3%B4ng#Ti.E1.BA.BFng_Vi.E1.BB.87t",
"https://vi.wiktionary.org/wiki/c%C3%A1m_%C6%A1n#Ti.E1.BA.BFng_Vi.E1.BB.87t",
]
HEADING_TAG = re.compile(r'^h(?P<level>[1-6])$', re.I)
COMMA_OR_SEMICOLON = re.co... | Python | 0 | |
7da53597f9cb4117cecbaed1dbb77f4693289815 | add a test for well locations endpoint | app/backend/wells/tests/test_wells.py | app/backend/wells/tests/test_wells.py | """
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 writing, software
distri... | Python | 0.000001 | |
32f7fe6562f4d1592dfab5a9b065154dca51f1d3 | Add rsync module | pyIsis/rsync.py | pyIsis/rsync.py | # -*- coding: utf-8 -*-
import os
import subprocess
import logging
#RSYNC_PATH = os.path.join(
# os.path.abspath (os.path.dirname(__file__)), 'bin', 'rsync')
RSYNC_PATH = '/opt/rsync/bin/rsync'
RSYNC_CMD = '{cmd} {options} "{source}" "{destination}"'
rsync_logger = logging.getLogger('avidisis')
class rsync(obj... | Python | 0.000001 | |
01eaa6ba14c51568ea7aa3cc436d14fbffb78720 | Create downloader-v0.22pa.py | downloader-v0.22pa.py | downloader-v0.22pa.py | import urllib2
import re
import os
def stahniHtml(url):
f = urllib2.urlopen(url)
obsah = f.read()
f.close()
return obsah
def nahled(url):
global chapter
global currpatch1
odkazy = vyberodkazux(url)
for odkaz in odkazy:
currpatch1 = odkaz.replace("index.html", "")
chapte... | Python | 0 | |
313d54c4dc4296dad82502ec18f28542ecc747b4 | Add growl hexchat plugin | HexChat/growl.py | HexChat/growl.py | # -*- coding: utf-8; tab-width: 4; -*-
__module_name__='Growl'
__module_description__='Growl notification support'
__module_author__='TingPing'
__module_version__='14'
import re
from time import time
import xchat
try:
import gntp.notifier
except ImportError:
xchat.prnt('Growl Error: Please install https://github.... | Python | 0 | |
d6b01b968b2ef97042bc7c3dfc1f1752fcbc98a4 | Create nnet3_compute_bnf.py | nnet3_compute_bnf.py | nnet3_compute_bnf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 5 16:49:55 2017
@author: Omid Sadjadi <s.omid.sadjadi@gmail.com>
"""
import numpy as np
import nnet3read
def splice_feats(x, w=9):
""" This routine splices the feature vectors in x by stacking over a window
of length w frames (must be... | Python | 0.00002 | |
49712dd43a2376c913e66cac7b52fc7247912e44 | Make disable_builtins schema a property | flexget/plugins/operate/disable_builtins.py | flexget/plugins/operate/disable_builtins.py | from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.plugin import priority, register_plugin, plugins
log = logging.getLogger('builtins')
def all_builtins():
"""Helper function to return an iterator over all builtin plugins."""
return (plug... | from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.plugin import priority, register_plugin, plugins
log = logging.getLogger('builtins')
def all_builtins():
"""Helper function to return an iterator over all builtin plugins."""
return (plug... | Python | 0.000003 |
e2b4d3849db7b51f81d1770ebcce2b9af7d098e6 | add tests for Mixpanel | test/test_mixpanel.py | test/test_mixpanel.py | import base64
import json
import unittest
from libsaas.executors import test_executor
from libsaas.services import mixpanel
class MixpanelTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
self.executor.set_response(b'1', 200, {})
self.service = mixpanel.M... | Python | 0 | |
790be842b1c2e752210d5328dad05acb05d337bb | add minimal test for serial.theaded | test/test_threaded.py | test/test_threaded.py | #!/usr/bin/env python
#
# This file is part of pySerial - Cross platform serial port support for Python
# (C) 2016 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
"""\
Test serial.threaded related functionality.
"""
import os
import unittest
import serial
import serial.threaded
import tim... | Python | 0.000015 | |
70683aabe3cebda02db62fc254b7ec7532a50618 | Add test_config.sample.py. | test_config.sample.py | test_config.sample.py | CREDENTIAL_FILE = ''
SHEET_NAME = ''
| Python | 0 | |
499adce8b5c23d60073d4c92259e611609ee0c61 | Add initial draft script to analyse Maven deps | states/common/maven/artifacts/check_dependencies.py | states/common/maven/artifacts/check_dependencies.py | #!/usr/bin/env python
import subprocess as sub
import yaml
import re
distrib_pom_path = '/home/uvsmtid/Works/maritime-singapore.git/clearsea-distribution/pom.xml'
# Resolve (download) all dependencies locally so that next command
# can work offline.
sub.check_call(
[
'mvn',
'-f',
distrib_... | Python | 0 | |
1a065a251c3337ae7741af1916c51f2edcb9180f | add db.py | www/transwarp/db.py | www/transwarp/db.py | #/usr/bin/python
#_*_ coding:utf-8 _*_
import threading
class _Engine(object):
"""
数据库引擎对象
"""
def __init__(self, connect):
self._connect = connect
def connect(self):
return self._connect()
engine = None
class _DbCtx(threading.local):
"""
持有数据库连接的上下文对象
"""
def __i... | Python | 0.000002 | |
fed635826be361c4748f13bca09ed411c59ca352 | Add test for OpenStackServer API to increase test coverage | instance/tests/api/test_openstack_server.py | instance/tests/api/test_openstack_server.py | # -*- coding: utf-8 -*-
#
# OpenCraft -- tools to aid developing and hosting free software projects
# Copyright (C) 2015-2016 OpenCraft <contact@opencraft.com>
#
# 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 Fre... | Python | 0 | |
6fd75772efac321517a1d8c01addfa5cbbf7caf0 | Add test file for user functions. | tests/db/user_test.py | tests/db/user_test.py | from okcupyd.db import user
def test_have_messaged_before(T):
message_thread_model = T.factory.message_thread()
assert user.have_messaged_by_username(
message_thread_model.initiator.handle,
message_thread_model.respondent.handle
)
assert user.have_messaged_by_username(
message_t... | Python | 0 | |
6d2480c5817a8ba7a4a810378ce8fabe0ede3cbf | check YAML examples | tests/testexamples.py | tests/testexamples.py | #!/usr/bin/python
import os
import yaml
def test_examples():
for filename in os.listdir("examples/"):
with open(os.path.join("examples", filename)) as stream:
print(yaml.load(stream))
| Python | 0.000001 | |
a9bb7c7c929b0e182160a700e0a3f23dc3e81765 | Update and rename exercises to exercises/12.py | exercises/12.py | exercises/12.py | '''
Define a procedure histogram() that takes a list of
integers and prints a histogram to the screen.
For example, histogram([4, 9, 7]) should print the following:
****
*********
*******
'''
def histogram(lst):
for item in lst:
print(item * '*')
| Python | 0.000001 | |
a0d2e58a6eecf3427646f311e638c359706e806a | Add Energenie example code | energenie.py | energenie.py | import RPi.GPIO as GPIO
from time import sleep
bit1 = 11
bit2 = 15
bit3 = 16
bit4 = 13
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(bit1, GPIO.OUT)
GPIO.setup(bit2, GPIO.OUT)
GPIO.setup(bit3, GPIO.OUT)
GPIO.setup(bit4, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.output(22, False... | Python | 0 | |
8646929a913b77438bf58e48e672ea68492d3ac1 | Mark third_party/accessibility-developer-tools as a known license info issue. | android_webview/tools/known_issues.py | android_webview/tools/known_issues.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""List of known-incompatibly-licensed directories for Android WebView.
This is not used by the webview_licenses tool itself; it is effectively a
"cache... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""List of known-incompatibly-licensed directories for Android WebView.
This is not used by the webview_licenses tool itself; it is effectively a
"cache... | Python | 0.000178 |
a5440305173c218ec785b0d5a2dfa8b02bb0b731 | Add package: py-fava (#21275) | var/spack/repos/builtin/packages/py-fava/package.py | var/spack/repos/builtin/packages/py-fava/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyFava(PythonPackage):
"""Fava is a web interface for the double-entry bookkeeping softwar... | Python | 0 | |
31342e58f914c057404fd35edfff42b95e5fb051 | Test #2 (with the current GitLab API syntax) | gitlabform/gitlabform/test/test_project_settings.py | gitlabform/gitlabform/test/test_project_settings.py | import pytest
from gitlabform.gitlabform import GitLabForm
from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, GROUP_NAME
PROJECT_NAME = 'project_settings_project'
GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME
@pytest.fixture(scope="module")
def gitlab(request):
... | Python | 0 | |
caf135f6c94146038ac9d9e77a808e30ea52f900 | make pyroma a runnable module (#62) | pyroma/__main__.py | pyroma/__main__.py | from . import main
if __name__ == "__main__":
main()
| Python | 0 | |
25a1d94b45980fbc78c162af2c81ad807ee954c9 | add test_vpr.py, add test functions and stubs | wradlib/tests/test_vpr.py | wradlib/tests/test_vpr.py | #!/usr/bin/env python
# -------------------------------------------------------------------------------
# Name: test_vpr.py
# Purpose: testing file for the wradlib.vpr module
#
# Authors: wradlib developers
#
# Created: 26.02.2016
# Copyright: (c) wradlib developers
# Licence: The MIT License
#... | Python | 0 | |
9ad3b4e6ff5ec500fe1feeb841c4fe00e9267d19 | add sh_quote.py | python/sh_quote.py | python/sh_quote.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Tristan Cavelier <t.cavelier@free.fr>
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public L... | Python | 0.000004 | |
8a836c53d85f63831e51e7aac9a2f77fdf25ef9f | Add more indexing tests. | numpy/core/tests/test_indexing.py | numpy/core/tests/test_indexing.py | from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.compat import asbytes
from numpy.testing import *
import sys, warnings
# The C implementation of fancy indexing is relatively complicated,
# and has many seeming inconsistencies. It also appears to lack any
# kind of test s... | from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.compat import asbytes
from numpy.testing import *
import sys, warnings
# The C implementation of fancy indexing is relatively complicated,
# and has many seeming inconsistencies. It also appears to lack any
# kind of test s... | Python | 0 |
2273dfcdb2f311f39e1bffe4f40cdc6e3b753155 | add buildOffsetMap.py | buildOffsetMap.py | buildOffsetMap.py | import sys, os, json
import frm
DATA_PATH = "data"
def main():
if len(sys.argv) != 2:
print "USAGE: %s IMAGES_LIST" % sys.argv[0]
sys.exit(1)
images = list(open(sys.argv[1]))
imageInfo = {}
for image in images:
image = image.rstrip()
frmPath = os.path.join(DATA_PATH, image + ".FRM")
frmInfo = frm.read... | Python | 0.000001 | |
a62b4f70816b831a16973e861449b0c76761cf52 | Create Odd_Even_Linked_List.py | data_structures/Linked_list/Python/Odd_Even_Linked_List.py | data_structures/Linked_list/Python/Odd_Even_Linked_List.py | '''
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
'''
class Solution(object):
def oddEvenList(self, head):
if head is None: return None
if head.next is None: return head
o = head
... | Python | 0 | |
dd0e335574afd936b5849186202aedc8500f2c5b | add build-front | organization/core/management/commands/build-front.py | organization/core/management/commands/build-front.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2017 Ircam
# Copyright (c) 2016-2017 Guillaume Pellerin
# Copyright (c) 2016-2017 Emilie Zawadzki
# This file is part of mezzanine-organization.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | Python | 0.000017 | |
cc2343a564572e6c0bd94279bf3907e9e85da79b | Create version.py | plotly-1.2.9/plotly/version.py | plotly-1.2.9/plotly/version.py | __version__ = '1.2.9'
| Python | 0.000001 | |
65239ce01df89ceaaed989b28f4623ac521ce2c3 | Add download_stats script | download_stats.py | download_stats.py | import argparse
from xmlrpclib import ServerProxy
import pickle
parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int)
parser.add_argument("--package-list",
action="store")
args = parser.parse_args()
url = 'https://pypi.python.org/pypi'
client = ServerProxy(url)
if not args.packag... | Python | 0 | |
2b79fd91b43248169e408093454a32367ecb6d61 | Add a solution that creates a separate LP for each frame transition. | project7/project7-lp-single.py | project7/project7-lp-single.py | from gurobipy import *
from sys import argv
import json
import math
import drawful
def read_lst(fn):
with open(fn, 'r') as f:
(n, tp) = json.load(f)
return (n, tp)
def write_lst(fn, lst):
with open(fn, 'w') as f:
json.dump(lst, f)
def distance(v1, v2):
return mat... | Python | 0 | |
95a26454173b59c8609ddb81027ed71005e9e86c | add module to handle exceptions | cno/misc/tools.py | cno/misc/tools.py | __all__ = ["CNOError"]
class CNOError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
| Python | 0.000001 | |
bb58564dc400e91c132e3a26532595ec9de73958 | Create managers.py | managers.py | managers.py | from django.db import models
class VisibilityManagerMixin(object):
"""
This manager should be used with a model that implements the Hideable
mixin.
"""
def __init__(self, *args, **kwargs):
self.visible = kwargs.pop('visible', True)
super().__init__(*args, **kwargs)
def get_qu... | Python | 0.000001 | |
fbaaf3ba027ee9d18df7b1f48533c8847f084381 | Add harmonic mean estimator. | harmonicmean.py | harmonicmean.py | import numpy.random
import numpy as np
import lib
from math import log
def compute_harmonicmean(lnlike_post, posterior_sample=None, lnlikefunc=None,
lnlikeargs=(), **kwargs):
"""
Computes the harmonic mean estimate of the marginal likelihood.
The estimation is based on n posterio... | Python | 0.000003 | |
156a31c7aef3dfc07f5e3b0998b0957308abdd16 | Create getPrice.py | src/getPrice.py | src/getPrice.py | import requests
import requests.auth
import time
import json
def getPrices():
print "Grabbing price..."
dogeprice = parsePrices("doge")
btcprice = parsePrices("btc")
ltcprice = parsePrices("ltc")
rddprice = parsePrices("rdd")
obj3 = open('price.txt', 'w')
obj3.wr... | Python | 0.000001 | |
7c0bf9e7930773a35da7303284842f74cc7b7744 | Add util script to dump flickr photo stats | myflickr.py | myflickr.py | #
# use flickrapi to dump stats about pictures in a flickr account
# use time sleep to prevent automatic flickr rejection
#
import sys
import flickrapi
import time
import sys
from basics import *
import xml.etree.ElementTree
#
# method to dump social stats about the flickr user account
# args:
# - api_se... | Python | 0 | |
082f11f5a24efd21f05b1d7cc7f1b1f1ab91fb0c | Add exercise 13: couplage | prologin-2014/13_couplage.py | prologin-2014/13_couplage.py | # http://www.prologin.org/training/challenge/demi2014/couplage
from sys import stdin
nbBowlsFirst = int(stdin.readline())
nbBowlsSecond = int(stdin.readline())
bowlsFirst = [int(x) for x in stdin.readline().split()]
bowlsSecond = [int(x) for x in stdin.readline().split()]
def maxInTwoLists(first, second):
"""Find th... | Python | 0.001185 | |
b405d9384cd9b1155177fe99cc40a8f1a53cb5f6 | Include graphing | mpi_optimizer.py | mpi_optimizer.py | """
@Author: Rui Shu
@Date: 4/11/15
Finds the global maxima of a costly function in a parallelized setting. Runs
optimizer.py in parallel with with several worker nodes that evaluates the costly
function in batch.
Run as: mpiexec -np 4 python parallel_optimizer.py
where 4 is the number of available processes
Framew... | Python | 0 | |
f8a0aa92c8e19bc11f8a609733644afe0efed5c8 | Update test script to do match testing. | decompose_test.py | decompose_test.py | from util.decompose_graph import decompose_graph
from core.himesis_utils import expand_graph, set_do_pickle, set_compression
set_do_pickle(True)
set_compression(6)
file_name = "226482067288742734644994685633991185819"
graph = expand_graph(file_name)
print(graph.name)
from core.himesis_utils import load_directory
... | Python | 0 | |
577891c76140ce50f6be450594a23d78366c5719 | Create __init__.py | pythainlp/number/__init__.py | pythainlp/number/__init__.py | # ระบบแปลงเลขใน 1- 10 ภาษาไทย
p = [['ภาษาไทย', 'ตัวเลข','เลขไทย'],
['หนึ่ง', '1', '๑'],
['สอง', '2', '๒'],
['สาม', '3', '๓'],
['สี่', '4', '๔'],
['ห้า', '5', '๕'],
['หก', '6', '๖'],
['หก', '7', '๗'],
['แปด', '8', '๘'],
['เก้า', '9', '๙']]
thaitonum = dict((x[2], x[1]) for x ... | Python | 0.000429 | |
8c98e313caeb82ee710d56399d5de7cf1eb1f7df | Add DNA Coding | python/src/dna/dna_coding.py | python/src/dna/dna_coding.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import src.mylib.mfile as mfile
from matplotlib import style
stop =int('101010', 2) #101010 I Ching 63 After Completion
befo =int('010101', 2) #101010 I Ching 64 Before Completion
guai =int('111110', 2) #101010 I Ching 43
qian =int('111111', 2) #... | Python | 0.000595 | |
1be041fd9bfc856fd59fba52501823d80d3ff037 | Create setup.py | neutron/setup.py | neutron/setup.py | Python | 0.000001 | ||
a4f030cf10683aa949550e9922c3ea72421cf392 | Update PCI configuration options | nova/conf/pci.py | nova/conf/pci.py | # needs:check_opt_group_and_type
# Copyright (c) 2013 Intel, Inc.
# Copyright (c) 2013 OpenStack Foundation
# 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
#... | # needs:check_opt_group_and_type
# Copyright (c) 2013 Intel, Inc.
# Copyright (c) 2013 OpenStack Foundation
# 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
#... | Python | 0.000002 |
08122e57235e836dbfd4230e9e3ad3f7c54072ff | add simple debug callback test case | pycurl/tests/test_debug.py | pycurl/tests/test_debug.py | # $Id$
import pycurl
def test(**args):
print args
c = pycurl.init()
c.setopt(pycurl.URL, 'http://curl.haxx.se/')
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.DEBUGFUNCTION, test)
c.perform()
c.cleanup()
| Python | 0 | |
6e42855d527976dd8b1cdb272502ce3aa76f8c6e | Add dbee abstract base class. | dbeekeeper/dbee/base.py | dbeekeeper/dbee/base.py | # Copyright 2013 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Python | 0 | |
7e96013f21bbb5003b30da1e04833dcf58650602 | Implement a ThriftHandler for tornado | freenoted/tasks/tornado_thrift.py | freenoted/tasks/tornado_thrift.py | from __future__ import absolute_import
import tornado.web
from thrift.transport.TTransport import TMemoryBuffer
from thrift.protocol.TBinaryProtocol import TBinaryProtocol
class TornadoThriftHandler(tornado.web.RequestHandler):
def initialize(self, processor):
self.processor = processor
def post... | Python | 0.000517 | |
c66e64556747736c1ee7461aa6ee8780a330481b | add sparse_to_dense_test | caffe2/python/sparse_to_dense_test.py | caffe2/python/sparse_to_dense_test.py | # Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | Python | 0.000006 | |
29e8dce6fc2956dc9f942eca41fdb632c382fe8e | Create pylsy.py | pylsy/tests/pylsy.py | pylsy/tests/pylsy.py | # -*- coding: utf-8 -*-
from __future__ import print_function
class PylsyTable(object):
def __init__(self, attributes):
self.StrTable = ""
self.Attributes = attributes
self.Table = []
self.AttributesLength = []
self.Cols_num = len(self.Attributes)
self.Lines_num =... | Python | 0.000001 | |
d60c1f9a6e56472611a96779462b42e8505e7905 | Convert a PDF document to JPEG/PNG image via /pdftoimg endpoint | python/pdf_to_img.py | python/pdf_to_img.py | import requests
import json
# Convert a PDF document to JPEG/PNG image via /pdftoimg endpoint - https://pixlab.io/cmd?id=pdftoimg
req = requests.get('https://api.pixlab.io/pdftoimg',params={
'src':'https://www.getharvest.com/downloads/Invoice_Template.pdf',
'export': 'jpeg',
'key':'My_PixLab_Key'
})
reply = req.j... | Python | 0.999999 | |
198b54c9ff796cc98cccfdc530f0111739901b0d | Create base-7.py | Python/base-7.py | Python/base-7.py | # Time: O(1)
# Space: O(1)
# Given an integer, return its base 7 string representation.
#
# Example 1:
# Input: 100
# Output: "202"
# Example 2:
# Input: -7
# Output: "-10"
# Note: The input will be in range of [-1e7, 1e7].
class Solution(object):
def convertToBase7(self, num):
if num < 0: return '-' + s... | Python | 0.000022 | |
50dc018891511ce34b4177a43cfcd678456444cf | test of quasiisothermaldf's meanvR | nose/test_qdf.py | nose/test_qdf.py | # Tests of the quasiisothermaldf module
import numpy
#fiducial setup uses these
from galpy.potential import MWPotential
from galpy.actionAngle import actionAngleAdiabatic, actionAngleStaeckel
from galpy.df import quasiisothermaldf
aAA= actionAngleAdiabatic(pot=MWPotential,c=True)
aAS= actionAngleStaeckel(pot=MWPotentia... | Python | 0 | |
660e53fa4505782a2d1484cc0b6e598edc851df0 | Initialize P05_stylingExcel | books/AutomateTheBoringStuffWithPython/Chapter12/P05_stylingExcel.py | books/AutomateTheBoringStuffWithPython/Chapter12/P05_stylingExcel.py | # This program uses the OpenPyXL module to manipulate Excel documents
import openpyxl
from openpyxl.styles import Font, Style
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name("Sheet")
italic24Font = Font(size=24, italic=True)
styleObj = Style(font=italic24Font)
sheet["A1"].style = styleObj
sheet["A1"] = "Hello ... | Python | 0.000002 | |
6e79ab6ca68252669055df12c333320bd0bda959 | Create obtainNytimes.py | obtainNytimes.py | obtainNytimes.py | import urllib.request, sys, re
from http.cookiejar import CookieJar
from docx import Document
def writeDoc(title,content):
docName = title+'.docx'
document = Document()
document.add_heading(title, 0)
document.add_paragraph(content)
document.save(docName)
def ObtainContent(pageContent):
#obtain title
for l... | Python | 0 | |
4e778d86670d4673cd591217d514a1f64dbc8424 | Add an OOP demo | oop/basic_oop.py | oop/basic_oop.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This script demonstrates how to use OOP in Python
Latest version can be found at https://github.com/letuananh/pydemo
References:
Classes in Python:
https://docs.python.org/2/tutorial/classes.html
@author: Le Tuan Anh <tuananh.ke@gmail.com>
'''
# Copyright (c) 2015,... | Python | 0.000001 | |
fb5ed0ea066c9bdb801a95e50d78529addffbed8 | add twitter url to video URL email | dj/scripts/email_url.py | dj/scripts/email_url.py | #!/usr/bin/python
# email_url.py
# emails the video URL to the presenters
from email_ab import email_ab
class email_url(email_ab):
ready_state = 7
subject_template = "[{{ep.show.name}}] Video up: {{ep.name}}"
body_body = """
The video of your talk is posted:
{{url}}
{% if ep.state == 7 %}
Look... | #!/usr/bin/python
# email_url.py
# emails the video URL to the presenters
from email_ab import email_ab
class email_url(email_ab):
ready_state = 7
subject_template = "[{{ep.show.name}}] Video up: {{ep.name}}"
body_body = """
The video of your talk is posted:
{{url}}
Look at it, make sure ... | Python | 0.000003 |
47a20435cf669d2fe0cdef1b82bbdac6a475ef5f | Add IMF to master | dlstats/fetchers/IMF.py | dlstats/fetchers/IMF.py | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 20 10:25:29 2015
@author: salimeh/ CEPREMAP
"""
from dlstats.fetchers._skeleton import Skeleton, Category, Series, Dataset, Provider
import urllib
import xlrd
import csv
import codecs
import datetime
import pandas
class IMF(Skeleton):
def __init__(self):
supe... | Python | 0.000039 | |
b47369d43a0a85ac2bc32bfa77c6a4d9074ce700 | Add basic test case for retrieve_dns module | test/test_retrieve_dns.py | test/test_retrieve_dns.py | import logging
import os
import tempfile
import unittest
import mock
import bin.retrieve_dns
logging.basicConfig(level=logging.INFO)
class RetrieveDnsTestCase(unittest.TestCase):
def setUp(self):
# Mock out logging
mock.patch('bin.retrieve_dns.set_up_logging', autospec=True).start()
... | Python | 0 | |
4f9aaa4809c0ff083393088e205a48c3197b46f2 | add forgoten '\n' in `Usage` output | platform/platform-resources/src/launcher.py | platform/platform-resources/src/launcher.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import sys
import os
import time
# see com.intellij.idea.SocketLock for the server side of this interface
RUN_PATH = u'$RUN_PATH$'
CONFIG_PATH = u'$CONFIG_PATH$'
args = []
skip_next = False
for i, arg in enumerate(sys.argv[1:]):
if arg ==... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import sys
import os
import time
# see com.intellij.idea.SocketLock for the server side of this interface
RUN_PATH = u'$RUN_PATH$'
CONFIG_PATH = u'$CONFIG_PATH$'
args = []
skip_next = False
for i, arg in enumerate(sys.argv[1:]):
if arg ==... | Python | 0.003142 |
b97a9571478dc8c919e072734816b412dadc0da9 | Add maths plugin | plugins/maths.py | plugins/maths.py | import io
import unittest
from sympy.parsing import sympy_parser
class Plugin:
def on_command(self, bot, msg, stdin, stdout, reply):
expr = " ".join(msg["args"][1:])
expr = sympy_parser.parse_expr(expr)
print(expr.evalf(), file=stdout)
def on_help(self):
return "Perform maths ... | Python | 0.000001 | |
932fc681e1e1b79a28d03a480c19869fc0a6956c | Add state module to manage InfluxDB users | salt/states/influxdb_user.py | salt/states/influxdb_user.py | # -*- coding: utf-8 -*-
'''
Management of InfluxDB users
============================
(compatible with InfluxDB version 0.9+)
'''
def __virtual__():
'''
Only load if the influxdb module is available
'''
if 'influxdb.db_exists' in __salt__:
return 'influxdb_user'
return False
def _change... | Python | 0 | |
8ab44294c0dd7b95102bfa1d9e8437067813cd0f | Add basic document parser | vc2xlsx/doc_parser.py | vc2xlsx/doc_parser.py | import parsley
class Goto (object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Goto({}, {})".format(repr(self.x), repr(self.y))
class Entry (object):
def __init__(self, value):
self.value = value
def __repr__(self):
return "Entry({})".format(repr(self.value))
class Me... | Python | 0.000004 | |
01bcda4326dc0204798f268bb1c60f06526aaba3 | add freebsd shadow module | salt/modules/freebsd_shadow.py | salt/modules/freebsd_shadow.py | '''
Manage the password database on FreeBSD systems
'''
# Import python libs
import os
try:
import pwd
except ImportError:
pass
# Import salt libs
import salt.utils
def __virtual__():
return 'shadow' if __grains__.get('os', '') == 'FreeBSD' else False
def info(name):
'''
Return information for... | Python | 0 | |
9dab373023fa6b7767cd7555a533161752205eda | Test a weighted affine solver. | scripts/0-weighted-affine.py | scripts/0-weighted-affine.py | #!/usr/bin/python
import sys
sys.path.append('../lib')
import transformations
v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]
v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]
#weights = [1.0, 1.0, 1.0, 1.0]
weights = [0.1, 0.01, 0.1, 0.2]
print "original"
print transformations.affine_matrix_from_points(v0, v1, shear=Fa... | Python | 0.001095 | |
3cb76ce0473c8598e1672828df152f164a6951c3 | Add os_recordset module (#2240) | lib/ansible/modules/extras/cloud/openstack/os_recordset.py | lib/ansible/modules/extras/cloud/openstack/os_recordset.py | #!/usr/bin/python
# Copyright (c) 2016 Hewlett-Packard Enterprise
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# T... | Python | 0 | |
962ecc4bda24a7dcb0ec75f49649853149f7e88d | Update to the tide utilities to work with the new .csv files | Module/tide_utils.py | Module/tide_utils.py | import os
import glob
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
def load_Neah_Bay(datadir):
"""
Function to load the Neah Bay tidal station data from 2015 - 2016
and returns a dataframe and a Datetime Index object
Datadir is the directory path to where ... | Python | 0 | |
260e0ef2bc37750dccea47d30110221c272e757a | Add script for automating analysis for all corpora | run_all_corpora.py | run_all_corpora.py | import os
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("corpusdir", help = "Path to the directory containing corpus directories")
parser.add_argument("script", help = "name of the script to be run")
args = parser.parse_args()
## lists of corpora to skip
## and failed to run... | Python | 0 | |
593941ec42918a389a348a5d35e8c5033bb34e73 | Add 8ball plugin | plugins/ball8.py | plugins/ball8.py | import random
from plugin import CommandPlugin, PluginException
class Ball8(CommandPlugin):
"""
8ball command (by javipepe :))
"""
def __init__(self, bot):
CommandPlugin.__init__(self, bot)
self.triggers = ['8ball']
self.short_help = 'Ask me a question'
self.help = 'As... | Python | 0 | |
d22ca6dbf7e8aa98b0f580b7972e157894925365 | Fix test output for combining filename and extension | tests/test_auto_moving.py | tests/test_auto_moving.py | import os
import shutil
from nose.tools import assert_equal
from .base import BaseTest
class TestAutoMoving(BaseTest):
organise = True
def teardown(self):
super(TestAutoMoving, self).teardown()
shutil.rmtree(self.organised)
os.mkdir(self.organised)
def test_using_organise_uses_... | import os
import shutil
from nose.tools import assert_equal
from .base import BaseTest
class TestAutoMoving(BaseTest):
organise = True
def teardown(self):
super(TestAutoMoving, self).teardown()
shutil.rmtree(self.organised)
os.mkdir(self.organised)
def test_using_organise_uses_... | Python | 0.000003 |
98c658822cf6782ca0907ab7a68691922e701aa6 | Add unittest for pytesseract | tests/test_pytesseract.py | tests/test_pytesseract.py | import unittest
import io
import pytesseract
import numpy as np
from wand.image import Image as wandimage
class TestPytesseract(unittest.TestCase):
def test_tesseract(self):
# Open pdf with Wand
with wandimage(filename='/input/tests/data/test.pdf') as wand_image:
img_buffer = np.asarray... | Python | 0.000001 | |
f8d8580dfffee35236478ec75116b291499c085c | Create maximum-average-subarray-i.py | Python/maximum-average-subarray-i.py | Python/maximum-average-subarray-i.py | # Time: O(n)
# Space: O(1)
# Given an array consisting of n integers,
# find the contiguous subarray of given length k that has the maximum average value.
# And you need to output the maximum average value.
#
# Example 1:
# Input: [1,12,-5,-6,50,3], k = 4
# Output: 12.75
# Explanation: Maximum average is (12-5-6+50)/... | Python | 0.999246 | |
164ccb9206885b216e724b3618ebae5601ab0ac0 | Add parallel execution utility module. | parallel.py | parallel.py | import multiprocessing as mp
def run_func(func, args, parallel=False):
if parallel:
mp.Pool(mp.cpu_count() - 1).map(func, args)
else:
for arg in args:
func(arg)
| Python | 0 | |
7c3ed589ace907a71931b79902382b168a2ae80d | add direct_link_downloader | downloaders/direct_link_downloader.py | downloaders/direct_link_downloader.py | import os
from urllib.request import urlopen
def direct_link_download(url, file_path):
"""
:param url: direct link to an image
:param file_path: file path (including filename) to save image to
"""
# make sure the file_path param doesn't point to a directory
if os.path.isdir(file_path):
... | Python | 0.000001 | |
e3e62c964b864c057e98763169ddc0dd922e6fa9 | Add a separate module for common parsing functions. | dunovo_parsers.py | dunovo_parsers.py | import collections
# A pair of `StrandFamily`s with the same barcode.
BarFamily = collections.namedtuple('BarFamily', ('bar', 'ab', 'ba'))
# A pair of `ReadFamily`s with the same order and barcode.
StrandFamily = collections.namedtuple('StrandFamily', ('order', 'mate1', 'mate2'))
# A set of `Read`s with the same ma... | Python | 0 | |
1455f6c563edd07a61dd826bde03137fff2d3f57 | add data for recipe 1.8 | code/ch_1-DATA_STRUCTURES_AND_ALGORITHMS/08-calculating_with_dictionaries/main.py | code/ch_1-DATA_STRUCTURES_AND_ALGORITHMS/08-calculating_with_dictionaries/main.py | def example_1():
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
max_price = max(zip(prices.values(), prices.keys()))
print(min_price, max_price)
sorted_prices = so... | Python | 0.000001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.