uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b03e8e96e5a594f5441fb852 | train | function | def Start():
Log('Start()')
ObjectContainer.art = R(ART)
DirectoryObject.thumb = R(ICON)
ObjectContainer.title1 = TITLE
TrackObject.thumb = R(ICON)
| def Start():
| Log('Start()')
ObjectContainer.art = R(ART)
DirectoryObject.thumb = R(ICON)
ObjectContainer.title1 = TITLE
TrackObject.thumb = R(ICON)
| TITLE = u'\xd61 Webradio'
PREFIX = '/music/oe1'
BASE_URL = 'http://oe1.orf.at'
ICON = 'icon-default.png'
ART = 'art-default.jpg'
def oe1feed(url):
return json.loads(urllib2.urlopen(url).read())
def Start():
| 64 | 64 | 44 | 3 | 61 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | Start | Start | 18 | 23 | 18 | 18 | 234edfdd71088916405b13354051c69d5d601e15 | bigcode/the-stack | train |
85530194d4790b01314f0f85 | train | function | @route(PREFIX + '/journale', allow_sync=True)
def Journale(title):
Log('Journale()')
oc = ObjectContainer(title2=title)
feed = oe1feed(BASE_URL + '/programm/konsole/journale')
for item in feed['list']:
oc.add(CreateTrackObject(url=item['url_stream'], title=item['title'], time=item['time'])... | @route(PREFIX + '/journale', allow_sync=True)
def Journale(title):
| Log('Journale()')
oc = ObjectContainer(title2=title)
feed = oe1feed(BASE_URL + '/programm/konsole/journale')
for item in feed['list']:
oc.add(CreateTrackObject(url=item['url_stream'], title=item['title'], time=item['time']))
return oc
| , ext='mp3'))
]
)
]
)
if include_container:
return ObjectContainer(objects=[track])
else:
return track
def PlayAudio(url):
return Redirect(url)
@route(PREFIX + '/journale', allow_sync=True)
def Journale(title):
| 64 | 64 | 91 | 18 | 46 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | Journale | Journale | 117 | 126 | 117 | 118 | aea26bee0442e015d50d50c4a62d79fb5b646fcc | bigcode/the-stack | train |
e6d0ed89bbd1e704f1ddec2a | train | function | @route(PREFIX + '/live')
def Live(title):
Log('Live()')
oc = ObjectContainer(title2=title)
return oc
| @route(PREFIX + '/live')
def Live(title):
| Log('Live()')
oc = ObjectContainer(title2=title)
return oc
| = 'Journale'
)
)
oc.add(CreateTrackObject(url='http://mp3stream4.apasf.apa.at:8000/;stream.mp3', title='CAMPUS', time=''))
return oc
@route(PREFIX + '/live')
def Live(title):
| 64 | 64 | 32 | 12 | 51 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | Live | Live | 49 | 53 | 49 | 50 | e333be0ced5fa392130dfad08b0c83cb3c05cb3f | bigcode/the-stack | train |
6b90c23025b711ea9f236657 | train | function | @route(PREFIX + '/campus')
def Campus(title):
Log('Campus()')
oc = ObjectContainer(title2=title)
oc.add(CreateTrackObject(url='http://mp3stream4.apasf.apa.at:8000/listen.pls', title='CAMPUS', time=''))
return oc
| @route(PREFIX + '/campus')
def Campus(title):
| Log('Campus()')
oc = ObjectContainer(title2=title)
oc.add(CreateTrackObject(url='http://mp3stream4.apasf.apa.at:8000/listen.pls', title='CAMPUS', time=''))
return oc
| 1feed(BASE_URL + '/programm/konsole/journale')
for item in feed['list']:
oc.add(CreateTrackObject(url=item['url_stream'], title=item['title'], time=item['time']))
return oc
@route(PREFIX + '/campus')
def Campus(title):
| 64 | 64 | 70 | 13 | 50 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | Campus | Campus | 130 | 135 | 130 | 131 | 41a4675635594dc73a2a48ff2125e07a08695635 | bigcode/the-stack | train |
3dda14a5cb006f3cab6c633b | train | function | def PlayAudio(url):
return Redirect(url)
| def PlayAudio(url):
| return Redirect(url)
| =AudioCodec.MP3,
parts = [
PartObject(key=Callback(PlayAudio, url=url, ext='mp3'))
]
)
]
)
if include_container:
return ObjectContainer(objects=[track])
else:
return track
def PlayAudio(url):
| 64 | 64 | 10 | 5 | 58 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | PlayAudio | PlayAudio | 112 | 113 | 112 | 112 | f493dd2e07b82d9c08bed593676e2d2cdfae92a5 | bigcode/the-stack | train |
f106490099d26bb54f8b7405 | train | function | @handler(PREFIX, TITLE)
def Main():
Log('Main()')
oc = ObjectContainer()
oc.add(CreateTrackObject(url='http://mp3stream3.apasf.apa.at:8000/;stream.mp3', title='Live', time=''))
oc.add(
DirectoryObject(
key = Callback(Catchup, title=u'7 Tage'),
title = u'7 Tage \... | @handler(PREFIX, TITLE)
def Main():
| Log('Main()')
oc = ObjectContainer()
oc.add(CreateTrackObject(url='http://mp3stream3.apasf.apa.at:8000/;stream.mp3', title='Live', time=''))
oc.add(
DirectoryObject(
key = Callback(Catchup, title=u'7 Tage'),
title = u'7 Tage \xd61'
)
)
oc.add(
... | json.loads(urllib2.urlopen(url).read())
def Start():
Log('Start()')
ObjectContainer.art = R(ART)
DirectoryObject.thumb = R(ICON)
ObjectContainer.title1 = TITLE
TrackObject.thumb = R(ICON)
@handler(PREFIX, TITLE)
def Main():
| 64 | 64 | 173 | 10 | 54 | vikingmedia/OE1.bundle | Contents/Code/__init__.py | Python | Main | Main | 25 | 46 | 25 | 26 | 29269950354d6af87bf67b3f03ef296a472b1e9b | bigcode/the-stack | train |
0476ee6b2a9d4b3a097ea5b9 | train | function | def test_wrong_number_alignments():
with pytest.raises(ValueError):
t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alig... | def test_wrong_number_alignments():
| with pytest.raises(ValueError):
t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignments=[Alignment.LEFT, Alignment.CE... | ─╫───────────────────────╢\n"
"║ SUM ║ 130 140 135 130 ║\n"
"╚═════╩═══════════════════════╝"
)
assert text == expected
def test_wrong_number_alignments():
| 64 | 64 | 106 | 7 | 56 | strugee/table2ascii | tests/test_alignments.py | Python | test_wrong_number_alignments | test_wrong_number_alignments | 27 | 35 | 27 | 27 | e0d94734f6b4ca72d2603c55ff8024265069f8c6 | bigcode/the-stack | train |
7362ef85f6953f88ab6af66f | train | function | def test_invalid_alignments():
with pytest.raises(ValueError):
t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignment... | def test_invalid_alignments():
| with pytest.raises(ValueError):
t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignments=[9999, -1, Alignment.RIGHT, A... | 35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignments=[Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT],
)
def test_invalid_alignments():
| 64 | 64 | 111 | 6 | 58 | strugee/table2ascii | tests/test_alignments.py | Python | test_invalid_alignments | test_invalid_alignments | 38 | 46 | 38 | 38 | a457e80f2499c9c5b4dabaf5245c2a65f78b76d4 | bigcode/the-stack | train |
a78e04e0c35f20c33e57557c | train | function | def test_first_left_four_right():
text = t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignments=[Alignment.LEFT] + [Alignment.RIGHT] * 4,
)
... | def test_first_left_four_right():
| text = t2a(
header=["#", "G", "H", "R", "S"],
body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
footer=["SUM", "130", "140", "135", "130"],
first_col_heading=True,
alignments=[Alignment.LEFT] + [Alignment.RIGHT] * 4,
)
expected = (
"╔═════╦═... | from table2ascii import table2ascii as t2a, Alignment
import pytest
def test_first_left_four_right():
| 25 | 82 | 274 | 7 | 17 | strugee/table2ascii | tests/test_alignments.py | Python | test_first_left_four_right | test_first_left_four_right | 6 | 24 | 6 | 6 | 85f31d3d0106e52a9ee55a4cf0936474ee21a218 | bigcode/the-stack | train |
7b39c54f61260eb6672db2f1 | train | function | @given(st.sets(st.tuples(text, records)))
def test_dumps_loads(data):
trie = marisa_trie.RecordTrie("<H?", data)
buf = io.BytesIO()
pickle.dump(trie, buf)
buf.seek(0)
assert trie == pickle.load(buf)
| @given(st.sets(st.tuples(text, records)))
def test_dumps_loads(data):
| trie = marisa_trie.RecordTrie("<H?", data)
buf = io.BytesIO()
pickle.dump(trie, buf)
buf.seek(0)
assert trie == pickle.load(buf)
| given
import marisa_trie
from .utils import text
records = st.tuples(st.integers(min_value=0, max_value=2**16 - 1),
st.booleans())
@given(st.sets(st.tuples(text, records)))
def test_dumps_loads(data):
| 64 | 64 | 63 | 20 | 44 | JonathanRaiman/marisa-trie | tests/test_record_trie.py | Python | test_dumps_loads | test_dumps_loads | 18 | 26 | 18 | 19 | 73a51f25d68f27a0d1a7db82f0f5673641903372 | bigcode/the-stack | train |
2d70d03beb4956792ac26710 | train | function | def run(command):
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
encoding='utf-8',
errors='replace'
)
while True:
realtime_output = process.stdout.readline()
if realtime_output == '' and process.poll() is not None:
break
if realtime_output:
... | def run(command):
| process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
encoding='utf-8',
errors='replace'
)
while True:
realtime_output = process.stdout.readline()
if realtime_output == '' and process.poll() is not None:
break
if realtime_output:
print(realtime_... | ', default='NA')
LOGGER.info('PTC Version: {}'.format(ptc_version))
ptc_jar_version = os.getenv('PTC_JAR_VERSION', default='NA')
LOGGER.info('PTC JAR Version: {}'.format(ptc_jar_version))
#
# Auxiliary functions
#
def run(command):
| 64 | 64 | 115 | 4 | 60 | pegi3s/phylogenetic-tree-collapser | scripts/collapse-tree.py | Python | run | run | 26 | 47 | 26 | 26 | 6787c7482f5c8f638cc68b6c726efd8dd97f757c | bigcode/the-stack | train |
0b24e98e2b77a367a79aeeb4 | train | class | class BooleanAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(BooleanAction, self).__init__(option_strings, dest, nargs=0, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, True)
| class BooleanAction(argparse.Action):
| def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(BooleanAction, self).__init__(option_strings, dest, nargs=0, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, True)
| Action to handle flags, inspired on this blog post: https://thisdataguy.com/2017/07/03/no-options-with-argparse-and-python/
# If the flag is present, then the corresponding target variable is set to True, otherwise remains as None.
#
class BooleanAction(argparse.Action):
| 64 | 64 | 73 | 7 | 57 | pegi3s/phylogenetic-tree-collapser | scripts/collapse-tree.py | Python | BooleanAction | BooleanAction | 57 | 62 | 57 | 57 | 7de62bf00789bc91703011892eb65e581d305d14 | bigcode/the-stack | train |
020bb21de8e456e1f63d086c | train | class | class UpdateThread(threading.Thread):
"""Thread updating the image of a :class:`~sil.gui.plot.Plot2D`
:param plot2d: The Plot2D to update."""
def __init__(self, plot2d):
self.plot2d = plot2d
self.running = False
self.future_result = None
super(UpdateThread, self).__init__()... | class UpdateThread(threading.Thread):
| """Thread updating the image of a :class:`~sil.gui.plot.Plot2D`
:param plot2d: The Plot2D to update."""
def __init__(self, plot2d):
self.plot2d = plot2d
self.running = False
self.future_result = None
super(UpdateThread, self).__init__()
def start(self):
"""Star... | achieved with
:func:`~silx.gui.utils.concurrent.submitToQtMainThread`.
In this example a thread calls submitToQtMainThread to update the image
of a plot.
Update from 1d to 2d example by Hans Fangohr, European XFEL GmbH, 26 Feb 2018.
"""
__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "05/09/2017"
impo... | 147 | 147 | 490 | 7 | 139 | tifuchs/silx | examples/plotUpdateImageFromThread.py | Python | UpdateThread | UpdateThread | 59 | 110 | 59 | 59 | 8a96e1544742fd1609afe6dc7caf90b4a14d128f | bigcode/the-stack | train |
7651a85b2ea276ec118d7789 | train | function | def main():
global app
app = qt.QApplication([])
# Create a Plot2D, set its limits and display it
plot2d = Plot2D()
plot2d.getIntensityHistogramAction().setVisible(True)
plot2d.setLimits(0, Nx, 0, Ny)
plot2d.getDefaultColormap().setVRange(0., 1.5)
plot2d.show()
# Create the thread ... | def main():
| global app
app = qt.QApplication([])
# Create a Plot2D, set its limits and display it
plot2d = Plot2D()
plot2d.getIntensityHistogramAction().setVisible(True)
plot2d.setLimits(0, Nx, 0, Ny)
plot2d.getDefaultColormap().setVRange(0., 1.5)
plot2d.show()
# Create the thread that calls s... | # keep a reference to the `future` object
self.future_result = concurrent.submitToQtMainThread(
self.plot2d.addImage, signal, resetzoom=False)
def stop(self):
"""Stop the update thread"""
self.running = False
self.join(2)
def main():
| 64 | 64 | 145 | 3 | 61 | tifuchs/silx | examples/plotUpdateImageFromThread.py | Python | main | main | 113 | 130 | 113 | 113 | aab994878bc290da18b0f2e4bb7f5e3935e39ab5 | bigcode/the-stack | train |
091c6a34c74798894eacf70d | train | class | class TestControllers(unittest.TestCase):
mongo_uri = "mongodb://localhost:27017/"
def setUp(self) -> None:
user1 = {"name": 'HanSolo', "email": 'han@federation.com'}
user2 = {"name": 'Chewy', "email": 'chewy@federation.com'}
user3 = {"name": 'Leia', "email": 'leia@federation.com'}
... | class TestControllers(unittest.TestCase):
| mongo_uri = "mongodb://localhost:27017/"
def setUp(self) -> None:
user1 = {"name": 'HanSolo', "email": 'han@federation.com'}
user2 = {"name": 'Chewy', "email": 'chewy@federation.com'}
user3 = {"name": 'Leia', "email": 'leia@federation.com'}
self.user_list = [user1, user2, user3... | # **********************************************************************
# Copyright (C) 2020 Johns Hopkins University Applied Physics Laboratory
#
# All Rights Reserved.
# For any other permission, please contact the Legal Office at JHU/APL.
# **********************************************************************... | 86 | 256 | 920 | 7 | 78 | JHUAPL/meta-system | tests/system/controllers/test_controllers.py | Python | TestControllers | TestControllers | 17 | 101 | 17 | 17 | 6cf4d855476759be86e1a43da1dc9f6f27fb5ea7 | bigcode/the-stack | train |
4f70ad02db9ad79fad16008d | train | function | def main():
module_logger.info("Vigibot starting...")
updater = Updater(token=BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher
# bot's error handler
dispatcher.add_error_handler(error)
# bot's command handlers
ola_handler = CommandHandler('ola', bom_dia, run_async=True)
dis... | def main():
| module_logger.info("Vigibot starting...")
updater = Updater(token=BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher
# bot's error handler
dispatcher.add_error_handler(error)
# bot's command handlers
ola_handler = CommandHandler('ola', bom_dia, run_async=True)
dispatcher.add_... | inlinequery, on_inline_result_chosen
from dotenv import load_dotenv
load_dotenv()
# Load environment variables from .env
BOT_TOKEN = os.getenv('BOT_TOKEN')
# Setup logging
module_logger = logging.getLogger(__name__)
module_logger.addHandler(loghandler)
module_logger.setLevel(logging.INFO)
# end of log section
def ... | 73 | 73 | 245 | 3 | 69 | AlertaDengue/vigibot | vbot.py | Python | main | main | 24 | 53 | 24 | 24 | a834fb4d2563c90812462d3fa313dd69c66370bf | bigcode/the-stack | train |
f3f3cfcfbc7f5e5ee24c51f3 | train | class | class OsuSvList(List[OsuSv], TimedList):
def _upcast(self, objList: List = None) -> OsuSvList:
""" This is to facilitate inherited functions to work
:param objList: The List to cast
:rtype: OsuSvList
"""
return OsuSvList(objList)
def data(self) -> List[OsuSv]:
... | class OsuSvList(List[OsuSv], TimedList):
| def _upcast(self, objList: List = None) -> OsuSvList:
""" This is to facilitate inherited functions to work
:param objList: The List to cast
:rtype: OsuSvList
"""
return OsuSvList(objList)
def data(self) -> List[OsuSv]:
return self
def multipliers(self) -> ... | from __future__ import annotations
from typing import List
from reamber.base.lists.TimedList import TimedList
from reamber.osu.OsuSv import OsuSv
class OsuSvList(List[OsuSv], TimedList):
| 55 | 64 | 120 | 15 | 39 | Bestfast/reamberPy | reamber/osu/lists/OsuSvList.py | Python | OsuSvList | OsuSvList | 9 | 24 | 9 | 10 | dd229b688a552fe1f37812697f15d1b1e15d1a40 | bigcode/the-stack | train |
84f18875685c9d0493d33cba | train | class | class AdminSiteTest(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(email="admin@gmail.com",password="admin@123")
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(email="test@... | class AdminSiteTest(TestCase):
| def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(email="admin@gmail.com",password="admin@123")
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(email="test@gmail.com",password="test@123",name=... | from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTest(TestCase):
| 32 | 75 | 253 | 8 | 23 | kishan-kyada/recipie-app-api | app/core/tests/test_admin.py | Python | AdminSiteTest | AdminSiteTest | 6 | 34 | 6 | 7 | 2fcfcbf67bcf6a97ecbc7512340d9a7adf7ed023 | bigcode/the-stack | train |
e99948471c51308a8643b44e | train | class | class LutronButton:
"""Representation of a button on a Lutron keypad.
This is responsible for firing events as keypad buttons are pressed
(and possibly released, depending on the button type). It is not
represented as an entity; it simply fires events.
"""
def __init__(self, hass, keypad, butt... | class LutronButton:
| """Representation of a button on a Lutron keypad.
This is responsible for firing events as keypad buttons are pressed
(and possibly released, depending on the button type). It is not
represented as an entity; it simply fires events.
"""
def __init__(self, hass, keypad, button):
"""Regi... | context, _event, _params):
"""Run when invoked by pylutron when the device state changes."""
self.schedule_update_ha_state()
@property
def name(self):
"""Return the name of the device."""
return f"{self._area_name} {self._lutron_device.name}"
@property
def should_poll(s... | 90 | 90 | 302 | 5 | 84 | petewill/home-assistant | homeassistant/components/lutron/__init__.py | Python | LutronButton | LutronButton | 125 | 163 | 125 | 125 | f411c170cf9db634b5772186631023fb16cf7464 | bigcode/the-stack | train |
aa8925df11ab15f1d86fa108 | train | class | class LutronDevice(Entity):
"""Representation of a Lutron device entity."""
def __init__(self, area_name, lutron_device, controller):
"""Initialize the device."""
self._lutron_device = lutron_device
self._controller = controller
self._area_name = area_name
async def async_a... | class LutronDevice(Entity):
| """Representation of a Lutron device entity."""
def __init__(self, area_name, lutron_device, controller):
"""Initialize the device."""
self._lutron_device = lutron_device
self._controller = controller
self._area_name = area_name
async def async_added_to_hass(self):
... | ]["binary_sensor"].append(
(area.name, area.occupancy_group)
)
for component in ("light", "cover", "switch", "scene", "binary_sensor"):
discovery.load_platform(hass, component, DOMAIN, {}, base_config)
return True
class LutronDevice(Entity):
| 64 | 64 | 202 | 6 | 57 | petewill/home-assistant | homeassistant/components/lutron/__init__.py | Python | LutronDevice | LutronDevice | 95 | 122 | 95 | 95 | df641710ed270193b64e099001d2100ad9d30fd9 | bigcode/the-stack | train |
36c53aa2f9d73aedd113d9a0 | train | function | def setup(hass, base_config):
"""Set up the Lutron component."""
from pylutron import Lutron
hass.data[LUTRON_BUTTONS] = []
hass.data[LUTRON_CONTROLLER] = None
hass.data[LUTRON_DEVICES] = {
"light": [],
"cover": [],
"switch": [],
"scene": [],
"binary_sensor":... | def setup(hass, base_config):
| """Set up the Lutron component."""
from pylutron import Lutron
hass.data[LUTRON_BUTTONS] = []
hass.data[LUTRON_CONTROLLER] = None
hass.data[LUTRON_DEVICES] = {
"light": [],
"cover": [],
"switch": [],
"scene": [],
"binary_sensor": [],
}
config = base_... | Entity
from homeassistant.util import slugify
DOMAIN = "lutron"
_LOGGER = logging.getLogger(__name__)
LUTRON_BUTTONS = "lutron_buttons"
LUTRON_CONTROLLER = "lutron_controller"
LUTRON_DEVICES = "lutron_devices"
# Attribute on events that indicates what action was taken with the button.
ATTR_ACTION = "action"
CONFI... | 146 | 146 | 488 | 8 | 138 | petewill/home-assistant | homeassistant/components/lutron/__init__.py | Python | setup | setup | 37 | 92 | 37 | 37 | b3099c0f4dc7c51b667fbfbf61c8c41db53a636b | bigcode/the-stack | train |
9db86b5490c2b50794ef29ba | train | function | def launch():
logging.info("Starting 'tasks' Config")
print("STARTING SCHEDULED TASK SCAN")
print(os.getcwd())
command = 'powershell schtasks /query /v /fo csv | ConvertFrom-CSV | Export-CSV -NoTypeInformation -Path ".\\evidence\\tasks.csv"'
result = helpers.execute.execute(command)
if not resu... | def launch():
| logging.info("Starting 'tasks' Config")
print("STARTING SCHEDULED TASK SCAN")
print(os.getcwd())
command = 'powershell schtasks /query /v /fo csv | ConvertFrom-CSV | Export-CSV -NoTypeInformation -Path ".\\evidence\\tasks.csv"'
result = helpers.execute.execute(command)
if not result == "ERROR":... | = "NA"
#detection_base['MITRE Tactic'] = "Execution, Persistence, Privilege Escalation"
#detection_base['MITRE Technique'] = "NA"
#detection_base['Risk'] = "Medium"
#detection_base['Details'] = str(d)
def launch():
| 64 | 64 | 96 | 3 | 61 | joeavanzato/QuickScan | configs/tasks/start.py | Python | launch | launch | 27 | 34 | 27 | 27 | 77556df80a8de09efedc94950e90279a85ed8656 | bigcode/the-stack | train |
d2a23d44f7de7d09227f9a77 | train | function | def process_services(file):
#fields = ['Name', 'Reason','File Path','Registry Path','MITRE Tactic','MITRE Technique','Risk','Details']
data = helpers.csv_parse.parse(file)
detection_list = []
for d in data:
if not d['HostName'] == 'HostName': #Sometimes we are seeing the headers row repeat multi... | def process_services(file):
#fields = ['Name', 'Reason','File Path','Registry Path','MITRE Tactic','MITRE Technique','Risk','Details']
| data = helpers.csv_parse.parse(file)
detection_list = []
for d in data:
if not d['HostName'] == 'HostName': #Sometimes we are seeing the headers row repeat multiple times - not sure why.
task_name = d['TaskName']
task_to_run = d['Task To Run']
try:
... | '] = "Medium"
#detection_base['Details'] = str(d)
def launch():
logging.info("Starting 'tasks' Config")
print("STARTING SCHEDULED TASK SCAN")
print(os.getcwd())
command = 'powershell schtasks /query /v /fo csv | ConvertFrom-CSV | Export-CSV -NoTypeInformation -Path ".\\evidence\\tasks.csv"'
result... | 146 | 146 | 489 | 34 | 112 | joeavanzato/QuickScan | configs/tasks/start.py | Python | process_services | process_services | 36 | 80 | 36 | 37 | e37de8b0b81892961a0b5d4a5c0b3385ca7f4201 | bigcode/the-stack | train |
61467f8621eac60c5d1587cf | train | function | def blink_all(tiles, color, duration=0.15):
for tile in tiles:
Blink(tile, color, duration).start()
| def blink_all(tiles, color, duration=0.15):
| for tile in tiles:
Blink(tile, color, duration).start()
| import time
from threading import Thread
from core import Colors
def blink_all(tiles, color, duration=0.15):
| 27 | 64 | 30 | 14 | 12 | mensch272/sudoku | logic/blink.py | Python | blink_all | blink_all | 7 | 9 | 7 | 7 | f517e1921236c145b5e06e91de2fe69968f1f41d | bigcode/the-stack | train |
4cf273a0276f3f0669fb3b58 | train | class | class Blink(Thread):
def __init__(self, tile, color, duration=0.3, **kwargs):
super(Blink, self).__init__(**kwargs)
self.tile = tile
self.color = color
self.duration = duration
self.setDaemon(True)
def run(self) -> None:
self.tile.color = self.color
ti... | class Blink(Thread):
| def __init__(self, tile, color, duration=0.3, **kwargs):
super(Blink, self).__init__(**kwargs)
self.tile = tile
self.color = color
self.duration = duration
self.setDaemon(True)
def run(self) -> None:
self.tile.color = self.color
time.sleep(self.duratio... | import time
from threading import Thread
from core import Colors
def blink_all(tiles, color, duration=0.15):
for tile in tiles:
Blink(tile, color, duration).start()
class Blink(Thread):
| 47 | 64 | 88 | 4 | 43 | mensch272/sudoku | logic/blink.py | Python | Blink | Blink | 12 | 27 | 12 | 12 | c7ae1731b927ac1fdfacdf31bc4d08bfe6300d69 | bigcode/the-stack | train |
fb0a2d4b8f812c3b79eeb4be | train | class | class NodeNetworkConfigurationPolicy(Resource):
api_group = Resource.ApiGroup.NMSTATE_IO
class Conditions:
class Type:
DEGRADED = "Degraded"
AVAILABLE = "Available"
class Reason:
CONFIGURATION_PROGRESSING = "ConfigurationProgressing"
SUCCESSFULLY... | class NodeNetworkConfigurationPolicy(Resource):
| api_group = Resource.ApiGroup.NMSTATE_IO
class Conditions:
class Type:
DEGRADED = "Degraded"
AVAILABLE = "Available"
class Reason:
CONFIGURATION_PROGRESSING = "ConfigurationProgressing"
SUCCESSFULLY_CONFIGURED = "SuccessfullyConfigured"
... | import re
from openshift.dynamic.exceptions import ConflictError
from ocp_resources.constants import TIMEOUT_4MINUTES
from ocp_resources.logger import get_logger
from ocp_resources.node import Node
from ocp_resources.node_network_configuration_enactment import (
NodeNetworkConfigurationEnactment,
)
from ocp_resou... | 125 | 256 | 3,037 | 7 | 117 | Anatw/openshift-python-wrapper | ocp_resources/node_network_configuration_policy.py | Python | NodeNetworkConfigurationPolicy | NodeNetworkConfigurationPolicy | 23 | 434 | 23 | 23 | 8e582f12c7c53e8f71f8f34d3d889746118c1cd5 | bigcode/the-stack | train |
4eef107c76520eaa8652d612 | train | class | class NNCPConfigurationFailed(Exception):
pass
| class NNCPConfigurationFailed(Exception):
| pass
| ment import (
NodeNetworkConfigurationEnactment,
)
from ocp_resources.node_network_state import NodeNetworkState
from ocp_resources.resource import Resource, ResourceEditor
from ocp_resources.utils import TimeoutExpiredError, TimeoutSampler
LOGGER = get_logger(name=__name__)
class NNCPConfigurationFailed(Exceptio... | 64 | 64 | 10 | 7 | 57 | Anatw/openshift-python-wrapper | ocp_resources/node_network_configuration_policy.py | Python | NNCPConfigurationFailed | NNCPConfigurationFailed | 19 | 20 | 19 | 19 | ce2fd17fe8af4bbcbd126cb611d9d36e5abc8cd9 | bigcode/the-stack | train |
3d8b0ca48e9154c17c81f1bb | train | function | def main():
opt = Options().parse()
# monai.config.print_config()
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# check gpus
if opt.gpu_ids != '-1':
num_gpus = len(opt.gpu_ids.split(','))
else:
num_gpus = 0
print('number of GPU:', num_gpus)
# Data loader cr... | def main():
| opt = Options().parse()
# monai.config.print_config()
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# check gpus
if opt.gpu_ids != '-1':
num_gpus = len(opt.gpu_ids.split(','))
else:
num_gpus = 0
print('number of GPU:', num_gpus)
# Data loader creation
#... | governing permissions and
# limitations under the License.
from init import Options
from networks import *
# from networks import build_net
import logging
import os
import sys
import tempfile
from glob import glob
import nibabel as nib
import numpy as np
import torch
from torch.utils.data import DataLoader
from tor... | 256 | 256 | 3,615 | 3 | 252 | davidiommi/SALMON | monai 0.5.0/deprecated/train.py | Python | main | main | 39 | 320 | 39 | 39 | b4c97bcd27532efd5d4164ecf55cd0edad349cf1 | bigcode/the-stack | train |
524811b44aaee59b0cf10f02 | train | function | def create_mirrored_strategy():
"""Create a MirroredStrategy, using a GPU if it is available."""
if tf.config.list_logical_devices('GPU'):
return tf.distribute.MirroredStrategy(['cpu:0', 'gpu:0'])
else:
return tf.distribute.MirroredStrategy(['cpu:0'])
| def create_mirrored_strategy():
| """Create a MirroredStrategy, using a GPU if it is available."""
if tf.config.list_logical_devices('GPU'):
return tf.distribute.MirroredStrategy(['cpu:0', 'gpu:0'])
else:
return tf.distribute.MirroredStrategy(['cpu:0'])
| .function
def _multiply(self, x, y):
return super(MultiplyLayerWithFunction, self)._multiply(x, y)
# If called outside any strategy.scope() calls, this will return the default
# strategy.
default_strategy_fn = tf.distribute.get_strategy
def create_mirrored_strategy():
| 64 | 64 | 70 | 7 | 56 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | create_mirrored_strategy | create_mirrored_strategy | 87 | 92 | 87 | 87 | f8c264db2846fa5502d064f58baff26fa5ffb9bb | bigcode/the-stack | train |
e8913d2af1120d6a72032ab6 | train | class | @combinations.generate(combinations.combine(mode=['graph', 'eager']))
class KerasLayerTest(keras_parameterized.TestCase):
"""Test mixed precision with Keras layers."""
@parameterized.named_parameters(*TESTCASES)
def test_mixed_policies_(self, strategy_fn):
strategy = strategy_fn()
for dtype in 'float16',... | @combinations.generate(combinations.combine(mode=['graph', 'eager']))
class KerasLayerTest(keras_parameterized.TestCase):
| """Test mixed precision with Keras layers."""
@parameterized.named_parameters(*TESTCASES)
def test_mixed_policies_(self, strategy_fn):
strategy = strategy_fn()
for dtype in 'float16', 'bfloat16':
x = tf.constant([1.])
policy_name = 'mixed_' + dtype
with strategy.scope(), policy.policy_s... | multiply(x, y)
# If called outside any strategy.scope() calls, this will return the default
# strategy.
default_strategy_fn = tf.distribute.get_strategy
def create_mirrored_strategy():
"""Create a MirroredStrategy, using a GPU if it is available."""
if tf.config.list_logical_devices('GPU'):
return tf.distri... | 256 | 256 | 3,387 | 27 | 229 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | KerasLayerTest | KerasLayerTest | 112 | 445 | 112 | 113 | 7b8e95fc9e652438b25bc8bd69700ab4e036272f | bigcode/the-stack | train |
9209cf3fb1423ac503399c29 | train | class | class MultiplyLayerWithFunction(mp_test_util.MultiplyLayer):
"""Same as MultiplyLayer, but _multiply is decorated with a tf.function."""
@tf.function
def _multiply(self, x, y):
return super(MultiplyLayerWithFunction, self)._multiply(x, y)
| class MultiplyLayerWithFunction(mp_test_util.MultiplyLayer):
| """Same as MultiplyLayer, but _multiply is decorated with a tf.function."""
@tf.function
def _multiply(self, x, y):
return super(MultiplyLayerWithFunction, self)._multiply(x, y)
| )
self.built = True
def call(self, inputs):
self.assert_input_types(inputs)
assert self.v.dtype in (tf.float32, tf.float64)
return self._multiply(inputs, tf.cast(self.v, inputs.dtype))
class MultiplyLayerWithFunction(mp_test_util.MultiplyLayer):
| 64 | 64 | 60 | 12 | 52 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | MultiplyLayerWithFunction | MultiplyLayerWithFunction | 74 | 79 | 74 | 74 | 099b694e8196cfa986fd9dfef3c47bdd1e14d1e3 | bigcode/the-stack | train |
88d90423c459b822628d70e3 | train | class | class MultiplyLayerWithoutAutoCast(mp_test_util.MultiplyLayer):
"""Same as MultiplyLayer, but does not use AutoCastVariables."""
def build(self, _):
dtype = self.dtype
if dtype in ('float16', 'bfloat16'):
dtype = 'float32'
self.v = self.add_weight(
'v', (),
initializer='ones',
... | class MultiplyLayerWithoutAutoCast(mp_test_util.MultiplyLayer):
| """Same as MultiplyLayer, but does not use AutoCastVariables."""
def build(self, _):
dtype = self.dtype
if dtype in ('float16', 'bfloat16'):
dtype = 'float32'
self.v = self.add_weight(
'v', (),
initializer='ones',
dtype=dtype,
experimental_autocast=False,
r... | _descent
from keras.saving import save
from keras.utils import generic_utils
# Pylint's static analysis incorrectly believes many layers are non-callable, so
# we disable the lint error.
# pylint: disable=not-callable
class MultiplyLayerWithoutAutoCast(mp_test_util.MultiplyLayer):
| 64 | 64 | 150 | 13 | 50 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | MultiplyLayerWithoutAutoCast | MultiplyLayerWithoutAutoCast | 53 | 71 | 53 | 53 | fdb7bf89f5650327c3745390eb475cbc46bc7788 | bigcode/the-stack | train |
1016d7e052ace68046426f41 | train | function | def create_central_storage_strategy():
"""Create a CentralStorageStrategy, using a GPU if it is available."""
compute_devices = ['cpu:0', 'gpu:0'] if (
tf.config.list_logical_devices('GPU')) else ['cpu:0']
return tf.distribute.experimental.CentralStorageStrategy(
compute_devices, parameter_device='cpu... | def create_central_storage_strategy():
| """Create a CentralStorageStrategy, using a GPU if it is available."""
compute_devices = ['cpu:0', 'gpu:0'] if (
tf.config.list_logical_devices('GPU')) else ['cpu:0']
return tf.distribute.experimental.CentralStorageStrategy(
compute_devices, parameter_device='cpu:0')
| , using a GPU if it is available."""
if tf.config.list_logical_devices('GPU'):
return tf.distribute.MirroredStrategy(['cpu:0', 'gpu:0'])
else:
return tf.distribute.MirroredStrategy(['cpu:0'])
def create_central_storage_strategy():
| 63 | 64 | 77 | 7 | 56 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | create_central_storage_strategy | create_central_storage_strategy | 95 | 100 | 95 | 95 | f8a9f4116ee2d9b926715fbdb190c8195aef2164 | bigcode/the-stack | train |
50e2a26002318fe920f5c965 | train | class | class KerasModelTest(keras_parameterized.TestCase):
"""Test mixed precision with Keras models."""
def _skip_if_strategy_unsupported(self, strategy_fn):
if (strategy_fn != default_strategy_fn and
testing_utils.get_model_type() == 'subclass'):
self.skipTest('Non-default strategies are unsupported w... | class KerasModelTest(keras_parameterized.TestCase):
| """Test mixed precision with Keras models."""
def _skip_if_strategy_unsupported(self, strategy_fn):
if (strategy_fn != default_strategy_fn and
testing_utils.get_model_type() == 'subclass'):
self.skipTest('Non-default strategies are unsupported with subclassed '
'models')
de... | .x])
del layer.x
self.assertEqual(layer.trainable_weights, [])
def test_build_and_call_layer_in_function(self):
layer = mp_test_util.MultiplyLayer(dtype=policy.Policy('mixed_float16'))
@tf.function
def f():
return layer(1.)
y = f()
self.evaluate(tf.compat.v1.global_variables_initial... | 255 | 256 | 7,398 | 12 | 243 | jordanondricka/keras | keras/mixed_precision/keras_test.py | Python | KerasModelTest | KerasModelTest | 448 | 1,209 | 448 | 448 | 7def0c51625ade14c109d727b0712e74f9fcad55 | bigcode/the-stack | train |
895a2c5e08b1347fb403f112 | train | class | class Part(SkidlBaseObject):
"""
A class for storing a definition of a schematic part.
Attributes:
ref: String storing the reference of a part within a schematic (e.g., 'R5').
value: String storing the part value (e.g., '3K3').
footprint: String storing the PCB footprint associated ... | class Part(SkidlBaseObject):
| """
A class for storing a definition of a schematic part.
Attributes:
ref: String storing the reference of a part within a schematic (e.g., 'R5').
value: String storing the part value (e.g., '3K3').
footprint: String storing the PCB footprint associated with a part (e.g., SOIC-8).
... | _pins(*pin_ids, **criteria)
# Get pin numbers from a part using brackets, e.g. [1,5:9].
__getitem__ = get_pins
def __setitem__(self, ids, *pins_nets_buses):
self.part.__setitem__(ids, *pins_nets_buses)
class PinNameSearch(object):
"""
A class for restricting part pin indexing to only pin... | 256 | 256 | 8,943 | 8 | 248 | eedin/skidl | skidl/part.py | Python | Part | Part | 103 | 1,266 | 103 | 103 | 7fe58047b16c0617371864edf09207d6c6bc69f9 | bigcode/the-stack | train |
9bdbe80249d7db40187a0145 | train | class | class PinNumberSearch(object):
"""
A class for restricting part pin indexing to only pin numbers
while ignoring pin names.
"""
def __init__(self, part):
# Store the part this object belongs to.
self.part = part
def get_pins(self, *pin_ids, **criteria):
# Add criteria th... | class PinNumberSearch(object):
| """
A class for restricting part pin indexing to only pin numbers
while ignoring pin names.
"""
def __init__(self, part):
# Store the part this object belongs to.
self.part = part
def get_pins(self, *pin_ids, **criteria):
# Add criteria that restricts pin searching to o... | try:
from PySpice.Unit.Unit import UnitValue
except ImportError:
# PySpice is not supported in Python 2, so need to make a dummy class
# to replicate a class from PySpice.
class UnitValue(object):
pass
class PinNumberSearch(object):
| 64 | 64 | 182 | 6 | 57 | eedin/skidl | skidl/part.py | Python | PinNumberSearch | PinNumberSearch | 56 | 77 | 56 | 56 | ccc8ee2fb5ef3d8d24feb389b7ec39a30f27d49c | bigcode/the-stack | train |
b83ab6fcff3899a36f186fa2 | train | class | class SkidlPart(Part):
"""
A class for storing a SKiDL definition of a schematic part. It's identical
to its Part superclass except:
+ The tool defaults to SKIDL.
+ The destination defaults to TEMPLATE so that it's easier to start
a part and then add pins to it without it being added to the... | class SkidlPart(Part):
| """
A class for storing a SKiDL definition of a schematic part. It's identical
to its Part superclass except:
+ The tool defaults to SKIDL.
+ The destination defaults to TEMPLATE so that it's easier to start
a part and then add pins to it without it being added to the netlist.
"""
... | ):
"""Any valid Part is True"""
return True
__nonzero__ = __bool__ # Python 2 compatibility.
def __len__(self):
"""Return the number of pins in this part."""
return len(self.pins)
##############################################################################
class SkidlPart(... | 63 | 64 | 143 | 7 | 56 | eedin/skidl | skidl/part.py | Python | SkidlPart | SkidlPart | 1,272 | 1,293 | 1,272 | 1,272 | 5cb50862cb3f62109b85c0193f66a7f2277afd8a | bigcode/the-stack | train |
2f33b05039834e61cc4cc038 | train | class | class PartUnit(Part):
"""
Create a PartUnit from a set of pins in a Part object.
Parts can be organized into smaller pieces called PartUnits. A PartUnit
acts like a Part but contains only a subset of the pins of the Part.
Args:
part: This is the parent Part whose pins the PartUnit is built... | class PartUnit(Part):
| """
Create a PartUnit from a set of pins in a Part object.
Parts can be organized into smaller pieces called PartUnits. A PartUnit
acts like a Part but contains only a subset of the pins of the Part.
Args:
part: This is the parent Part whose pins the PartUnit is built from.
pin_ids... | __nonzero__ = __bool__ # Python 2 compatibility.
def __len__(self):
"""Return the number of pins in this part."""
return len(self.pins)
##############################################################################
class SkidlPart(Part):
"""
A class for storing a SKiDL definition of a... | 194 | 195 | 651 | 6 | 188 | eedin/skidl | skidl/part.py | Python | PartUnit | PartUnit | 1,299 | 1,386 | 1,299 | 1,299 | a5ed83f539f89f3dd629ffd38c8c1a3894d1c95b | bigcode/the-stack | train |
e31efcfdea5f35d6cfac33f4 | train | class | class PinNameSearch(object):
"""
A class for restricting part pin indexing to only pin names
while ignoring pin numbers.
"""
def __init__(self, part):
self.part = part
def get_pins(self, *pin_ids, **criteria):
# Add criteria that restricts pin searching to only names.
c... | class PinNameSearch(object):
| """
A class for restricting part pin indexing to only pin names
while ignoring pin numbers.
"""
def __init__(self, part):
self.part = part
def get_pins(self, *pin_ids, **criteria):
# Add criteria that restricts pin searching to only names.
criteria["only_search_names"] ... | from a part using brackets, e.g. [1,5:9].
__getitem__ = get_pins
def __setitem__(self, ids, *pins_nets_buses):
self.part.__setitem__(ids, *pins_nets_buses)
class PinNameSearch(object):
| 64 | 64 | 176 | 6 | 58 | eedin/skidl | skidl/part.py | Python | PinNameSearch | PinNameSearch | 80 | 100 | 80 | 80 | bccc459597b6aaa6b9f0ebceaf623d849ec9ea5b | bigcode/the-stack | train |
d58afdb9f76e34abbfccf071 | train | class | class TestMoveFileAsync:
@pytest.mark.asyncio
# use tmp_path pytest fixture to create a temporary directory
async def test_move_file_async(self, tmp_path: Path):
"""
Move a file from one location to another.
"""
src_path: Path = tmp_path / "source.txt"
src_path.write... | class TestMoveFileAsync:
@pytest.mark.asyncio
# use tmp_path pytest fixture to create a temporary directory
| async def test_move_file_async(self, tmp_path: Path):
"""
Move a file from one location to another.
"""
src_path: Path = tmp_path / "source.txt"
src_path.write_text("source")
dst_path: Path = tmp_path / "destination.txt"
await move_file_async(src_path, dst_pa... | (src_path, dst_path)
assert shutil_move_called is True
assert src_path.exists() is False
assert dst_path.exists() is True
assert dst_path.read_text() == "source"
# use tmp_path pytest fixture to create a temporary directory
def test_move_file_failing(self, tmp_path: Path, monkey... | 256 | 256 | 886 | 26 | 229 | PuNkYsHuNgRy/joker-blockchain | tests/core/util/test_files.py | Python | TestMoveFileAsync | TestMoveFileAsync | 172 | 278 | 172 | 174 | 8ac252503ba0926a1b7c5c389452bd444862e29d | bigcode/the-stack | train |
9f967f7f3420ec00269a9c17 | train | class | class TestMoveFile:
# use tmp_path pytest fixture to create a temporary directory
def test_move_file(self, tmp_path: Path):
"""
Move a file from one location to another and verify the contents.
"""
src_path: Path = tmp_path / "source.txt"
src_path.write_text("source")
... | class TestMoveFile:
# use tmp_path pytest fixture to create a temporary directory
| def test_move_file(self, tmp_path: Path):
"""
Move a file from one location to another and verify the contents.
"""
src_path: Path = tmp_path / "source.txt"
src_path.write_text("source")
dst_path: Path = tmp_path / "destination.txt"
move_file(src_path, dst_pa... | import os
import pytest
import shutil
import sys
from joker.util import files
from joker.util.files import move_file, move_file_async, write_file_async
from pathlib import Path
class TestMoveFile:
# use tmp_path pytest fixture to create a temporary directory
| 57 | 256 | 1,313 | 18 | 38 | PuNkYsHuNgRy/joker-blockchain | tests/core/util/test_files.py | Python | TestMoveFile | TestMoveFile | 11 | 169 | 11 | 12 | fdf249f19a2624e49d0b946f29039d3a58b8a377 | bigcode/the-stack | train |
5f9a052d3af848b8e59b3dca | train | class | class TestWriteFile:
@pytest.mark.asyncio
# use tmp_path pytest fixture to create a temporary directory
async def test_write_file(self, tmp_path: Path):
"""
Write a file to a location.
"""
dest_path: Path = tmp_path / "test_write_file.txt"
await write_file_async(dest... | class TestWriteFile:
@pytest.mark.asyncio
# use tmp_path pytest fixture to create a temporary directory
| async def test_write_file(self, tmp_path: Path):
"""
Write a file to a location.
"""
dest_path: Path = tmp_path / "test_write_file.txt"
await write_file_async(dest_path, "test")
assert dest_path.read_text() == "test"
@pytest.mark.asyncio
# use tmp_path pytes... | test_move_file_async_failure_on_reattempt(self, tmp_path: Path, monkeypatch):
"""
Simulate moving a file where the move fails and exhausts all reattempts. The move should fail.
"""
total_allowed_attempts: int = 3
attempts: int = 0
def mock_os_replace(src, dst):
... | 256 | 256 | 968 | 25 | 230 | PuNkYsHuNgRy/joker-blockchain | tests/core/util/test_files.py | Python | TestWriteFile | TestWriteFile | 281 | 388 | 281 | 283 | 4ba3042d760d00d95de9f5e429e0617e0797f7dd | bigcode/the-stack | train |
6d002afb694a4af3a6317cf9 | train | function | def merge(lst):
if len(lst) == 1:
return lst
left = lst[:len(lst)//2]
right = lst[len(lst)//2:]
left_sorted = merge(left)
right_sorted = merge(right)
return merge_sort(left_sorted, right_sorted)
| def merge(lst):
| if len(lst) == 1:
return lst
left = lst[:len(lst)//2]
right = lst[len(lst)//2:]
left_sorted = merge(left)
right_sorted = merge(right)
return merge_sort(left_sorted, right_sorted)
| ) >= 1:
if left[0] <= right[0]:
new_list.append(left.pop(0))
else:
new_list.append(right.pop(0))
new_list = new_list + left
new_list = new_list + right
return new_list
def merge(lst):
| 64 | 64 | 60 | 4 | 59 | eidgahadi/Homework3 | sorting.py | Python | merge | merge | 36 | 45 | 36 | 36 | 29f58179a5b9eb21e139fe040b7eca42732a7768 | bigcode/the-stack | train |
1a62b921d9daf24a2b0e3419 | train | function | def merge_sort(left, right):
new_list = []
if len(left) == 1 and len(right) == 1:
if left[0] < right[0]:
new_list.append(left[0])
new_list.append(right[0])
else:
new_list.append(right[0])
new_list.append(left[0])
else:
while len(left) >... | def merge_sort(left, right):
| new_list = []
if len(left) == 1 and len(right) == 1:
if left[0] < right[0]:
new_list.append(left[0])
new_list.append(right[0])
else:
new_list.append(right[0])
new_list.append(left[0])
else:
while len(left) >= 1 and len(right) >= 1:
... | else:
pivot = lst.pop(0)
left, right = [], []
for i in lst:
if i > pivot:
right.append(i)
else:
left.append(i)
return quick_sort(left) + [pivot] + quick_sort(right)
def merge_sort(left, right):
| 64 | 64 | 148 | 7 | 57 | eidgahadi/Homework3 | sorting.py | Python | merge_sort | merge_sort | 15 | 33 | 15 | 15 | 56b710a103888204334cc6c7d5fac6b03c4e4536 | bigcode/the-stack | train |
46be8aa950b7afc05532e5dc | train | function | def quick_sort(lst):
if len(lst) <= 1:
return lst
else:
pivot = lst.pop(0)
left, right = [], []
for i in lst:
if i > pivot:
right.append(i)
else:
left.append(i)
return quick_sort(left) + [pivot] + quick_sort(right)
| def quick_sort(lst):
| if len(lst) <= 1:
return lst
else:
pivot = lst.pop(0)
left, right = [], []
for i in lst:
if i > pivot:
right.append(i)
else:
left.append(i)
return quick_sort(left) + [pivot] + quick_sort(right)
| def quick_sort(lst):
| 5 | 64 | 76 | 5 | 0 | eidgahadi/Homework3 | sorting.py | Python | quick_sort | quick_sort | 1 | 12 | 1 | 1 | e3b5cff9595f569199ce1c0014a10571dd7b1c2d | bigcode/the-stack | train |
d2d75cf9636a32453d5f31e9 | train | function | def depthZeroSearch(board):
ogBoard = board
count = 0
move1 = move2 = None
board1 = board2 = None
for move in ogBoard.legal_moves:
if count == 0:
move1 = move
else:
modBoard = ogBoard
move2 = move
modBoard.push(move1)
move... | def depthZeroSearch(board):
| ogBoard = board
count = 0
move1 = move2 = None
board1 = board2 = None
for move in ogBoard.legal_moves:
if count == 0:
move1 = move
else:
modBoard = ogBoard
move2 = move
modBoard.push(move1)
move1Feature = convertToFeatureV... | else:
pieces.append(-11)
return pieces
def evaluateMove(move1, move2):
df1 = pd.DataFrame(data=[move1])
df2 = pd.DataFrame(data=[move2])
return model.predict([df1, df2])
def depthZeroSearch(board):
| 64 | 64 | 171 | 6 | 58 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | depthZeroSearch | depthZeroSearch | 105 | 129 | 105 | 105 | 9a3c4398d88caa4802a1ea94d29f16c5695fae77 | bigcode/the-stack | train |
2526db6bc80eb306c47d3503 | train | function | def chooseEngine(num):
if num == 1:
return chess.engine.SimpleEngine.popen_xboard("./crafty")
return chess.engine.SimpleEngine.popen_uci("./stockfish_10_x64")
| def chooseEngine(num):
| if num == 1:
return chess.engine.SimpleEngine.popen_xboard("./crafty")
return chess.engine.SimpleEngine.popen_uci("./stockfish_10_x64")
| legal move
nn_depth = 4 # <--- DEPTH OF OUR ALPHABETA ALGORITHM
engine_depth = 4 # <--- DEPTH OF THE ENGINE
print("Loading Model")
model = tf.keras.models.load_model(nn_fn_array[nn])
print("Done Loading")
def chooseEngine(num):
| 64 | 64 | 44 | 5 | 59 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | chooseEngine | chooseEngine | 44 | 47 | 44 | 44 | 70efbdd512cc1fa591ed1bcddbe9bdf5f73e836f | bigcode/the-stack | train |
8fa53b52466a2826e84cd350 | train | function | def evaluateMove(move1, move2):
df1 = pd.DataFrame(data=[move1])
df2 = pd.DataFrame(data=[move2])
return model.predict([df1, df2])
| def evaluateMove(move1, move2):
| df1 = pd.DataFrame(data=[move1])
df2 = pd.DataFrame(data=[move2])
return model.predict([df1, df2])
| s & chess.BB_A8)
if(queenBlack):
pieces.append(10)
else:
pieces.append(-10)
if(board.turn):
pieces.append(11)
else:
pieces.append(-11)
return pieces
def evaluateMove(move1, move2):
| 64 | 64 | 45 | 10 | 53 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | evaluateMove | evaluateMove | 99 | 102 | 99 | 99 | ae24b30a0851e6d5e19b00e1d828490de62aed95 | bigcode/the-stack | train |
06f203fedb4af09eeb429806 | train | function | def comparisonAlphaBeta(board, depth, whitesTurn):
if depth == 0 or board.is_game_over():
return board
board = board.copy()
best_board = board
cnt = 0
mv1 = None
prune = False
for move in board.legal_moves:
if cnt > 1:
board.push(move)
if whitesT... | def comparisonAlphaBeta(board, depth, whitesTurn):
| if depth == 0 or board.is_game_over():
return board
board = board.copy()
best_board = board
cnt = 0
mv1 = None
prune = False
for move in board.legal_moves:
if cnt > 1:
board.push(move)
if whitesTurn:
evaluated_pos = comparisonAlph... | Board
move2 = move
modBoard.push(move1)
move1Feature = convertToFeatureVector(modBoard)
modBoard.pop()
modBoard.push(move2)
move2Feature = convertToFeatureVector(modBoard)
modBoard.pop()
strengthArr = evaluateMove(move1Fea... | 147 | 147 | 493 | 11 | 136 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | comparisonAlphaBeta | comparisonAlphaBeta | 133 | 203 | 133 | 133 | 35ad6f98ed92adb3af00f489b9877758d7b7b3b4 | bigcode/the-stack | train |
29fab335d08ef39b468278c0 | train | function | def convertToFeatureVector(boardState):
pieces = []
encoding = {'P':1,'R':2,'N':3,'B':4,'Q':5,'K':6,'p':-1,'r':-2,'n':-3,'b':-4,'q':-5,'k':-6, '.':0}
for i in range(64):
piece = boardState.piece_at(i)
if piece:
piece = piece.symbol()
else:
piece = '.'
... | def convertToFeatureVector(boardState):
| pieces = []
encoding = {'P':1,'R':2,'N':3,'B':4,'Q':5,'K':6,'p':-1,'r':-2,'n':-3,'b':-4,'q':-5,'k':-6, '.':0}
for i in range(64):
piece = boardState.piece_at(i)
if piece:
piece = piece.symbol()
else:
piece = '.'
pieces.append(encoding[piece])
... | _model(nn_fn_array[nn])
print("Done Loading")
def chooseEngine(num):
if num == 1:
return chess.engine.SimpleEngine.popen_xboard("./crafty")
return chess.engine.SimpleEngine.popen_uci("./stockfish_10_x64")
def countMoves(moves):
length = 0
for _ in moves:
length += 1
return length
d... | 92 | 92 | 308 | 8 | 83 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | convertToFeatureVector | convertToFeatureVector | 55 | 97 | 55 | 55 | e5f0b126684d29faea88684fb373ae51c8cd1693 | bigcode/the-stack | train |
5ec79ec4baacc64519ba6b54 | train | function | def countMoves(moves):
length = 0
for _ in moves:
length += 1
return length
| def countMoves(moves):
| length = 0
for _ in moves:
length += 1
return length
| .models.load_model(nn_fn_array[nn])
print("Done Loading")
def chooseEngine(num):
if num == 1:
return chess.engine.SimpleEngine.popen_xboard("./crafty")
return chess.engine.SimpleEngine.popen_uci("./stockfish_10_x64")
def countMoves(moves):
| 64 | 64 | 28 | 6 | 58 | ucdchessai/chess-ai | source/Tester/depthTesting/StockfishDepth4.py | Python | countMoves | countMoves | 49 | 53 | 49 | 49 | 6005a044cfa281022024785e452ddf46ffee3053 | bigcode/the-stack | train |
025b2ec25c4127ae7e577d10 | train | function | def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list ... | def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
| from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta.get_fields()
for field in fields:
# Skip ManyToOneRel ... | OLIBRI_HOME"]):
os.mkdir(os.environ["KOLIBRI_HOME"])
django.setup()
# Monkey patch this so we don't have any complaints during Sphinx inspect
from django.db.models.fields import files # noqa
files.FileDescriptor.__get__ = lambda *args: None
# Auto list fields from django models - from https://djangosnippets.or... | 115 | 115 | 386 | 28 | 86 | MingDai/kolibri | docs/conf.py | Python | process_docstring | process_docstring | 51 | 88 | 51 | 52 | e3804e70deaadf0f7ab0535e5d02f04bfc1e2198 | bigcode/the-stack | train |
5d1efa6a16e27e747247cc40 | train | function | def setup(app):
# Register the docstring processor with sphinx
app.connect('autodoc-process-docstring', process_docstring)
| def setup(app):
# Register the docstring processor with sphinx
| app.connect('autodoc-process-docstring', process_docstring)
| ~%s`' % (field.attname, type(field).__name__, to))
else:
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
return lines
def setup(app):
# Register the docstring processor with sphinx
| 64 | 64 | 30 | 15 | 48 | MingDai/kolibri | docs/conf.py | Python | setup | setup | 91 | 93 | 91 | 92 | 1842501a45f5870714016259aff4e13ee624edb4 | bigcode/the-stack | train |
f3505e4ed3fb24ad400554d0 | train | function | def get_focused_window_handle():
print('\nClick in the window to get the process! The first click will be considered.')
hwnd = []
def on_click(x, y, button, pressed):
if not pressed:
hwnd.append(win32gui.GetForegroundWindow())
return False
with MouseListener(on_click=on_click) as mouse_listener... | def get_focused_window_handle():
| print('\nClick in the window to get the process! The first click will be considered.')
hwnd = []
def on_click(x, y, button, pressed):
if not pressed:
hwnd.append(win32gui.GetForegroundWindow())
return False
with MouseListener(on_click=on_click) as mouse_listener:
mouse_listener.join()
pri... | 9' should return 'F9', 'w' should return as 'w'
cleaned_key = button.replace('Key.', '')
if cleaned_key in PYNPUT_SPECIAL_CASE_MAP:
return PYNPUT_SPECIAL_CASE_MAP[cleaned_key]
return cleaned_key
def get_focused_window_handle():
| 64 | 64 | 108 | 7 | 56 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | get_focused_window_handle | get_focused_window_handle | 120 | 135 | 120 | 120 | 38e5bb4f16ba0e052cacdbb2501560328e1f020c | bigcode/the-stack | train |
5f95f2f65fa66c8ee668be71 | train | function | def playActions(filename, hwnd):
# Read the file
script_dir = os.path.dirname(__file__)
filepath = os.path.join(
script_dir,
'recordings',
filename
)
with open(filepath, 'r') as jsonfile:
# parse the json
data = json.load(jsonfile)
# loop over each action
# Because we are not waitin... | def playActions(filename, hwnd):
# Read the file
| script_dir = os.path.dirname(__file__)
filepath = os.path.join(
script_dir,
'recordings',
filename
)
with open(filepath, 'r') as jsonfile:
# parse the json
data = json.load(jsonfile)
# loop over each action
# Because we are not waiting any time before executing the first action, any de... | import os
import json
import win32api, win32con, win32gui
from time import sleep, time
from pyfiglet import Figlet
from pynput.mouse import Listener as MouseListener
from ctypes import windll
def main():
hwnd = get_focused_window_handle()
start_countdown(3)
playActions("tower_b5.json", hwnd)
sleep(... | 99 | 139 | 466 | 13 | 86 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | playActions | playActions | 19 | 72 | 19 | 20 | 7e0e5ec2461d7f16e3b45bec3e1dbae2207a3fd9 | bigcode/the-stack | train |
4025d727b1d8cbb143b9bfd3 | train | function | def print_logo(text_logo: str):
figlet = Figlet(font='slant')
print(figlet.renderText(text_logo))
| def print_logo(text_logo: str):
| figlet = Figlet(font='slant')
print(figlet.renderText(text_logo))
| (sleep_time_sec=5):
print('Starting', end='', flush=True)
for i in range(10):
print('.', end='', flush=True)
sleep(sleep_time_sec/10)
print('\nReady, forcing dwarves to work!')
def print_logo(text_logo: str):
| 62 | 64 | 28 | 8 | 55 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | print_logo | print_logo | 174 | 176 | 174 | 174 | 2e7e874e172d20d0020a7f048afc6eb4abecf234 | bigcode/the-stack | train |
9610357a67e1166aee31157b | train | function | def window_key_down(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key, 0);
| def window_key_down(hwnd, key):
| win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key, 0);
| 32gui.GetForegroundWindow())
return False
with MouseListener(on_click=on_click) as mouse_listener:
mouse_listener.join()
print('Window Selected: ', win32gui.GetWindowText(hwnd[0]))
sleep(0.5)
return hwnd[0]
def window_key_down(hwnd, key):
| 63 | 64 | 28 | 8 | 55 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | window_key_down | window_key_down | 138 | 139 | 138 | 138 | beadae5d2ccc3da5dde4520d8522cf6da7974300 | bigcode/the-stack | train |
97152f4fe140bfb67f1e5f7e | train | function | def magic_click(hwnd, x, y):
old_pos = win32api.GetCursorPos()
windll.user32.BlockInput(True)
win32api.SetCursorPos((x, y))
win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, 0)
sleep(0.015)
win32api.SetCursorP... | def magic_click(hwnd, x, y):
| old_pos = win32api.GetCursorPos()
windll.user32.BlockInput(True)
win32api.SetCursorPos((x, y))
win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, 0)
sleep(0.015)
win32api.SetCursorPos(old_pos)
windll.user32.Bl... | window_key_down(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key, 0);
def window_key_up(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYUP, key, 0);
def magic_click(hwnd, x, y):
| 64 | 64 | 117 | 9 | 55 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | magic_click | magic_click | 146 | 155 | 146 | 146 | d5cfab519af34cac96b76e27d7ae3a4275369d8d | bigcode/the-stack | train |
378695346d0389456c2a7289 | train | function | def start_countdown(sleep_time_sec=5):
print('Starting', end='', flush=True)
for i in range(10):
print('.', end='', flush=True)
sleep(sleep_time_sec/10)
print('\nReady, forcing dwarves to work!')
| def start_countdown(sleep_time_sec=5):
| print('Starting', end='', flush=True)
for i in range(10):
print('.', end='', flush=True)
sleep(sleep_time_sec/10)
print('\nReady, forcing dwarves to work!')
| (hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, lParam)
# region Helpers
def start_countdown(sleep_time_sec=5):
| 64 | 64 | 59 | 11 | 52 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | start_countdown | start_countdown | 166 | 171 | 166 | 166 | 95502a99dc8941f063f6403947b0386bf4c6d8ff | bigcode/the-stack | train |
2f48606d9fec907a72dd71a3 | train | function | def main():
hwnd = get_focused_window_handle()
start_countdown(3)
playActions("tower_b5.json", hwnd)
sleep(1)
print("Done")
| def main():
| hwnd = get_focused_window_handle()
start_countdown(3)
playActions("tower_b5.json", hwnd)
sleep(1)
print("Done")
| import os
import json
import win32api, win32con, win32gui
from time import sleep, time
from pyfiglet import Figlet
from pynput.mouse import Listener as MouseListener
from ctypes import windll
def main():
| 53 | 64 | 36 | 3 | 49 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | main | main | 10 | 16 | 10 | 10 | b278ceda023a14db94d31f8c3f247c59124ce418 | bigcode/the-stack | train |
ffe64c3279262f8ada4454a1 | train | function | def convertKey(button):
PYNPUT_SPECIAL_CASE_MAP = {
'f1': 0x70,
'f2': 0x71,
'f3': 0x72,
'f4': 0x73,
'f5': 0x74,
'f6': 0x75,
'f7': 0x76,
'f8': 0x77,
'f9': 0x78,
'space': 0x20,
'enter': 0x0D,
'w': 0x57,
'a': 0x41,
's': 0x53,
'd': 0x44,
'c': 0x43,
'up': 0x26,
'left':... | def convertKey(button):
| PYNPUT_SPECIAL_CASE_MAP = {
'f1': 0x70,
'f2': 0x71,
'f3': 0x72,
'f4': 0x73,
'f5': 0x74,
'f6': 0x75,
'f7': 0x76,
'f8': 0x77,
'f9': 0x78,
'space': 0x20,
'enter': 0x0D,
'w': 0x57,
'a': 0x41,
's': 0x53,
'd': 0x44,
'c': 0x43,
'up': 0x26,
'left': 0x25,
'down': 0x28,
... | elapsed_time -= (time() - action_start_time)
if elapsed_time < 0:
elapsed_time = 0
print('sleeping for {}'.format(elapsed_time))
sleep(elapsed_time)
# convert pynput button keys into win32 virtual keys
# https://pynput.readthedocs.io/en/latest/_modules/pynput/keyboard/_base.html#Key
# https://d... | 109 | 109 | 366 | 5 | 103 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | convertKey | convertKey | 78 | 117 | 78 | 78 | 9d24caae424c4f5b8c81a87049e52a73648eed23 | bigcode/the-stack | train |
1ad0fbdd55d73d814590cd2b | train | function | def window_key_up(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYUP, key, 0);
| def window_key_up(hwnd, key):
| win32api.PostMessage(hwnd, win32con.WM_KEYUP, key, 0);
| print('Window Selected: ', win32gui.GetWindowText(hwnd[0]))
sleep(0.5)
return hwnd[0]
def window_key_down(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key, 0);
def window_key_up(hwnd, key):
| 64 | 64 | 28 | 8 | 56 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | window_key_up | window_key_up | 142 | 143 | 142 | 142 | f8db72c68591380a4b36367c8ae8462e02426819 | bigcode/the-stack | train |
f734b6647414d1ed0560b21f | train | function | def right_click_window(hwnd, x, y):
lParam = win32api.MAKELONG(x, y)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, lParam)
| def right_click_window(hwnd, x, y):
| lParam = win32api.MAKELONG(x, y)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, lParam)
| 0)
sleep(0.005)
win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, 0)
sleep(0.015)
win32api.SetCursorPos(old_pos)
windll.user32.BlockInput(False)
def right_click_window(hwnd, x, y):
| 64 | 64 | 78 | 10 | 54 | xandao6/clockworks-flyff-bots | recording_bot/background_playback.py | Python | right_click_window | right_click_window | 158 | 162 | 158 | 158 | 3c3406aa837ec182947c70abbe3ab3c967561b49 | bigcode/the-stack | train |
8616296b056013ffa7191123 | train | function | def main(args, sys_argv):
check_dependencies()
with bcbio_tmpdir():
setup_data_dir(args)
print("Installing isolated base python installation")
anaconda = install_anaconda_python(args, remotes)
print("Installing bcbio-nextgen")
install_conda_pkgs(anaconda)
bcbio = ... | def main(args, sys_argv):
| check_dependencies()
with bcbio_tmpdir():
setup_data_dir(args)
print("Installing isolated base python installation")
anaconda = install_anaconda_python(args, remotes)
print("Installing bcbio-nextgen")
install_conda_pkgs(anaconda)
bcbio = bootstrap_bcbionextgen(ana... | gen.git",
"system_config":
"https://raw.github.com/chapmanb/bcbio-nextgen/master/config/bcbio_system.yaml",
"anaconda":
"http://repo.continuum.io/miniconda/Miniconda-3.5.5-%s-x86_64.sh"}
def main(args, sys_argv):
| 75 | 75 | 252 | 8 | 67 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | main | main | 28 | 47 | 28 | 28 | 7d86683150e9a615e4697c69e81f4d0aca0941fe | bigcode/the-stack | train |
967a86c27dc103f4f6b0ab0b | train | function | def bootstrap_bcbionextgen(anaconda, args, remotes):
"""Install bcbio-nextgen to bootstrap rest of installation process.
"""
subprocess.check_call([anaconda["pip"], "install", "fabric"])
subprocess.check_call([anaconda["pip"], "install", "-r", remotes["requirements"]])
if args.upgrade == "developmen... | def bootstrap_bcbionextgen(anaconda, args, remotes):
| """Install bcbio-nextgen to bootstrap rest of installation process.
"""
subprocess.check_call([anaconda["pip"], "install", "fabric"])
subprocess.check_call([anaconda["pip"], "install", "-r", remotes["requirements"]])
if args.upgrade == "development":
subprocess.check_call([anaconda["pip"], "... | bcbio["bcbio_nextgen.py"], "--version"], stdout=subprocess.PIPE)
version, _ = process.communicate()
if version.strip() > "0.7.4":
if "--nodata" in base:
base.remove("--nodata")
else:
base.append("--data")
return base
def bootstrap_bcbionextgen(anaconda, args, remotes)... | 84 | 84 | 281 | 15 | 68 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | bootstrap_bcbionextgen | bootstrap_bcbionextgen | 65 | 86 | 65 | 65 | 949a29c474989770275c1a46a76fdf7db927a8ba | bigcode/the-stack | train |
b6aa88f483f79e97708679fd | train | function | def setup_manifest(datadir):
"""Create barebones manifest to be filled in during update
"""
manifest_dir = os.path.join(datadir, "manifest")
if not os.path.exists(manifest_dir):
os.makedirs(manifest_dir)
| def setup_manifest(datadir):
| """Create barebones manifest to be filled in during update
"""
manifest_dir = os.path.join(datadir, "manifest")
if not os.path.exists(manifest_dir):
os.makedirs(manifest_dir)
| .check_call("bash %s -b -p %s" %
(os.path.basename(url), anaconda_dir), shell=True)
return {"conda": conda,
"pip": os.path.join(bindir, "pip"),
"dir": anaconda_dir}
def setup_manifest(datadir):
| 64 | 64 | 51 | 6 | 58 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | setup_manifest | setup_manifest | 125 | 130 | 125 | 125 | f0382d76827fc852652f7f6b93b3726ff82ef23c | bigcode/the-stack | train |
719215e5ec1ae00422cf9ff9 | train | function | def _clean_args(sys_argv, args, bcbio):
"""Remove data directory from arguments to pass to upgrade function.
"""
base = [x for x in sys_argv if
x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))]
# specification of data argument changes in install (default data) ... | def _clean_args(sys_argv, args, bcbio):
| """Remove data directory from arguments to pass to upgrade function.
"""
base = [x for x in sys_argv if
x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))]
# specification of data argument changes in install (default data) to upgrade (default nodata)
# in bcb... | (" Tools installed in:\n %s" % args.tooldir)
print(" Ready to use system configuration at:\n %s" % system_config)
print(" Edit configuration file as needed to match your machine or cluster")
def _clean_args(sys_argv, args, bcbio):
| 64 | 64 | 174 | 14 | 50 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | _clean_args | _clean_args | 49 | 63 | 49 | 49 | 4403ad0ed8641944c4f213f0cdbdbbfb192dcc58 | bigcode/the-stack | train |
fe5f2cb2bd68b5bab628c87b | train | function | def install_conda_pkgs(anaconda):
pkgs = ["biopython", "boto", "cpat", "cython", "ipython", "lxml",
"matplotlib", "msgpack-python", "nose", "numpy", "pandas", "patsy", "pycrypto",
"pip", "pysam", "pyvcf", "pyyaml", "pyzmq", "reportlab", "requests", "scipy",
"setuptools", "sqlalch... | def install_conda_pkgs(anaconda):
| pkgs = ["biopython", "boto", "cpat", "cython", "ipython", "lxml",
"matplotlib", "msgpack-python", "nose", "numpy", "pandas", "patsy", "pycrypto",
"pip", "pysam", "pyvcf", "pyyaml", "pyzmq", "reportlab", "requests", "scipy",
"setuptools", "sqlalchemy", "statsmodels", "toolz", "tor... | ", "-f", final_script]
subprocess.check_call(sudo_cmd + cmd)
cmd = ["ln", "-s", ve_script, final_script]
subprocess.check_call(sudo_cmd + cmd)
out[script] = ve_script
return out
def install_conda_pkgs(anaconda):
| 64 | 64 | 185 | 9 | 54 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | install_conda_pkgs | install_conda_pkgs | 88 | 95 | 88 | 88 | adb78cf5d4d4a3e404cbb7508c7586a7905bd3f8 | bigcode/the-stack | train |
f22cef8b1c3bc15861a4e13f | train | function | def setup_data_dir(args):
if not os.path.exists(args.datadir):
cmd = ["mkdir", "-p", args.datadir]
if args.sudo:
cmd.insert(0, "sudo")
subprocess.check_call(cmd)
if args.sudo:
subprocess.check_call(["sudo", "chown", "-R", os.environ["USER"], args.datadir])
| def setup_data_dir(args):
| if not os.path.exists(args.datadir):
cmd = ["mkdir", "-p", args.datadir]
if args.sudo:
cmd.insert(0, "sudo")
subprocess.check_call(cmd)
if args.sudo:
subprocess.check_call(["sudo", "chown", "-R", os.environ["USER"], args.datadir])
| %s\n" % (line.split(":")[0],
os.path.join(java_basedir, final_dir))
in_prog = None
elif line.startswith("galaxy"):
line = "# %s" % line
out_handle.write(line)
return out_file
def setup_data_dir(args... | 64 | 64 | 79 | 6 | 57 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | setup_data_dir | setup_data_dir | 171 | 178 | 171 | 171 | 3e08f3bc22875fa74c9a2ac3205fc61cdc40f76b | bigcode/the-stack | train |
57b4e5d138a9f1c9adc343f3 | train | function | def _check_toolplus(x):
"""Parse options for adding non-standard/commercial tools like GATK and MuTecT.
"""
import argparse
Tool = collections.namedtuple("Tool", ["name", "fname"])
std_choices = set(["data", "cadd", "dbnsfp"])
if x in std_choices:
return Tool(x, None)
elif "=" in x a... | def _check_toolplus(x):
| """Parse options for adding non-standard/commercial tools like GATK and MuTecT.
"""
import argparse
Tool = collections.namedtuple("Tool", ["name", "fname"])
std_choices = set(["data", "cadd", "dbnsfp"])
if x in std_choices:
return Tool(x, None)
elif "=" in x and len(x.split("=")) == ... | Ensure required tools for installation are present.
"""
print("Checking required dependencies")
try:
subprocess.check_call(["git", "--version"])
except OSError:
raise OSError("bcbio-nextgen installer requires Git (http://git-scm.com/)")
def _check_toolplus(x):
| 64 | 64 | 184 | 7 | 57 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | _check_toolplus | _check_toolplus | 200 | 216 | 200 | 200 | c8ad793882565b53a75552d12adb57f502780229 | bigcode/the-stack | train |
b131072b32468d98d6d6d0c3 | train | function | def write_system_config(base_url, datadir, tooldir):
"""Write a bcbio_system.yaml configuration file with tool information.
"""
out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url))
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
if o... | def write_system_config(base_url, datadir, tooldir):
| """Write a bcbio_system.yaml configuration file with tool information.
"""
out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url))
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
if os.path.exists(out_file):
# if no tool directo... | subprocess.check_call("bash %s -b -p %s" %
(os.path.basename(url), anaconda_dir), shell=True)
return {"conda": conda,
"pip": os.path.join(bindir, "pip"),
"dir": anaconda_dir}
def setup_manifest(datadir):
"""Create barebones manifest to be filled in ... | 125 | 125 | 419 | 14 | 111 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | write_system_config | write_system_config | 132 | 169 | 132 | 132 | b500b363af03ef029dcd69f0d87df5fb1a67b974 | bigcode/the-stack | train |
44329dae56b58fc9bc29e587 | train | function | def install_anaconda_python(args, remotes):
"""Provide isolated installation of Anaconda python for running bcbio-nextgen.
http://docs.continuum.io/anaconda/index.html
"""
anaconda_dir = os.path.join(args.datadir, "anaconda")
bindir = os.path.join(anaconda_dir, "bin")
conda = os.path.join(bindir... | def install_anaconda_python(args, remotes):
| """Provide isolated installation of Anaconda python for running bcbio-nextgen.
http://docs.continuum.io/anaconda/index.html
"""
anaconda_dir = os.path.join(args.datadir, "anaconda")
bindir = os.path.join(anaconda_dir, "bin")
conda = os.path.join(bindir, "conda")
if not os.path.exists(anacond... | "install", "--yes"] + channels + pkgs)
def _guess_distribution():
"""Simple approach to identify if we are on a MacOSX or Linux system for Anaconda.
"""
if platform.mac_ver()[0]:
return "macosx"
else:
return "linux"
def install_anaconda_python(args, remotes):
| 73 | 73 | 245 | 10 | 63 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | install_anaconda_python | install_anaconda_python | 105 | 123 | 105 | 105 | 2a688a0a37c51d714ed8bc1b7212d0dc8c98e1b0 | bigcode/the-stack | train |
d518ac40b6da9eedcd445a96 | train | function | @contextlib.contextmanager
def bcbio_tmpdir():
orig_dir = os.getcwd()
work_dir = os.path.join(os.getcwd(), "tmpbcbio-install")
if not os.path.exists(work_dir):
os.makedirs(work_dir)
os.chdir(work_dir)
yield work_dir
os.chdir(orig_dir)
shutil.rmtree(work_dir)
| @contextlib.contextmanager
def bcbio_tmpdir():
| orig_dir = os.getcwd()
work_dir = os.path.join(os.getcwd(), "tmpbcbio-install")
if not os.path.exists(work_dir):
os.makedirs(work_dir)
os.chdir(work_dir)
yield work_dir
os.chdir(orig_dir)
shutil.rmtree(work_dir)
| ]
if args.sudo:
cmd.insert(0, "sudo")
subprocess.check_call(cmd)
if args.sudo:
subprocess.check_call(["sudo", "chown", "-R", os.environ["USER"], args.datadir])
@contextlib.contextmanager
def bcbio_tmpdir():
| 64 | 64 | 76 | 13 | 51 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | bcbio_tmpdir | bcbio_tmpdir | 180 | 189 | 180 | 181 | ce72b7a6ee81fe6e1bc48c2b2daf07d3baf44438 | bigcode/the-stack | train |
6cecef3088942354e97ccda3 | train | function | def check_dependencies():
"""Ensure required tools for installation are present.
"""
print("Checking required dependencies")
try:
subprocess.check_call(["git", "--version"])
except OSError:
raise OSError("bcbio-nextgen installer requires Git (http://git-scm.com/)")
| def check_dependencies():
| """Ensure required tools for installation are present.
"""
print("Checking required dependencies")
try:
subprocess.check_call(["git", "--version"])
except OSError:
raise OSError("bcbio-nextgen installer requires Git (http://git-scm.com/)")
| = os.getcwd()
work_dir = os.path.join(os.getcwd(), "tmpbcbio-install")
if not os.path.exists(work_dir):
os.makedirs(work_dir)
os.chdir(work_dir)
yield work_dir
os.chdir(orig_dir)
shutil.rmtree(work_dir)
def check_dependencies():
| 64 | 64 | 63 | 4 | 60 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | check_dependencies | check_dependencies | 191 | 198 | 191 | 191 | 7277458a6036d2742dff1d8b963e67506e98529a | bigcode/the-stack | train |
3fc805d543e036de96c9eb62 | train | function | def _guess_distribution():
"""Simple approach to identify if we are on a MacOSX or Linux system for Anaconda.
"""
if platform.mac_ver()[0]:
return "macosx"
else:
return "linux"
| def _guess_distribution():
| """Simple approach to identify if we are on a MacOSX or Linux system for Anaconda.
"""
if platform.mac_ver()[0]:
return "macosx"
else:
return "linux"
| -c", "https://conda.binstar.org/bcbio"]
subprocess.check_call([anaconda["conda"], "install", "--yes", "numpy"])
subprocess.check_call([anaconda["conda"], "install", "--yes"] + channels + pkgs)
def _guess_distribution():
| 63 | 64 | 51 | 5 | 58 | nuin/bcbio-nextgen | scripts/bcbio_nextgen_install.py | Python | _guess_distribution | _guess_distribution | 97 | 103 | 97 | 97 | d8c72eea08022f3e0302950cc907e333076cd4d2 | bigcode/the-stack | train |
246c628f6995cf68cb60d6b8 | train | class | class Payload:
def __init__(self, url=None):
self.url = url
| class Payload:
| def __init__(self, url=None):
self.url = url
| class Payload:
| 3 | 64 | 19 | 3 | 0 | DL4PD/glouton-satnogs-data-downloader | glouton/domain/payload/payload.py | Python | Payload | Payload | 1 | 3 | 1 | 1 | 792d72f64ba50d557d3ba9a75549e3d57e31e1a3 | bigcode/the-stack | train |
d9a971871a225b2797ed53ea | train | class | class TestAutoCStruct:
"""
Testing class for the autocstruct directive
"""
my_struct_type = """\
struct my_struct_type
A struct that is actually anonymouse but is typedefed in place.
int bar
The bar like member for bar like things. This is multiple lines to make
... | class TestAutoCStruct:
| """
Testing class for the autocstruct directive
"""
my_struct_type = """\
struct my_struct_type
A struct that is actually anonymouse but is typedefed in place.
int bar
The bar like member for bar like things. This is multiple lines to make
sure the parsing logic... | """
Test autoctype directive
"""
from textwrap import dedent
import pytest
from sphinx.ext.autodoc.directive import AutodocDirective
class TestAutoCStruct:
| 37 | 198 | 661 | 6 | 30 | speedyleion/sphinx-c-doc | tests/directives/test_autocstruct.py | Python | TestAutoCStruct | TestAutoCStruct | 11 | 115 | 11 | 11 | 6ba952a25a8e3aca52b3dce12eee4e4ea399033e | bigcode/the-stack | train |
08468217c164c101a724b56a | train | class | class SharedObjects:
"""Various common components for use in games.
Category: Gameplay Classes
Objects contained here are created on-demand as accessed and shared
by everything in the current activity. This includes things such as
standard materials.
"""
_STORENAME = ba.storagename()
... | class SharedObjects:
| """Various common components for use in games.
Category: Gameplay Classes
Objects contained here are created on-demand as accessed and shared
by everything in the current activity. This includes things such as
standard materials.
"""
_STORENAME = ba.storagename()
def __init__(self) -... | 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, distribute, sublicense, and/or sell
# copies of the Software, and to permit pe... | 256 | 256 | 1,128 | 4 | 251 | SahandAslani/ballistica | assets/src/ba_data/python/bastd/gameutils.py | Python | SharedObjects | SharedObjects | 33 | 163 | 33 | 33 | 7d6078fd4943a7964fb93a2b749a9a79cd92cd18 | bigcode/the-stack | train |
4091df5f98a311525e830f43 | train | function | @app.route("/debug/database_contents", methods=["GET"])
def debug_database_contents() -> Dict:
# Get all database contents
# jsonify
return {} | @app.route("/debug/database_contents", methods=["GET"])
def debug_database_contents() -> Dict:
# Get all database contents
# jsonify
| return {} | Dict
from api import app
@app.route("/debug/test_message", methods=["GET"])
def test_message() -> Dict:
return {"message": "hello world"}
@app.route("/debug/database_contents", methods=["GET"])
def debug_database_contents() -> Dict:
# Get all database contents
# jsonify
| 64 | 64 | 33 | 30 | 34 | spark-c/UI-Test | api/routes.py | Python | debug_database_contents | debug_database_contents | 10 | 14 | 10 | 13 | dde8c98d373dc7b3ef637301d1312022e2ee426f | bigcode/the-stack | train |
97e4095c5318be5553836d6a | train | function | @app.route("/debug/test_message", methods=["GET"])
def test_message() -> Dict:
return {"message": "hello world"}
| @app.route("/debug/test_message", methods=["GET"])
def test_message() -> Dict:
| return {"message": "hello world"}
| from typing import Dict
from api import app
@app.route("/debug/test_message", methods=["GET"])
def test_message() -> Dict:
| 28 | 64 | 27 | 18 | 9 | spark-c/UI-Test | api/routes.py | Python | test_message | test_message | 6 | 8 | 6 | 7 | 41e25135090a37ec1dc9c395ee1490b6ea887e00 | bigcode/the-stack | train |
9ca1e55696f15d0990662fbb | train | class | class LeastTests(TestCase):
def test_basic(self):
now = timezone.now()
before = now - timedelta(hours=1)
Article.objects.create(title='Testing with Django', written=before, published=now)
articles = Article.objects.annotate(first_updated=Least('written', 'published'))
self.a... | class LeastTests(TestCase):
| def test_basic(self):
now = timezone.now()
before = now - timedelta(hours=1)
Article.objects.create(title='Testing with Django', written=before, published=now)
articles = Article.objects.annotate(first_updated=Least('written', 'published'))
self.assertEqual(articles.first().f... | from datetime import datetime, timedelta
from decimal import Decimal
from unittest import skipIf, skipUnless
from django.db import connection
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce, Least
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
fro... | 90 | 222 | 743 | 6 | 83 | imjvdn/scratch-game-1 | tests/db_functions/comparison/test_least.py | Python | LeastTests | LeastTests | 14 | 93 | 14 | 15 | f58a6857feedb8e527ce4eaf7e6ec63e6802ee75 | bigcode/the-stack | train |
31b3cc1d5a3ae360f8e9d4ae | train | class | class Mynet(torch.nn.Module):
def __init__(self):
super(Mynet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 96, kernel_size=7, padding=1, stride=2)
self.conv2 = torch.nn.Conv2d(96, 256, kernel_size=5, padding=1, stride=2)
self.conv3 = torch.nn.Conv2d(256, 384, kernel_size=3, padd... | class Mynet(torch.nn.Module):
| def __init__(self):
super(Mynet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 96, kernel_size=7, padding=1, stride=2)
self.conv2 = torch.nn.Conv2d(96, 256, kernel_size=5, padding=1, stride=2)
self.conv3 = torch.nn.Conv2d(256, 384, kernel_size=3, padding=1)
self.conv4 = to... | import torch
import torch.nn.functional as F
import argparse
import cv2
import numpy as np
from glob import glob
num_classes = 2
img_height, img_width = 224, 224
GPU = False
torch.manual_seed(0)
class Mynet(torch.nn.Module):
| 62 | 125 | 418 | 7 | 55 | KuKuXia/DeepLearningMugenKnock | Question_model/answers/zfnet_pytorch.py | Python | Mynet | Mynet | 13 | 42 | 13 | 13 | 306eefa82112632df7b9b9482d6382b03146763b | bigcode/the-stack | train |
d69d68b71583cd67391669ca | train | function | def arg_parse():
parser = argparse.ArgumentParser(description='CNN implemented with Keras')
parser.add_argument('--train', dest='train', action='store_true')
parser.add_argument('--test', dest='test', action='store_true')
args = parser.parse_args()
return args
| def arg_parse():
| parser = argparse.ArgumentParser(description='CNN implemented with Keras')
parser.add_argument('--train', dest='train', action='store_true')
parser.add_argument('--test', dest='test', action='store_true')
args = parser.parse_args()
return args
| axis=0)
x = torch.tensor(x, dtype=torch.float).to(device)
pred = model(x)
pred = F.softmax(pred, dim=1).detach().cpu().numpy()[0]
print("in {}, predicted probabilities >> {}".format(path, pred))
def arg_parse():
| 63 | 64 | 61 | 4 | 59 | KuKuXia/DeepLearningMugenKnock | Question_model/answers/zfnet_pytorch.py | Python | arg_parse | arg_parse | 159 | 164 | 159 | 159 | 74f8a9c4121cf5cae612a34cb9c1f6902434a77f | bigcode/the-stack | train |
58b9a8bd8fcbee79f9a4ce1d | train | function | def train():
# GPU
device = torch.device("cuda" if GPU else "cpu")
# model
model = Mynet().to(device)
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
model.train()
xs, ts, paths = data_load('../Dataset/train/images/', hf=True, vf=True)
# training
mb = 16
mbi = ... | def train():
# GPU
| device = torch.device("cuda" if GPU else "cpu")
# model
model = Mynet().to(device)
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
model.train()
xs, ts, paths = data_load('../Dataset/train/images/', hf=True, vf=True)
# training
mb = 16
mbi = 0
train_ind = np.ar... | if vf:
xs.append(x[::-1])
ts.append(t)
paths.append(path)
if hf and vf:
xs.append(x[::-1, ::-1])
ts.append(t)
paths.append(path)
xs = np.array(xs, dtype=np.float32)
ts = np.array(ts, dtype=np.int)
... | 103 | 103 | 344 | 7 | 95 | KuKuXia/DeepLearningMugenKnock | Question_model/answers/zfnet_pytorch.py | Python | train | train | 92 | 134 | 92 | 93 | 4858fd9397b064f882035c0a5adbc351c510e065 | bigcode/the-stack | train |
1a0380bbb43a84153e2f357e | train | function | def test():
device = torch.device("cuda" if GPU else "cpu")
model = Mynet().to(device)
model.eval()
model.load_state_dict(torch.load('cnn.pt'))
xs, ts, paths = data_load('../Dataset/test/images/')
for i in range(len(paths)):
x = xs[i]
t = ts[i]
path = paths[i]
... | def test():
| device = torch.device("cuda" if GPU else "cpu")
model = Mynet().to(device)
model.eval()
model.load_state_dict(torch.load('cnn.pt'))
xs, ts, paths = data_load('../Dataset/test/images/')
for i in range(len(paths)):
x = xs[i]
t = ts[i]
path = paths[i]
x = ... | =1, keepdim=True)
acc = pred.eq(t.view_as(pred)).sum().item() / mb
print("iter >>", i+1, ',loss >>', loss.item(), ',accuracy >>', acc)
torch.save(model.state_dict(), 'cnn.pt')
# test
def test():
| 64 | 64 | 150 | 3 | 60 | KuKuXia/DeepLearningMugenKnock | Question_model/answers/zfnet_pytorch.py | Python | test | test | 137 | 156 | 137 | 137 | 38ae44fa6fc1f4fe666fb35da6493b0371cc572f | bigcode/the-stack | train |
74d9609e1cdb152090a6f342 | train | function | def data_load(path, hf=False, vf=False):
xs = []
ts = []
paths = []
for dir_path in glob(path + '/*'):
for path in glob(dir_path + '/*'):
x = cv2.imread(path)
x = cv2.resize(x, (img_width, img_height)).astype(np.float32)
x /= 255.
xs.append(x)... | def data_load(path, hf=False, vf=False):
| xs = []
ts = []
paths = []
for dir_path in glob(path + '/*'):
for path in glob(dir_path + '/*'):
x = cv2.imread(path)
x = cv2.resize(x, (img_width, img_height)).astype(np.float32)
x /= 255.
xs.append(x)
for i, cls in enumerate(CLS... | ))
x = torch.nn.Dropout()(x)
x = F.relu(self.fc2(x))
x = torch.nn.Dropout()(x)
x = self.fc_out(x)
return x
CLS = ['akahara', 'madara']
# get train data
def data_load(path, hf=False, vf=False):
| 69 | 69 | 233 | 11 | 57 | KuKuXia/DeepLearningMugenKnock | Question_model/answers/zfnet_pytorch.py | Python | data_load | data_load | 48 | 88 | 48 | 48 | ee9ba5529ba1497afe58218f227a36db97d0605c | bigcode/the-stack | train |
e53910279c5ee6814a0e8e0f | train | function | @login_required
def settings():
return render_template('settings.html') | @login_required
def settings():
| return render_template('settings.html') | Flask imports
from flask import render_template
from flask_login import login_required
# Third-party imports
# App imports
def index():
return render_template('index.html')
def register():
return render_template('register.html')
def login():
return render_template('login.html')
@login_required
def se... | 64 | 64 | 14 | 6 | 58 | nuvic/flask_for_startups | flask_for_startups/views/static_views.py | Python | settings | settings | 21 | 23 | 21 | 22 | 3d9485a5b2eb7b9ffe034112ee6bf5a1d0cdaa9f | bigcode/the-stack | train |
1c78322bec157175253cd36f | train | function | def index():
return render_template('index.html')
| def index():
| return render_template('index.html')
| # Standard Library imports
# Core Flask imports
from flask import render_template
from flask_login import login_required
# Third-party imports
# App imports
def index():
| 35 | 64 | 11 | 3 | 31 | nuvic/flask_for_startups | flask_for_startups/views/static_views.py | Python | index | index | 12 | 13 | 12 | 12 | 761a6ba1ba10c661054a0cc1ab37fdc2f7f54825 | bigcode/the-stack | train |
f6fe6eb81e7f1a42eff6c368 | train | function | def register():
return render_template('register.html')
| def register():
| return render_template('register.html')
| # Standard Library imports
# Core Flask imports
from flask import render_template
from flask_login import login_required
# Third-party imports
# App imports
def index():
return render_template('index.html')
def register():
| 46 | 64 | 11 | 3 | 43 | nuvic/flask_for_startups | flask_for_startups/views/static_views.py | Python | register | register | 15 | 16 | 15 | 15 | ca7c440c44bb95642960d50d6bd5bb89aaad6f8f | bigcode/the-stack | train |
a4693c7f2996549bb0d70e04 | train | function | def login():
return render_template('login.html')
| def login():
| return render_template('login.html')
| # Standard Library imports
# Core Flask imports
from flask import render_template
from flask_login import login_required
# Third-party imports
# App imports
def index():
return render_template('index.html')
def register():
return render_template('register.html')
def login():
| 57 | 64 | 11 | 3 | 54 | nuvic/flask_for_startups | flask_for_startups/views/static_views.py | Python | login | login | 18 | 19 | 18 | 18 | 18131c09ac7659bd56429ff7d9fb5052f67a39f6 | bigcode/the-stack | train |
8634ab508bc2ae6fd55bb02f | train | class | class RemoveBot(Client):
def on_text(self, thread, author, text, mentions):
# We can only kick people from group chats, so no need to try if it's a
# user chat
if text == "Remove me!" and isinstance(thread, Group):
print("{.name} asked to be removed from {.name}".format(author, t... | class RemoveBot(Client):
| def on_text(self, thread, author, text, mentions):
# We can only kick people from group chats, so no need to try if it's a
# user chat
if text == "Remove me!" and isinstance(thread, Group):
print("{.name} asked to be removed from {.name}".format(author, thread))
self.... | # -*- coding: UTF-8 -*-
from fbchat import *
class RemoveBot(Client):
| 18 | 64 | 85 | 5 | 13 | alexwilson1/fbchat | examples/remove_bot.py | Python | RemoveBot | RemoveBot | 6 | 12 | 6 | 6 | cf7065207a470dc5470d87306af19ae699a88afc | bigcode/the-stack | train |
0ca0ae661256b1e1037d7d42 | train | function | def add(num):
global result
result+=num
return result
| def add(num):
| global result
result+=num
return result
| result=0
def add(num):
| 8 | 64 | 17 | 4 | 3 | choijiwoong/-ROKA-torch-tutorial-files | 3. Linear Regresion/3-4)class.py | Python | add | add | 3 | 6 | 3 | 3 | 1febb0b12901d9e0c4fd01523b6e3e11070a3610 | bigcode/the-stack | train |
b2c79da9360abdf5915ed73a | train | function | def readme():
with open('README.md') as file:
return file.read()
| def readme():
| with open('README.md') as file:
return file.read()
| from setuptools import setup
# access readme for long description
def readme():
| 17 | 64 | 19 | 4 | 12 | hoangnv-bkhn/grive | setup.py | Python | readme | readme | 5 | 7 | 5 | 5 | 333f2168dc29d8124f188067b7b279c527a5596f | bigcode/the-stack | train |
364a114d5d005b75c376665c | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding M2M table for field sections on 'SessionKind'
m2m_table_name = db.shorten_name(u'conference_sessionkind_sections')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, a... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding M2M table for field sections on 'SessionKind'
m2m_table_name = db.shorten_name(u'conference_sessionkind_sections')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('s... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 37 | 256 | 1,488 | 6 | 30 | EuroPython/djep | pyconde/conference/migrations/0009_auto.py | Python | Migration | Migration | 8 | 98 | 8 | 9 | ef93ac828235d572a4d468e2f415b0d17a581efb | bigcode/the-stack | train |
907cc27cd0668cb3c29a202f | train | function | def get_performance_comparisons(base_branch, commit_sha):
""" Compare the performance results from two branches. This returns an array of tuples. The first item in the tuple
is the OLTPBench config, the second item in the tuple is the % difference in throughput, the third item in the
tuple is the master bra... | def get_performance_comparisons(base_branch, commit_sha):
| """ Compare the performance results from two branches. This returns an array of tuples. The first item in the tuple
is the OLTPBench config, the second item in the tuple is the % difference in throughput, the third item in the
tuple is the master branch throughput, and the fourth item in the tuple is the co... | details]
table_content.append(row)
if len(table_content):
table_text = tabulate(table_content, headers=table_headers, tablefmt='github')
else:
table_text = '**Could not find any performance results to compare for this commit.**'
return description_text + ta... | 76 | 76 | 254 | 13 | 62 | cmu-db/noisepage-stats | performance-storage-service/pss_project/api/github_integration/PerformanceGuardBot.py | Python | get_performance_comparisons | get_performance_comparisons | 100 | 119 | 100 | 100 | 258153223ee9521ea68e9a63e7e977e42ee06a6b | bigcode/the-stack | train |
db86d3c42337b023a988e565 | train | function | def generate_performance_result_markdown(performance_comparisons):
""" Generate the markdown content that will show up in the detailed view of the check run. This includes a short
description and a table displaying the OLTPBench test config and results. """
description_text = ("This performance comparison i... | def generate_performance_result_markdown(performance_comparisons):
| """ Generate the markdown content that will show up in the detailed view of the check run. This includes a short
description and a table displaying the OLTPBench test config and results. """
description_text = ("This performance comparison is based on the performance results collected from the most"
... | def get_min_performance_change(performance_comparisons):
""" Determine the worst performance difference between the master branch and the PR's branch and then determine
the corresponding conclusion status. """
min_performance_change = 0
for _, percent_diff, _, _ in performance_comparisons:
if p... | 101 | 101 | 339 | 13 | 87 | cmu-db/noisepage-stats | performance-storage-service/pss_project/api/github_integration/PerformanceGuardBot.py | Python | generate_performance_result_markdown | generate_performance_result_markdown | 134 | 158 | 134 | 134 | ec0512b29c83c452f57931ee772c57228ff670c8 | bigcode/the-stack | train |
68fc00a7160cee11c3207538 | train | function | def generate_details_table_cell(config, master_throughput, commit_throughput):
config_details_str = ", ".join(["=".join([key, str(val)]) for key, val in config.items()])
return f'<details><summary>Details</summary>master tps={round(master_throughput,2)},' \
f' commit tps={round(commit_throughput,2)},... | def generate_details_table_cell(config, master_throughput, commit_throughput):
| config_details_str = ", ".join(["=".join([key, str(val)]) for key, val in config.items()])
return f'<details><summary>Details</summary>master tps={round(master_throughput,2)},' \
f' commit tps={round(commit_throughput,2)}, {config_details_str}</details>'
| _text = tabulate(table_content, headers=table_headers, tablefmt='github')
else:
table_text = '**Could not find any performance results to compare for this commit.**'
return description_text + table_text
def generate_details_table_cell(config, master_throughput, commit_throughput):
| 64 | 64 | 90 | 17 | 46 | cmu-db/noisepage-stats | performance-storage-service/pss_project/api/github_integration/PerformanceGuardBot.py | Python | generate_details_table_cell | generate_details_table_cell | 161 | 164 | 161 | 161 | 1621ed27c671e82b3780986e90f137da932a8812 | bigcode/the-stack | train |
01bf08f6d5aeda72bc728289 | train | function | def get_min_performance_change(performance_comparisons):
""" Determine the worst performance difference between the master branch and the PR's branch and then determine
the corresponding conclusion status. """
min_performance_change = 0
for _, percent_diff, _, _ in performance_comparisons:
if p... | def get_min_performance_change(performance_comparisons):
| """ Determine the worst performance difference between the master branch and the PR's branch and then determine
the corresponding conclusion status. """
min_performance_change = 0
for _, percent_diff, _, _ in performance_comparisons:
if percent_diff < min_performance_change:
min_per... | comparison = (config,
percent_diff,
float(m_result.metrics.get('throughput', 0)),
float(c_result.metrics.get('throughput', 0)))
result_comparisons.append(comparison)
return result_comparisons
de... | 64 | 64 | 88 | 12 | 51 | cmu-db/noisepage-stats | performance-storage-service/pss_project/api/github_integration/PerformanceGuardBot.py | Python | get_min_performance_change | get_min_performance_change | 122 | 131 | 122 | 122 | eb2fa48dcd9f0fbd5534638c9b9be3e6c1d8738a | bigcode/the-stack | train |
f0618b60769e7e318cc74eaf | train | class | class PerformanceGuardBot(BasePRBot):
""" This PR Bot is initialized in a queued stated. It waits for the CI pipeline to
complete. When the CI pipeline completes it fetches the latest performance results
for the commit. Then it compares the performance results with the most recent
nightly performance re... | class PerformanceGuardBot(BasePRBot):
| """ This PR Bot is initialized in a queued stated. It waits for the CI pipeline to
complete. When the CI pipeline completes it fetches the latest performance results
for the commit. Then it compares the performance results with the most recent
nightly performance results. The results are organized into ... | from tabulate import tabulate
import logging
from pss_project.api.github_integration.BasePRBot import (BasePRBot, CONCLUSION_SUCCESS, CONCLUSION_NEUTRAL,
CONCLUSION_FAILURE)
from pss_project.api.models.database.OLTPBenchResult import OLTPBenchResult
from pss_pr... | 85 | 226 | 756 | 8 | 77 | cmu-db/noisepage-stats | performance-storage-service/pss_project/api/github_integration/PerformanceGuardBot.py | Python | PerformanceGuardBot | PerformanceGuardBot | 12 | 97 | 12 | 12 | f3563de6cf9b046639cad6da9f0e6cbdaaced7fb | bigcode/the-stack | train |
2b0ad5967a9429c4143aa5a7 | train | class | class StreamToLogger(object):
def __init__(self, logger):
self.logger = logger
def __getattr__(self, name):
return getattr(sys.__stdout__, name)
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.info(line.rstrip())
sys.__stdout__.write(buf... | class StreamToLogger(object):
| def __init__(self, logger):
self.logger = logger
def __getattr__(self, name):
return getattr(sys.__stdout__, name)
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.info(line.rstrip())
sys.__stdout__.write(buf)
| import sys
class StreamToLogger(object):
| 9 | 64 | 72 | 6 | 2 | iopipe/iopipe-python | iopipe/contrib/logger/stream.py | Python | StreamToLogger | StreamToLogger | 4 | 14 | 4 | 4 | 16dea9d340df1407dfe5c58388a909dea388ce1d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.